I need to map the form data into a pojo, so ii set the POJO as a method parameter. So then request data should bind to the pojo. But it not working. I am using spring 4.2.3.RELEASE
. This is the my code
public class PersonDto {
private int userId;
private String userName;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
@Controller()
@RequestMapping("/u")
public class UserController {
@ResponseBody
@RequestMapping(value = "/add",method = RequestMethod.POST)
public String addUser(PersonDto dto){
System.out.println("Name : "+dto.getUserName());
return ""+dto.getUserName();
}
@RequestMapping("/home")
public String userHome(){
System.out.println("UserDetailsController Index");
return "user-home";
}
}
in here home request mapping is working. But when i send post request to /add
then PersonDto is empty. This is how i send request What is the reason for this?
您需要在方法参数中使用@RequestBody注释PersonDto dto,以指示它应绑定到请求主体:
public String addUser(@RequestBody PersonDto dto){
try this options:
Use @RequestBody in POST method.
include maven dependency for jackson
com.fasterxml.jackson.databind.ObjectMapper
Try to mark your method parameter with @ModelAttribute
annotation:
@ResponseBody
@RequestMapping(value = "/add",method = RequestMethod.POST)
public String addUser(@ModelAttribute("dto") PersonDto dto){
System.out.println("Name : "+dto.getUserName());
return ""+dto.getUserName();
}
Note, that you can specify name of model attribute. If you use <spring:form>
tag check you form modelAttribute
attribute:
<form:form method="POST" action="/someaction" modelAttribute="dto">
...
</form:form>
I might be pretty late to the party, but if this issue is not yet resolved (since I don't see any accepted answer), this answer may help. I had a similar issue and realised that I had not added a constructor wherein all the parameters passed in request body could be set. So perhaps adding the following constructor:
public PersonDto(int userId, String userName){
this.userId=userId;
this.userName=userName;
}
Please let me know if this works for you. If something else already did, please share your answer since it was quite a task for me to realise my silly error.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.