Redirect to homepage if user is already registered

Possible duplicate:
How to redirect to another page when an authenticated user accesses the login page

If a registered user clicks on a login.jsppage, he should be automatically redirected to his home.jsp. Before the authentication user goes to login.jspand after the successful servlet authentication (doPost), he is redirected to home.jsp, but when the same user clicks on the login page, he should be automatically redirected to home.jspinstead of re-logging in. How can I do this in JSP / Servlet? I am establishing a session from this servlet after successful authentication.

Before entering the system, the user clicks login.jspand goes to the doPost()servlet method and goes to home.jsp. After a successful login, if the user clicks on again login.jsp, and instead of switching to login.jsp, control should go directly to home.jsp. How can i do this?

If the user logs out, then only after clicking the button login.jspthe control will go to login.jsp, and then to the doPost()servlet, and finally home.jsp.

+5
source share
3 answers

try this code in your login.jsp

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

/ , , , :

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

, , , .

+3

For your help, I wrote an example and executed the code on my machine.

On the servlet page in 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);

in 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>
0
source

All Articles