Arcturus
Arcturus

Reputation: 27055

Preserving state on two pages in Spring MVC

I have a Spring MVC 3 application where we have two pages. One page users select some data, which is posted to the controller and buildsup page 2. Then after page 2 gets its values, I want to use the values of the firstpage for the database action.

Things I've tried so far:

I looked at the ModelAttribute

First up is the post of the first controller:

@RequestMapping(value = "/firstPage")
public ModelAndView firstPageSubmit(String valuePage1, String valuePage2) {
     return new ModelAndView("secondPage", "readonlySettings", new ReadonlySettings( valuePage1, valuePage2 );
} 

And I was hoping, spring would preserve this object, and give it to me again:

@RequestMapping(value = "/secondPage")
public ModelAndView secondPage(@ModelAttribute("readonlySettings") ReadonlySettings settings, String valuePage2) {
     //Store stuff in the database
     doa.save(settings.getValuePage1(), settings.getValuePage2(), valuePage2);
} 

But no dice.. All the values are empty.

Btw: I did nothing with the ReadonlySettings object on the jsp itself. So no hidden fields or whatever, because I do not like this solution. People can change hidden fields, and that is something I really wish to avoid.

Does anyone know how to handle this?

Upvotes: 2

Views: 3168

Answers (1)

Affe
Affe

Reputation: 47954

You can tell Spring to keep the object around associated with the user's web session on the server side by using @SessionAttributes.

@Controller
@SessionAttributes("readonlySettings")
public class MyController {

@RequestMapping(value = "/firstPage")
public ModelAndView firstPageSubmit(String valuePage1, String valuePage2, ModelMap map) {
    map.addAttribute("readonlySettings", new ReadonlySettings( valuePage1, valuePage2 );
    return new ModelAndView("secondPage");
} 

@RequestMapping(value = "/secondPage")
public ModelAndView secondPage(ModelMap map, SessionStatus status, String valuePage2, ) {
    ReadonlySettings settings = map.getAttribute("readonlySettings");
    doa.save(settings.getValuePage1(), settings.getValuePage2(), valuePage2);
    status.setComplete();
} 

Now obviously this is fairly primitive. Depending on the context of the operation you may need to add handling for when someone loads the second page directly via a link and has no object in their session. Also the object will be left hanging there until the session is cleaned up if someone never completes the second step. (May be tolerable in the case of just two strings.) If your actual use case is significantly more complicated than this, you may want to look in to something like web flow rather than re-inventing.

Upvotes: 2

Related Questions