我在处理会话中的对象时遇到问题。
我像这样在会话中存储对象。假设对象是对象的名称。我在动作课中这样做:
if(object!=null)
{
session.settAttribute("objectName",object);
return mapping.findForward("success");
}
else
{
return mapping.findForward("failure");
}
我将成功和失败都映射到同一jsp页面。我检查像
if(session.getAttribute("objectName")!=null)
{
object= (SomeObjectClass)session.getAttribute("objectName");
}
if(object!=null)
{
//Do this
}
else
{
//Do that
}
现在是我的问题了。在会话中第一次设置对象时没有问题。当我同时从两个不同的浏览器中调用此动作类时,我遇到了一个问题,一种情况下转到其他部分,一种情况下转到另一部分。我相信这是因为会话不是线程安全的。有什么解决办法吗?
最佳答案
您提到要在两个浏览器之间查看相同的信息...如果要共享的信息是“全局”的(即对于应用程序的所有用户都应该相同),则应存储该信息在应用程序作用域中,而不是会话作用域中(有关作用域的说明,请参见http://java.sun.com/developer/onlineTraining/JSPIntro/contents.html#JSPIntro5)。例如:
ServletContext servletContext = getServlet().getServletContext(); //"application scope"
SomeObjectClass object = (SomeObjectClass) servletContext.getAttribute("objectName");
if(object !=null){
//Do this
} else {
//Do that
}
如果您拥有帐户和登录机制,并且希望同一登录在两个不同的浏览器中看到相同的信息,那么您将遇到不同的问题。在那种情况下,信息将需要存储在“数据库”中(不一定是rdbms,可能是应用程序范围!,取决于您的持久性需求),并且需要使用用户在操作类中检索信息。可以存储在会话,cookie等中的信息
//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
}