1

我使用 Struts2 框架。在 jsp 中,我在我的项目中显示了一个登录框,当用户单击登录按钮时,我设置了一个名为“loggedin”的 cookie,并在 Action 类中将其值设置为“true”。

然后返回“成功”将再次加载此登录页面。

在登录页面:

<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 并重新加载页面。但是,在我手动重新加载页面之前,仍然显示登录表单,而不是用户名/个人资料图片。

  1. 我该如何解决这个问题?
  2. 我认为这不是检查是否登录的正确方法。有人可以告诉我如何以另一种方式检查吗?
4

2 回答 2

6

请 !请 !不要使用小脚本。它们很难维护,每个开发人员都讨厌它们。

有很多方法可以跟踪会话。

  • 使用 cookie
  • 网址重写
  • 隐藏参数

这些在网络上都有很好的记录。生成会话的最快方法是执行HttpSession session = request.getSession(true);. 创建此对象后,您可以继续将会话信息附加到该对象。

看一看JSTL 入门和关于为什么 scriptlet 不好的咆哮。

于 2013-04-04T04:25:41.590 回答
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 类中。

于 2013-04-04T05:20:42.887 回答