简体   繁体   English

用户在JSP和Servlet中无法使用Session登录时出现错误消息

[英]Error message when user Fails to Login using Session in JSP and Servlet

My goal is to create an error message when user fails to log in to the system. 我的目标是在用户无法登录系统时创建一条错误消息。 I managed to create an error message using session. 我设法使用会话创建错误消息。

However, when I refresh the browser, the error message is still there. 但是,当我刷新浏览器时,错误消息仍然存在。 It should not appear. 它不应该出现。 Is there a way for me to make the error message invisible when user refresh the browser? 当用户刷新浏览器时,我是否有办法使错误消息不可见?

Below are my codes. 以下是我的代码。 Help will be appreciate..Thanks! 帮助将不胜感激..谢谢! :) :)

At login.jsp login.jsp

<div class="error">
<% String e = (String) session.getAttribute("error" );
if(e != null)
{
    out.print(e); 
}%>
</div>

At Servlet Servlet

HttpSession session = request.getSession(true);
session.setAttribute( "error", "Invalid username or password");
RequestDispatcher dispatcher = request.getRequestDispatcher("/login.jsp");
dispatcher.forward( request, response); 

Session attributes live for the duration of an HttpSession . 会话属性在HttpSession Try using request attributes 尝试使用请求属性

request.setAttribute( "error", "Invalid username or password");

which only last for the duration of the request. 仅在请求期间持续。

Otherwise, you will have to remove the attribute from the HttpSession . 否则,您将必须从HttpSession删除该属性。

you can either the use the request object or you can just check if the session attribute exists in the session and if so you can just remove that. 您可以使用请求对象,也可以仅检查会话中是否存在session属性,如果存在,则可以将其删除。

ie jsp 即jsp

<% String e = (String) session.getAttribute("error" );
if(e != null)
{
    out.print(e); 
}else{
  out.print("All Is Well");
}>

servlet 的servlet

HttpSession session = req.getSession(true);
    try{
        if(null != (session.getAttribute("error"))){
            session.removeAttribute("error");
        }else{
            session.setAttribute( "error", "Invalid username or password");
        }
    }catch(Exception er){
        er.printStackTrace();
    }

    RequestDispatcher dispatcher = req.getRequestDispatcher("/jsp/LoginTest.jsp");
    dispatcher.forward( req, res); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM