java - 如何维护 session 范围的pojo类中的数据 spring mvc 3.0.3

标签 java spring-mvc

我已根据查询搜索了论坛,但找不到答案。 我是 spring mvc 新手,所以我有点困惑,如果有人帮助我,那就太好了,

我有一个 spring mvc 应用程序,我从请求参数中获取一些数据,我必须在整个 session 中维护该数据。我如何使用 Spring 3.0.3 实现这一点。

我有一些想法来实现这个

1> 创建一个具有 session 范围的 pojo 2> 然后在 Controller 中 Autowiring pojo并填充pojo。 3> 由于它在 session 范围内,因此填充的值应该在整个 session 中可用

请让我知道我是否走在正确的道路上。

谢谢。

最佳答案

您所说的想法是使用 session 范围 bean 的一种方法。您可以定义 session 范围的 POJO:

@Component
@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class YourSessionBean{
...
}

然后你可以将它注入(inject)到你的 Controller 类中:

@Controller
public class YourController {
     @Autowired
     private YourSessionBean yourSessionBean;
     ...
}

您还可以使用@SessionAttributes将 POJO 存储到 session 中:

public class YourObject {
...
}

您可以在 Controller 中使用@SessionAttributes注释将YourObject实例放入 session 中:

@Controller
@SessionAttributes("yourObj")
public class YourController {
     ...
    @RequestMapping(value="/url")  
    public ModelAndView process(...) {  
    ModelAndView modelAndView = new ModelAndView();  
    modelAndView.addObject("yourObj", new YourObject());  // this will put YourObj into session

    return modelAndView;  
}  
}

但是,在使用 @SessionAttributes 时,您应该考虑以下语句 block (复制自 @SessionAttributes Doc ):

NOTE: Session attributes as indicated using this annotation correspond to a specific handler's model attributes, getting transparently stored in a conversational session. Those attributes will be removed once the handler indicates completion of its conversational session. Therefore, use this facility for such conversational attributes which are supposed to be stored in the session temporarily during the course of a specific handler's conversation.

For permanent session attributes, e.g. a user authentication object, use the traditional session.setAttribute method instead.

您还可以使用 HttpSession 作为 @RequestMapping 处理程序方法的方法参数,然后将 POJO 类添加到 session 中:

@Controller
public class YourController {
     ...
    @RequestMapping(value="/url")  
    public ModelAndView process(HttpSession session,...) {  
    ModelAndView modelAndView = new ModelAndView();  
    session.setAttribute("yourObj", yourObj);
    ...  
    return modelAndView;  
}  
}

关于java - 如何维护 session 范围的pojo类中的数据 spring mvc 3.0.3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19699922/

相关文章:

java - 我无法将 Mockito 单元测试重写为 Spock 规范

java - 有没有办法减少页面返回的参数数量?

java - Java/OOP 编程中传递参数、好的和坏的实践

java - Beanshell Sampler JMeter 解析 RegularExpressionExtractor 时出错

java - Spring 3 MVC,Tomcat Web 应用程序在几次请求后挂起

spring - 一旦调用 Spring Controller 方法,我可以确认文件已完全上传吗?

java - 定期重新创建对象

java - 当前请求不是多部分请求

java - 在哪里可以找到日志记录 channel 适配器的文档?

Java将InputStream转换为String