2

我有一个 Spring MVC 3 应用程序,其中有两个页面。一页用户选择一些数据,这些数据被发布到控制器并构建第 2 页。然后在第 2 页获取其值后,我想将第一页的值用于数据库操作。

到目前为止我尝试过的事情:

我看着ModelAttribute

首先是第一个控制器的帖子:

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

我希望,春天会保存这个对象,并再次把它交给我:

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

但是没有骰子..所有的值都是空的。

ReadonlySettings顺便说一句:我对 jsp 本身的对象什么也没做。所以没有隐藏字段或其他什么,因为我不喜欢这个解决方案。人们可以更改隐藏字段,这是我真正希望避免的事情。

有谁知道如何处理这个?

4

1 回答 1

2

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.

于 2012-11-26T16:52:57.487 回答