如果用户已登录,则重定向到主页

时间:2011-12-25 11:53:32

标签: java jsp session servlets

  

可能重复:
  How to redirect to another page when already authenticated user accesses login page

如果登录用户点击了login.jsp页面,那么他应该会自动重定向到他的home.jsp。在身份验证之前,用户转到login.jsp并且在成功通过servlet(doPost)进行身份验证后,他被重定向到home.jsp,但是当同一用户再次点击登录页面时,他应该被自动重定向到{{1而不是再次记录。我怎么能在JSP / Servlet中做到这一点?我在成功通过身份验证后从该servlet设置会话。

登录前,用户点击home.jsp并转到login.jsp servlet方法,然后转到doPost()。成功登录后,如果用户再次点击home.jsp,则不应转到login.jsp,而是直接转到login.jsp。我该怎么办?

如果用户已退出,则只有在点击home.jsp控件后才会转到login.jsp,然后转到login.jsp的servlet,最后doPost()将会到来。

3 个答案:

答案 0 :(得分:9)

在login.jsp中尝试此代码

if(session.getAttribute("authenticated")!=null && session.getAttribute("authenticated").equals(true))
{
   response.sendRedirect("home.jsp");
}

答案 1 :(得分:3)

登录页面/操作检查用户是否已登录,如果已登录则重定向到主页:

if (alreadyLoggedIn) {
    response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + "/home"));
    return;
}

但如果用户已经登录,您可能首先没有指向登录页面的链接。

答案 2 :(得分:0)

为了您的帮助,我编写了一个示例并在我的机器中执行了代码。

在servlet页面的doPost

String username = request.getParameter("username");
String password = request.getParameter("password");
boolean isCredentialValid = validateCredentials(username, password);
String nextPage ="";
HttpSession session = request.getSession(true);
if(isCredentialValid){
    nextPage = "home.jsp";
    session.setAttribute("isLoggedIn", "true");
}else{
    request.setAttribute("error", "Either username or password is invalid.");
    nextPage ="login.jsp";
}
RequestDispatcher rd = request.getRequestDispatcher(nextPage);
rd.forward(request, response);
login.jsp

中的

<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript">
  var isLoggedIn = "<%= (String)session.getAttribute("isLoggedIn")%>";
  if(isLoggedIn === "true")
     window.location.href="home.jsp";
  }
</script>
</head>
<body>
   <form action="Test" method="post">
    ${error}
    <br/>
     UserName : <input type="text" name="username"/>
    <br/>
     Password : <input type="text" name="password"/>
    <br/>
    <input type="submit" value="submit"/>
  </form>
</body>
相关问题