Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maintain Model Data between Pages (Spring 3 MVC)

I am having a add Contact process in Spring which will span across multiple pages, First Pages will take text Input, second Page will Take Image input and Third with Display the Draft.

First Page

@RequestMapping("/addContact")
public String registerContact(@ModelAttribute Contact contact) {
 return "addContact";
}
@RequestMapping("/addContact")

Second Page

@RequestMapping("/addImages")
public String registerImages(@Valid Contact contact, BindingResult result) {
 return "addImages";
}

How can I maintain contact model data between the pages so that, I can give option to user to move back and froth between the pages?

like image 444
Tushar Avatar asked Sep 13 '13 08:09

Tushar


2 Answers

If you have a single controller handling all the pages you can use @SessionAttributes to store the Contact between requests in the session. After the last page use SessionStatus to mark the use of the @SessionAttribtues complete (for cleanup).

@Controller
@SessionAttributes("contact")
public AddContactController {

    @ModelAttribute
    public Contact contact() {
        return new Contact();
    }

    @RequestMapping("/addContact")
    public String registerContact(@ModelAttribute Contact contact) {
        return "addContact";
    }

    @RequestMapping("/addImages")
    public String registerImages(@Valid @ModelAttribute Contact contact, BindingResult result) {
        return "addImages";
    }

    @RequestMapping("/save")    
    public String firstPage(@ModelAttribute Contact contact, SessionStatus status) {
      status.complete();
    }
}
like image 106
M. Deinum Avatar answered Oct 30 '22 15:10

M. Deinum


This can be done by using @SessionAttributes which has one limitation check this. This totally depends upon your design though.

or you can use below mention pesudocode.Check the Session API here

Use HttpServletRequest in your RequestMapping to get request.


HttpSession session = request.getSession();//make an 

session.setAttribute("user", userDTO);


try
{
HttpSession session=request.getSession(false);
if(session!=null)
{

UserDTO userDTO = (UserDTO) session.getAttribute("user");

}

where userDTO is your object

HOW TO GO BACK AND FORTH IN FORM

Now in Order to go back and forth in your Flow.You have to create forward and backward links and use the session to populate the already saved values.

If you need more specific code let me know.

like image 35
beinghuman Avatar answered Oct 30 '22 17:10

beinghuman