[java] HTTP Status 405 - Request method 'POST' not supported (Spring MVC)

Im getting this error: HTTP Status 405 - Request method 'POST' not supported

What I am trying to do is make a form with a drop down box that get populated based on the other value selected in another drop down box. For example when I select a name in the customerName box the onChange function in the .jsp page should be run and the page submitted then loaded again with the corresponding values in the customerCountry box.

however I'm getting this HTTP Status 405 error. I have searched the internet for a solution but haven't been able to find anything that helped. Here is the relevant parts of my code:

part of jsp page

<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>

part of controller:

@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";
        }

    }

How come I get this error? Any help would be much appreciated! Thanks

EDIT: Changed hasId to hasCustomerName. I still get the HTTP Status 405 - Request method 'POST' not supported error though.

EDIT2: Commented out the line in the setFalse function that was causing the error

// D

This question is related to java javascript spring hibernate methods

The answer is


I was getting similar problem for other reason (url pattern test-response not added in csrf token) I resolved it by allowing my URL pattern in following property in config/local.properties:

csrf.allowed.url.patterns = /[^/]+(/[^?])+(sop-response)$,/[^/]+(/[^?])+(merchant_callback)$,/[^/]+(/[^?])+(hop-response)$

modified to

csrf.allowed.url.patterns = /[^/]+(/[^?])+(sop-response)$,/[^/]+(/[^?])+(merchant_callback)$,/[^/]+(/[^?])+(hop-response)$,/[^/]+(/[^?])+(test-response)$


You might need to change the line

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

to

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

The problem is that your controller expect a parameter hasId=false or hasId=true, but you are not passing that. Your hidden field has the id hasId but is passed as hasCustomerName, so no mapping matches.

Either change the path of the hidden field to hasId or the mapping parameter to expect hasCustomerName=true or hasCustomerName=false.


Check if you are returning a @ResponseBody or a @ResponseStatus

I had a similar problem. My Controller looked like that:

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

When calling with a POST request I always got the following error:

HTTP Status 405 - Request method 'POST' not supported

After a while I figured out that the method was actually called, but because there is no @ResponseBody and no @ResponseStatus Spring MVC raises the error.

To fix this simply add a @ResponseBody

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

or a @ResponseStatus to your method.

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

I am not sure if this helps but I had the same problem.

You are using springSecurityFilterChain with CSRF protection. That means you have to send a token when you send a form via POST request. Try to add the next input to your form:

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

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to spring

Are all Spring Framework Java Configuration injection examples buggy? Two Page Login with Spring Security 3.2.x Access blocked by CORS policy: Response to preflight request doesn't pass access control check Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified Spring Data JPA findOne() change to Optional how to use this? After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName The type WebMvcConfigurerAdapter is deprecated No converter found capable of converting from type to type

Examples related to hibernate

Hibernate Error executing DDL via JDBC Statement How does spring.jpa.hibernate.ddl-auto property exactly work in Spring? Error creating bean with name 'entityManagerFactory' defined in class path resource : Invocation of init method failed JPA Hibernate Persistence exception [PersistenceUnit: default] Unable to build Hibernate SessionFactory Disable all Database related auto configuration in Spring Boot Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment] HikariCP - connection is not available Hibernate-sequence doesn't exist How to find distinct rows with field in list using JPA and Spring? Spring Data JPA and Exists query

Examples related to methods

String method cannot be found in a main class method Calling another method java GUI ReactJS - Call One Component Method From Another Component multiple conditions for JavaScript .includes() method java, get set methods includes() not working in all browsers Python safe method to get value of nested dictionary Calling one method from another within same class in Python TypeError: method() takes 1 positional argument but 2 were given Android ListView with onClick items