I am facing an issue in handling an object in session.
I store a开发者_如何转开发n object in the session like this. Assume object is the name of the object. I do this in my action class:
if(object!=null)
{
session.settAttribute("objectName",object);
return mapping.findForward("success");
}
else
{
return mapping.findForward("failure");
}
I map both success and failure to the same jsp page. I check like
if(session.getAttribute("objectName")!=null)
{
object= (SomeObjectClass)session.getAttribute("objectName");
}
if(object!=null)
{
//Do this
}
else
{
//Do that
}
Now here comes my problem. There is no problem when I set the object in first time in the session. I get a problem when I call this action class from two different browsers at the same time I go to else part for one case and if part for one case. I believe this is because session is not thread safe. Is there any solution?
You mention that you're trying to see the same information between two browsers... if the information you're trying to share is "global" (i.e. it should be the same for ALL users of the application, you should store the information in the application scope, not the session scope. (see http://java.sun.com/developer/onlineTraining/JSPIntro/contents.html#JSPIntro5 for explanation of scopes). For example:
ServletContext servletContext = getServlet().getServletContext(); //"application scope"
SomeObjectClass object = (SomeObjectClass) servletContext.getAttribute("objectName");
if(object !=null){
//Do this
} else {
//Do that
}
If you have accounts and a login mechanism and you're wanting the same login to see the same information in two different browsers, then you have a different issue. In that case the information will need to be stored in a "database" (not necessarily a rdbms, could be the application scope!, depending on your needs for persistence) and the information would need to be retrieved in the action class using the user information that could be stored in the session, cookie, etc.
//get the user info from the session, cookies, whatever
UserInfoObject userInfo = getUserInfo(request);
//get the object from the data store using the user info
SomeObjectClass object = getObjectForUser(userinfo);
if(object !=null){
//Do this
} else {
//Do that
}
When you access action/page from different browser you create a new session. In modern browsers you can share session between tabs or views. The only way to share session with more browsers is to use jSessionid param in URLs.
精彩评论