我使用Struts2框架。在jsp中,我在项目中显示一个登录框,当用户点击登录按钮时,我设置了一个名为“loggedin”的cookie,并在Action Class中将其值设置为“true”。
然后返回“success”将再次加载此登录页面。
在登录页面中:
<body>
<%
Cookie cookie[] = request.getCookies();
for( c : cookie )
{
if( c.getName().equals("loggedin") )
{
if( !c.getValue().equals("true") )
{
%>
//show login form here.
<%
}//end inner if
else //if cookie "loggedin" value is "true"
{
%>
//show username/profile picture/logout button here
<%
}//end else
}//end outer if
}/end for loop
%>
</body>
我遇到了问题。当我单击登录表单中的登录按钮时,将设置cookie并重新加载页面。但是,在我手动重新加载页面之前,登录表单仍然显示,而不是用户名/个人资料图片。
答案 0 :(得分:6)
拜托!请 !不要使用scriptlet。它们难以维护,每个开发人员都厌恶它们。
有很多方法可以跟踪会话。
这些在网络上很好documented。生成会话的最快方法是执行HttpSession session = request.getSession(true);
。您可以在创建此对象后继续将会话信息附加到该对象。
答案 1 :(得分:4)
永远不建议在jsp中使用scriptlet。为什么不使用struts标签或JSTL标签。 使用session在每次成功登录时设置会话属性,并检查会话和该特定属性以检查用户登录。像:
//on successfull login...
Session session=request.getSession(true);
session.setAttribute("id",id); //here in place of id you can use something related to user, that can uniquely identify to each user.
// now to check for user logged in or not
Session session=request.getSession(false);
// by providing false value it will try to access a session already available, but it won't create a new session.
//now you can check like this..
if(session!=null)
{if(((String)session.getAttribute("id")).equals(id))
{
// do your stuffs here.........
}
else
{
// you can send the control to login page or to somewhere else as your requirement.
}
}
else{
// send the control to login page because session object is null...
}
最重要的一点是,不要在你的jsp中写下所有这些逻辑。 Jsp应该只放置视图逻辑。在struts中将所有业务/主要逻辑放在Action类中。