Search code examples
springmavenposthttp-status-code-405

Spring Controller 405 errors for POST request


I'm following this Tutorial. It had a build error which I fixed by adding the following code in the POM.xml

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
     <artifactId>maven-war-plugin</artifactId>
     <version>2.3</version>
     <configuration>
          <failOnMissingWebXml>false</failOnMissingWebXml>
    </configuration>
</plugin>

The project is working fine as expected. Now I added a simple form which sends a post request to the controller. The search page looks like this

<form name='SearchForm' action="<c:url value='/search' />" method='POST'>
    <center>Search By Name : <input type="text" name="name" id="name" /><input type="Submit" name="action" value="Search"> </td></center>
</form>

The controller looks like this (Even when I hard code the search parameter, the request does not reach the controller)

@ResponseBody
@RequestMapping(value="/search" , method=RequestMethod.POST)
public ModelAndView searchUser(HttpServletRequest request, HttpServletResponse response){

    ModelAndView model = new ModelAndView("searchPage");
    model.addObject("userDTOList", userService.searchUser("sam"));
    return model;
}

I have the relevant service and modal and DAO classes to do a retrieval. If I change the request to be GET, it works as expected. But when I try POST method, I get 405 exception.

HTTP Status 405 - Request method 'POST' not supported

What am I doing wrong in this? Thanks in advance


Solution

  • The tutorial uses springSecurityFilterChain with CSRF protection configured and Spring Security 3.2.3 so add the following to your searchpage.html:

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