在spring mvc中正确使用session

时间:2016-04-07 09:42:56

标签: java spring spring-mvc session

我使用的是Spring 4.1.1。我必须为用户会话服务。存储用户的会话相关数据的最佳方法是什么?我阅读了很多方法,但我不明白哪种方式适当?

这是我需要的例子

@Controller
@SessionAttributes("user")
public class PagesController {
@RequestMapping(value="/sign_in", method = RequestMethod.POST)
public String getSignIn(@RequestParam(value="user")String user ,
                        @RequestParam(value="pass")String password,
                        Model model) {
    UserDAO dao = new UserDao();
    if(dao.isUserValid(user,password) && !model.containsAttribute("user")){
        User user = new User();
        model.addAttribute("user",user);
        return USER_PAGE;
    }
    return LOGIN_PAGE;
}

}

2 个答案:

答案 0 :(得分:1)

It is OK that you put your user object in session, and then use it in your project everywhere. However, if you get a lot of users, that means you have many user object in the memory of your server. The memory might run out.

Another way to do it is to put some user information in cookies with some encryption and validation, but just remember not to put too much info in cookies because cookies will be sent every time a request or a response is made. If there to much information to send, it will slow the response time.

And just a reminder, you should call status.setComplete() to clean the attributes inside a session when they are not needed.

Does SessionStatus object.setComplete() clears all the session attributes or just work for the controller in which it is used?

and if you don't know how to use it, you can see the article below

http://vard-lokkur.blogspot.tw/2011/01/spring-mvc-session-attributes-handling.html

答案 1 :(得分:1)

首先,会话属性不是存储用户对象的好选择。是春天决定何时清除会话属性数据。根据spring文档,spring在理解对话时会删除会话属性。完成了。您只在控制器范围内使用会话属性,并且暂时需要将数据存储在会话中。

就用户登录对象而言,您需要做的是使用http sesison。当您登录/登录您的应用程序时,您实际上将登录凭证发布到您的控制器。验证完成后,将用户对象(尽可能少的信息 - 放入对象并存储到会话中)。只要它没有到期,或者在用户触发注销时清除它,该对象将保持不变。

此外,如果您仍想使用SessionAttribute来存储您的用户对象。然后,将应用程序部署到群集环境时可能会出现进一步的问题。除非您实现粘性会话,否则必须将会话复制到服务器的每个实例。复制httpsession是最简单的任务,而复制sessionAttribute的相同实例则不是。

    @RequestMapping(value = "login.html", method = RequestMethod.POST)
    public ModelAndView post(@ModelAttribute("login") LoginEntity login, HttpServletRequest req) {


... process the data ...
if passed put it into session:

HttpSession session = req.getSession(true);
UserObject userObject=new UserObject();
userObject.setName(login.getUserName());
...

session.setAttribute("user",userObject);