Spring Boot form submission works with a get but not a post

Viewed 26

I am trying to submit a form to a controller. On the page this is simply:

code

<form action="http://localhost:8080/form/submit" method="post">

    <button type="submit">Submit</button>
</form>

code

On the controller I have the following handler:

code

@RequestMapping(value = "/form/submit", method = RequestMethod.POST, produces = MediaType.APPLICATION_XHTML_XML_VALUE)
@ResponseBody
public String submitForm(HttpServletRequest request) {
    
    String baseUrl = getBaseUrl(request);
    
    TestForm testForm = new TestForm();
    
    log.info("form submitted");
    
    return formService.generate("test", baseUrl, testForm);
}

code

When I submit the form it gives me a 404 not found error. Yet if I change this to GET instead of POST it works fine.

I am using Spring Security where I have allowed requests to this controller.

code

.antMatchers("/form/**").authenticated()

code

Is there any reason why this would work for GET but not POST?

1 Answers

I fixed the issue: it has to do with Spring Security and CSRF. You can disable CSRF in Spring Security or add a CSRF parameter to the form.

code

<form th:action="${baseUrl + '/form/submit'}" method="post" th:object="${testForm}">
    <input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}" />

code

I was generating my own page separate from Spring so this applies specifically to this case.

Related