【问题标题】:Retrieving Session data in a Spring MVC application在 Spring MVC 应用程序中检索 Session 数据
【发布时间】:2013-10-13 05:16:02
【问题描述】:

我继承了一个 Spring MVC 应用程序。我对 .NET MVC 很熟悉,而且我认为我会以非常不同的方式设计这个东西,但是使用我所拥有的东西,这就是我想做的事情:

当前设计:

SearchController - 用于提交和呈现搜索结果。每个单独的搜索结果都有一个添加/编辑/删除选项,可将请求提交给不同的控制器。

@RequestMapping(valur={"/searchResult.do"}...)        
public ModelAndView searchResult(@ModelAttribute GlobalPojo pojo) {
  //here I'd like to store the pojo in session so that the search results
    //can be re-rendered after an Add/Edit/Delete action
}

CrudController

@RequestMapping(value = { "/modifyAction.do" }, method = { org.springframework.web.bind.annotation.RequestMethod.GET }) 
public ModelAndView modifyRecord(@RequestParam("id") String uid) {
    //here I'd like to return to the results page after completing an action 
}

这个 GlobalPojo 到处都被用作参数和结果,所以我不能很好地使它成为一个会话范围的 bean。我想我能做的是:

  1. 将此添加到 SearchController:@SessionAttributes("searchPojo")
  2. 修改@ModelAttribute --> @ModelAttribute("searchPojo")

但是,我不确定如何从 CrudController 访问 searchPojo,因为我想在其上设置一个 message 属性以显示在搜索结果页面上。

我看到的将会话传递给控制器​​操作的示例不使用属性,所以我只是不确定应该是什么样子。

提前致谢。

【问题讨论】:

    标签: spring-mvc


    【解决方案1】:

    如果您使用的 Spring 版本高于 3.1.2.RELEASE,则只需将 @SessionAttributes("searchPojo") 添加到您的 CrudController 的顶部,然后将 ModelAttibute("searchPojo") 指定为modifyRecord 方法。

    @Controller
    @SessionAttributes("searchPojo")
    public class CrudController {
        ...
    
        @RequestMapping(value = { "/modifyAction.do" }, method = { org.springframework.web.bind.annotation.RequestMethod.GET }) 
        public ModelAndView modifyRecord(@RequestParam("id") String uid, @ModelAttribute("searchPojo") SearchPojo pojo) {
            //here I'd like to return to the results page after completing an action 
        }
    }
    

    然后,Spring 应该在会话中查找 searchPojo 并将其传递给 modifyRecord 方法。然后您应该能够在modifyRecord 内的searchPojo 上设置消息属性。

    这里有一个使用SessionAttributes在控制器之间共享数据的示例:Spring 3.0 set and get session attribute

    【讨论】:

    • 谢谢 - 不幸的是,我们正在使用 3.0.5 或类似的版本。但如果这不起作用,我会尝试您链接中列出的版本。
    • @SessionAttribute 方法不起作用(同样,我们处于早期版本中),但提供的链接确实起作用。即,将 HttpSession 传递给所涉及的控制器操作,并在搜索操作中执行 session.setAttribute,在 CRUD 控制器操作中执行 session.getAttribute。
    【解决方案2】:

    也许您可以尝试从请求中获取会话并将 pojo 设置为会话属性。

    【讨论】:

    • 对,但是接下来就变成访问Request对象的问题了
    • 你试过把它作为论据吗?喜欢public ModelAndView searchResult(@ModelAttribute GlobalPojo pojo, HttpServletRequest req){HttpSession session = req.getSession();}
    • “我看到的将会话传递给控制器​​操作的示例不使用属性,所以我只是不确定应该是什么样子。” - 所以不,我不确定我是否可以这样做,或者它是否需要按照示例似乎暗示的特定顺序进行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-17
    • 2023-03-16
    • 1970-01-01
    • 2013-10-09
    • 1970-01-01
    • 2011-01-17
    • 2015-10-27
    相关资源
    最近更新 更多