Reputation: 41
I have this problem where I call API with get and it works fine while it gives empty object in case of POST. Below are the code snippets.
@Controller
@RequestMapping("/demo")
public class DemoController {
@RequestMapping(value = "/create")
public ModelAndView createUser(@ModelAttribute User user) {
...
...
}
}
GET: localhost:8080/demo/create.json?name=test&title=this works fine POST using form-data is not working. I am getting empty object.
public class User implements Serializable {
private String name;
private String title;
...
}
Upvotes: 1
Views: 5770
Reputation: 41
Thanks for your kind replies. I was using Postman to validate my controller. I found I need to add multipart resolver.
Below is the line that fixed it.
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
Thanks!
Upvotes: 0
Reputation: 463
I would suggest the following code.
@RequestMapping(value = "/create", method = RequestMethod.GET)
public ModelAndView createUser() {
ModelAndView modelAndView = new ModelAndView("/createuser.jsp");
modelAndView.addObject("user", new User());
return modelAndView;
}
@RequestMapping(value = "/create", method = RequestMethod.POST)
public ModelAndView createUserProcess(@ModelAttribute("user") User user,) {
// save user to db
}
Just out of curiosity. Shouldn't you be displaying the form with createUser and processing it with createUserProcess? Also make sure your form has the following:
<form:form commandName="user" modelAttribute="user">
</form:form>
Upvotes: 1