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
精彩评论