1
@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 button.

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

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Axtavt, excellent explanation, I have already done the @SeesionAttributes from the springsource site example but I didn't understand it before.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.