开发者

Spring MVC 2.5 form backing object using @modelAttribute

@RequestMapping(method = RequestMethod.GET)
public String setupForm(@RequestParam("username") String username, ModelMap model, HttpServletRequest request) {
    User userFromDB = userService.getUser(username);
    UserPersonalDetails userDetails = userService.getUserPersonalDetails(username);
    UserBackingObject user = new UserBackingObject(userDetails.getFirstName() + " " + userDetails.getLastName(), username, userDetails.getEmail(), userDetails.getTelephone());
    model.addAttribute("user", user);

    return EDIT_USER_VIEW;
}


@RequestMapping(method = RequestMethod.POST, params="save")
public String processSave(@ModelAttribute("user") UserBackingObject user, BindingResult result, ModelMap model, HttpServletRequest request) {


    return LISTUSERS_VIEW;
}

in the form jsp, I'm only displaying user details(can't be edited or altered) and I have submit but开发者_如何学Cton.

when I debug the post method, user object ( UserBackingObject) only has username and the rest of the fields are null.I don't understand why this happen even though I've created the user object and added to the model in the 'get' method. so why its not showing email or phone number in the post method? the purpose of the backing object is to send and receive? could someone explain clearly please


Spring MVC follows a stateless approach. It means that (by default) Spring doesn't store any state of the conversation with a particular user on the server between requests.

Therefore the instance of UserBackingObject you get in the POST method is not the same instance that you added to the model in the GET method. The UserBackingObject you get in the POST method is reconstructed from HTTP parameters of the POST method, that is from the values of form fields. It means that only the properties that have corresponding fields in your HTML page will be populated.

If you need, you can override this default behaviour by using @SessionAttributes annotation.

So, you can either add additional fields (possibly hidden) to the form or store model attributes in the session using @SessionAttributes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜