Search code examples
javaspringsessionspring-mvcspring-form

Spring MVC - Transferring the same object from one page to other


In my Spring MVC application, I have 2 pages.
I have an object with 10 variables in it. In the first page, I am setting 9 variables of the above object(first page has 9 fields). I set this object in session as well as model attribute in the controller. I also need to pass this same object to the next page. In the second page, I need to set the 10th variable in the same object(second page has only one field 10th field). (why I need a second page for setting the 10th variable is - In the second page, I populate a dropdown based on the entries in the first page)

When I submit the form in the second page - I need to submit the same object with 10 variables. (I couldn't paste the code because of my company policy) Can anyone please help me in fixing this?


Solution

  • Note that both methods are in the same controller. You need to do something like this:

    @Controller
    @SessionAttributes("myObject")
    public class SessionAttributesController {
    
        // Save session attribute in model. 
        @RequestMapping(value = "/page1.html", method = RequestMethod.GET)
        public String page1( @ModelAttribute MyClass myObject, ModelMap model ) {
            model.addtAttribute("myObject", myObject);
            return "page1.html";
        }
    
        // Now you model is having myObject, so it has to be used in jsp. You can add ModelMap parameter to this method and check what contains model in debug mode.   
        @RequestMapping(value = "/page2.html", method = RequestMethod.GET)
        public String page(ModelMap model) {
              model.get("myObject").setAttr10(value);   
              return "page2.html";
        }
    
    }