如果用户已登录,则重定向到主页
可能重复:
当已经过身份validation的用户访问登录页面时,如何重定向到另一个页面
如果登录用户单击login.jsp
页面,则应自动将其重定向到他的home.jsp
。 在身份validation之前,用户转到login.jsp
并在成功通过servlet(doPost)进行身份validation后,将其重定向到home.jsp
,但是当同一用户再次单击登录页面时,他应该自动重定向到home.jsp
而不是再次登录。 我怎么能在JSP / Servlet中做到这一点? 我在成功通过身份validation后从该servlet设置会话。
在登录之前,用户单击login.jsp
并转到servlet的doPost()
方法并转到home.jsp
。 成功登录后,如果用户再次点击login.jsp
那么控制权应该直接转到home.jsp
。 我该怎么做?
如果用户已注销,则只有在单击login.jsp
控件后才会进入login.jsp
,然后是servlet的doPost()
,最后是home.jsp
。
在login.jsp中尝试此代码
if(session.getAttribute("authenticated")!=null && session.getAttribute("authenticated").equals(true)) { response.sendRedirect("home.jsp"); }
登录页面/操作检查用户是否已登录,如果已登录则重定向到主页:
if (alreadyLoggedIn) { response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + "/home")); return; }
但如果用户已经登录,您可能首先没有指向登录页面的链接。
为了您的帮助,我编写了一个示例并在我的机器中执行了代码。
在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
Insert title here