我已根据查询搜索了论坛,但找不到答案。 我是 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/