My Spring Boot project has a form at /albums/add
which looks like this:
<form method="post">
<input type="text" name="albumName"/>
<input type="submit" value="Add album"/>
</form>
I'm trying to deal with that request in the controller below:
@Controller
@RequestMapping(value = "/albums")
public class AlbumController {
(...)
@PostMapping("/add")
public String processAddAlbumForm(@RequestParam String albumName) {
albums.add(albumName);
return "redirect:";
}
}
However, Spring throws a 400 and tells me "Required String parameter 'albumName' is not present".
If I view the Network tab in my browser, I can see the request arrive with a value for albumName under the "Form Data" header, where the @RequestParam
annotation can't seem to find it.
My code is copied directly from this tutorial, but I'm worried something might have deprecated since it was made - any ideas?
@RequestParam
is used to retrieve parameters from the URL, but it also works to retrieve the parameter from an HTTP POST request and your code is working just fine on my local. What I see is that I'm being sent to a white label error page, is this the error you are referring to? In any case I cannot see any 500 being returned or any exception in the log. If you add the @ResponseBody
annotation you will be able to send a string in the body of your response:
@PostMapping("/add")
@ResponseBody
public String processAddAlbumForm(@RequestParam String albumName) {
albums.add(albumName);
return "redirect:";
}
If you want to avoid using @ResponseBody
in each method you could use @RestController
instead of @Controller
which is going to assume @ResponseBody
by default.
The html I used to test the endpoint is the following, copied your piece of html and added the action
property to specify the endpoint of my application:
<form action="http://localhost:8080/albums/add" method="post">
<input type="text" name="albumName"/>
<input type="submit" value="Add album"/>
</form>
The @RequestBody
annotation is usually used when you are passing information in the body of your post request, usually in json format. In that case your form will have to send a json string like {"albumName": "my amazing album"}
.
UPDATE
So, I've checked out your repository and it's actually not working. Adding the following dependency to your pom.xml
is making the code I suggested working just fine:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>