登录失败使用session传数据

做登录界面失败时想要判断输出失败提示消息
起初使用页面跳转

            // 失败
            logger.debug("登陆失败");
            request.setAttribute("fail", "fail");
            request.setAttribute("name", username);
            request.getRequestDispatcher("login.jsp").forward(request,response);
            //String resp = "fail";
            //logger.debug("登陆失败");
            //response.sendRedirect("login.jsp?resp=fail");

这样可以成功实现跳转页面,并且通过login页面判断可以弹出登陆失败,只是再刷新页面时会提示是否重新提交表单,其实并没有什么影响
但是我又想到现在很多登录界面都是失败后只做文字提示
如图为qq空间登录失败的提示:

想要实现这种,设想为用一个表单来实现

      <style>
       #tip {
            color: red; /*输入文字、光标颜色*/
            caret-color: red; /*光标颜色*/
            width: 300px;
            border: none;
            height: 15px;
        }
      </style>
      <body>
            <input type="text" id="tip" name="tip" value="用户名或密码错误,请重新输入" style="display: none" readonly>
      </body>
      <script>
        var fail = "${fail}";
        console.log("fail = " + fail);
        if (fail != null && fail != '') {
            console.log("失败")
            $("#tip").show();
            document.getElementById("username").value = "${name}";
            document.getElementById("password").value = "${psw}";
        }
      </script>

这样基本实现了提示

但是再刷新页面时出现了问题,由于每次刷新页面都经过了Login.do,fail一直有值,所以相当于刷新失败了


后来经过老师指导,使用session来传数据,并且在页面定义一个中间变量,每次刷新将之前的session清空来实现
代码如下:
Sevlet:

logger.debug("登陆失败");
request.getSession().setAttribute("fail", "fail");
request.getSession().setAttribute("name", username);
request.getSession().setAttribute("psw", password);
response.sendRedirect("login.jsp");

Jsp页面:

<%
// 临时判断
if(session.getAttribute("fail")!=null){
   pageContext.setAttribute("loginFail",true);
   session.removeAttribute("fail");
}
%>

这里只放了页面刚开始定义存放session数据的中间量和移除session中的对应数据,其余参照上述代面

posted @ 2020-09-14 23:05  玖捌贰陆  阅读(398)  评论(0)    收藏  举报