自动登陆、Cookie的清除、登陆页面中文的处理

it2022-05-09  34

转自:https://blog.csdn.net/weixin_42150318/article/details/80460364

 

使用场景,当一个登陆页面登陆时输入的账号或者密码错误时清除Cookie;

另一种场景当用户退出的时候,清除Cookie,即使勾选的自动登陆,退出了系统,下次登陆就必须重写输入账号和密码。

登陆时处理在请求方式的方法内设定编码外(doGet()和doPost()方法内设置UTF-8或者其他),在创建Cookie时也要对中文进行编码,如果没有处理,存到Cookie里面的是乱码。

自动登陆时也要在jsp页面对取到的Cookie对象中的中文进行解码,不然取出来的还是乱码

--------------------登陆的jsp页面--------------------

<%@ page import="java.net.*" language="java" contentType="text/html; charset=UTF-8"     pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <%

    Cookie[] cookies = request.getCookies();  //获取Cookie所有存的值

    String username = null;     String password = null;     if(cookies != null)   //在这里加判断是为了防止空指针异常,如果cookies为null的或for循环中的cookies.length会报空指针异常     {         for(int i=0;i<cookies.length;i++)         {             Cookie cookie = cookies[i];                          String name = cookie.getName();//cookie的名称             String value = URLDecoder.decode(cookie.getValue(),"utf-8");  //cookie的值  解码(针对中文)             //解码URLDecoder.decoder("需要解码的内容" ,"编码样式");     (j)             //System.out.println(name + "  : " + value);                          if("c_username".equals(name))             {                 username = value;             }             else if("c_password".equals(name))             {                 password = value;             }         }                  System.out.println(username + "  "+ password);                  //自动登录         if((username!=null && !"".equals(username)) && (password != null && !"".equals(password)))         {   

            session.setAttribute("username", username);       //用session存Cookie存的username和password             session.setAttribute("password", password);             response.sendRedirect(request.getContextPath() + "/loginServlet");  //跳转到Servlet的使用的是doGet()         }     }

%>

<body>     <form action="loginServlet" method="post">         用户名:<input type="text" name="username" value='<%=(username!=null && !"".equals(username))?username:""%>'><br/><br/>         密    码:<input type="text" name="password" value='<%=(password!=null && !"".equals(password))?password:""%>'><br/><br/>         <input type="checkbox" name="autoLogin" value="autoLogin">自动登录<br/><br/>                  <input type="submit" value="登陆">     </form>          <font color="red" size="-1"> <%=request.getAttribute("errorMsg")%> </font>      </body> </html>


最新回复(0)