开发者

Where to store an object I need the whole session and I need the possibility to update it, while also updating it in the database?

开发者 https://www.devze.com 2023-03-21 19:49 出处:网络
The Object is the logged in user with some objects related to him. I would like to keep the traffic on the database to a minimum. I need a proper solution to do this. I use JSP-Code without Scriptlets

The Object is the logged in user with some objects related to him. I would like to keep the traffic on the database to a minimum. I need a proper solution to do this. I use JSP-Code without Scriptlets, with Servlets and I get the object through JPA. I hope you understand what I mean.开发者_StackOverflow中文版


If you store the data to the session like powerMicha suggested, you have to make sure that the data you are storing is serializable. Otherwise you might get some weird behavior as some Webcontainers save the session data to disk via serialization if they need the memory for other things.


You can store your object to the HttpSession via the methods setAttribute(...) and retrieve it via getAttribute(...)

So your code (in a servlet) would look something like that:

final String CURRENT_USER_KEY = "CURRENT_USER";

EntityManager em; // somewhere initialized
Integer userid; //  somewhere initialized

HttpSession session =  httpServletRequest.getSession();
User user = session.getAttribute(CURRENT_USER_KEY);

if(user == null){
  User user = em.find(User.class, userId);
  session.setAttribute(CURRENT_USER_KEY, user);
}

// perform further actions on your user
0

精彩评论

暂无评论...
验证码 换一张
取 消