Статус HTTP 405 - Метод запроса "POST" не поддерживается (Spring MVC) - программирование
Подтвердить что ты не робот

Статус HTTP 405 - Метод запроса "POST" не поддерживается (Spring MVC)

Im получает эту ошибку: HTTP Status 405 - Request method 'POST' not supported

То, что я пытаюсь сделать, это создать форму с раскрывающимся списком, который будет заполнен на основе другого значения, выбранного в другом раскрывающемся списке. Например, когда я выбираю имя в поле customerName, функция onChange на странице .jsp должна быть запущена, а затем страница снова загружена с соответствующими значениями в поле customerCountry.

однако я получаю эту ошибку HTTP Status 405. Я искал интернет для решения, но не смог найти ничего, что помогло. Вот соответствующие части моего кода:

часть страницы jsp

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Insert title here</title>
            <style>
            .error { color: red; }
            </style>

        <script>
            function repopulate(){  
                document.deliveryForm.submit();
            }

            function setFalse(){
                document.getElementById("hasId").value ="false";
                document.deliveryForm.submit();
                // document.submitForm.submit(); (This was causing the error)

            }
        </script>

    </head>
    <body>

        <h1>Create New Delivery</h1>

        <c:url var="saveUrl" value="/test/delivery/add" />
        <form:form modelAttribute="deliveryDtoAttribute" method="POST" action="${saveUrl}" name="deliveryForm">
            <table>


                <tr>
                    <td><form:hidden id="hasId" path="hasCustomerName" value="true"/></td>
                </tr>

                <tr>
                    <td>Customer Name</td>
                    <td><form:select path="customerName" onChange="repopulate()">
                        <form:option value="" label="--- Select ---" />
                        <form:options items="${customerNameList}" />
                        </form:select>
                    </td>
                    <td><form:errors path="customerName" cssClass="error" /></td>
                </tr>

                <tr>
                    <td>Customer Country</td>
                    <td><form:select path="customerCountry">
                        <form:option value="" label="--- Select ---" />
                        <form:options items="${customerCountryList}" />
                        </form:select>
                    </td>
                    <td><form:errors path="customerCountry" cssClass="error" /></td>
                </tr>

        </form:form>

        <form:form name="submitForm">
        <input type="button" value="Save" onClick="setFalse()"/>
        </form:form>

    </body>
</html>

часть контроллера:

@RequestMapping(value = "/add", method = RequestMethod.GET)
    public String getDelivery(ModelMap model) {
        DeliveryDto deliveryDto = new DeliveryDto();

        model.addAttribute("deliveryDtoAttribute", deliveryDto);
        model.addAttribute("customerNameList",
                customerService.listAllCustomerNames());
        model.addAttribute("customerCountryList", customerService
                    .listAllCustomerCountries(deliveryDto.getCustomerName()));
        return "new-delivery";
    }

    // I want to enter this method if hasId=true which means that a value in the CustomerName 
    // drop down list was selected. This should set the CountryList to the corresponding values 
    // from the database. I want this post method to be triggered by the onChange in the jsp page

    @RequestMapping(value = "/add", method = RequestMethod.POST, params="hasCustomerName=true")
    public String postDelivery(
            @ModelAttribute("deliveryDtoAttribute") DeliveryDto deliveryDto,
            BindingResult result, ModelMap model) {


            model.addAttribute("deliveryDtoAttribute", deliveryDto);

            model.addAttribute("customerNameList",
                    customerService.listAllCustomerNames());
            model.addAttribute("customerCountryList", customerService
                    .listAllCustomerCountries(deliveryDto.getCustomerName()));

            return "new-delivery";
    }

    // This next post method should only be entered if the save button is hit in the jsp page

    @RequestMapping(value = "/add", method = RequestMethod.POST, params="hasCustomerName=false")
    public String postDelivery2(
            @ModelAttribute("deliveryDtoAttribute") @Valid DeliveryDto deliveryDto,
            BindingResult result, ModelMap model) {

        if (result.hasErrors()) {

            model.addAttribute("deliveryDtoAttribute", deliveryDto);

            model.addAttribute("customerNameList",
                    customerService.listAllCustomerNames());
            model.addAttribute("customerCountryList", customerService
                    .listAllCustomerCountries(deliveryDto.getCustomerName()));

            return "new-delivery";
        } else {

            Delivery delivery = new Delivery();

            //Setters to set delivery values

            return "redirect:/mis/home";
        }

    }

Почему я получил эту ошибку? Любая помощь приветствуется! Благодаря

EDIT: Изменено hasId до hasCustomerName. Однако я все равно получаю ошибку HTTP Status 405 - Request method 'POST' not supported.

EDIT2: Прокомментировала строку в функции setFalse, которая вызывала ошибку

//D

4b9b3361

Ответ 1

Я нашел проблему, которая вызывала ошибку HTTP.

В функции setFalse(), которая запускается кнопкой Save, мой код пытался отправить форму, содержащую кнопку.

        function setFalse(){
            document.getElementById("hasId").value ="false";
            document.deliveryForm.submit();
            document.submitForm.submit();

когда я удаляю document.submitForm.submit();, он работает:

        function setFalse(){
            document.getElementById("hasId").value ="false";
            document.deliveryForm.submit()

@Roger Lindsjö Спасибо за то, что вы заметили мою ошибку, когда я не прошел правильный параметр!

Ответ 2

Я не уверен, что это помогает, но у меня была та же проблема.

Вы используете SpringSecurityFilterChain с защитой CSRF. Это означает, что вам нужно отправить токен при отправке формы через запрос POST. Попробуйте добавить следующий вход в форму:

<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>

Ответ 3

Убедитесь, что вы возвращаете @ResponseBody или @ResponseStatus

У меня была аналогичная проблема. Мой контроллер выглядел так:

@RequestMapping(value="/user", method = RequestMethod.POST)
public String updateUser(@RequestBody User user){
    return userService.updateUser(user).getId();
}

При вызове с POST-запросом я всегда получал следующую ошибку:

Статус HTTP 405 - не поддерживается метод запроса POST

Через некоторое время выяснилось, что метод действительно вызван, но поскольку нет @ResponseBody и нет @ResponseStatus Spring MVC вызывает ошибку.

Чтобы исправить это, просто добавьте @ResponseBody

@RequestMapping(value="/user", method = RequestMethod.POST)
public @ResponseBody String updateUser(@RequestBody User user){
    return userService.updateUser(user).getId();
}

или @ResponseStatus для вашего метода.

@RequestMapping(value="/user", method = RequestMethod.POST)
@ResponseStatus(value=HttpStatus.OK)
public String updateUser(@RequestBody User user){
    return userService.updateUser(user).getId();
}

Ответ 4

Проблема в том, что ваш контроллер ожидает, что параметр hasId = false или hasId = true, но вы не передаете это. Ваше скрытое поле имеет id hasId, но передается как hasCustomerName, поэтому сопоставление не соответствует.

Или измените путь скрытого поля на hasId или параметр отображения, чтобы ожидать hasCustomerName = true или hasCustomerName = false.

Ответ 5

Возможно, вам потребуется изменить строку

@RequestMapping(value = "/add", method = RequestMethod.GET)

к

@RequestMapping(value = "/add", method = {RequestMethod.GET,RequestMethod.POST})