自动登录,是为了帮助用户多次使用这个网页时,不用再次输入用户名和密码就可以登录。

是指用户将用户的登录信息,人,保存到本地的文件中Cookie中。

Name,value – 声明时 new Cookie(key,value);

       Path        - 默认值,即为当前保存cookie的这个serlvet所在的路径。   

              如果Cookie在这样的路径:http://loclhost:8080/project/abc/AServlet

              则Cookie的路径为: http://loclhost/project/abc

              则说明:

              所在在http://loclhost/project/abc目录下的servlet才可以读取这个cookie的值。

              如果:

              保存Cookie类:http://loclhost:8080/project/a/b/AServlet

              则Cookie的默认path为;

              http://loclhost/project/a/b        

              对于path这个值可以手工设置:

如果设置为: http://loclhost/project/ 即到项目名。

              则所有这个项目中的所有Serlvet|jsp都可以读取到这个 cookie.

              Cookie.setPath(requst.getContextPath());

 如果将path设置为   /

              即:cookie.setpath(“/”); - http://localhost/

              则所有在tomcat中运行的项目都可以读取这个到cookie.  

 如果path设置为/必须要与domain共同使用才有意义。      

       Age        - 默认值-1,在浏览器中存在。 0:删除文件中的cookie和浏览器中的cookie。

       Domain     - 域 -

                     www.sina.com - login

                     www.bbs.sina.com

                     www.news.sina.com

    删除时,必须要设置的与之前设置的信息完全一样:

        Name

  Age = 0(文件和缓存),-1(只删除文件)

  Path 一样。

  Domain :null

    下一次用户再打开这个网页时,应该读取cookie中的信息,实现自动登录。    



思路:登录时用户勾选了记住密码几天,登录Servlet 里返回给浏览器一个Cookie,name是autoLogin,value是:(编码)用户名_(加密)密码,用户再次进来时,过滤器遍历所有的Cookie,看是否有一个叫autoLgin的Cookie。如果有,解析用户名密码。自动登录。其中加密部分借鉴了别人的文章感觉不错。连接

代码L:

User类:

package com.lhy.domain;

public class User {
  
  private String username;
  private String password;
  public String getUsername() {
    return username;
  }
  public void setUsername(String username) {
    this.username = username;
  }
  public String getPassword() {
    return password;
  }
  public void setPassword(String password) {
    this.password = password;
  } 
}

LoginServlet:

@WebServlet(name="LoginServlet",urlPatterns="/LoginServlet")
public class LoginServlet extends HttpServlet{

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    System.err.println("---------->LoginServlet");
    req.setCharacterEncoding("UTF-8");
    //
    String username = req.getParameter("username");
    String password = req.getParameter("password");
    //是否自动登录
    String auto = req.getParameter("auto");
    if("lhy".equals(username) && "123".equals(password)){
      
      //登录成功,将用户信息放session
      User user = new User();
      user.setUsername(username);
      req.getSession().setAttribute("user", user);
      
      if(!"-1".equals(auto)){
        //勾选了自动登录
        int day = Integer.parseInt(auto);//1|7
        int seconds = 60 * 60 * 24 * day;//cookie存活时间 单位:秒
        //声明cookie
        //  用户名(编码)_密码(加密))
        //cookie不能存中文,用户名有中文编码后可以转为字母
        Cookie c = new Cookie("autoLogin",Base64Util.encode(username)+"_"+Md5Util.encode(password));
        c.setMaxAge(seconds);
        c.setPath(req.getContextPath());
        //保存cookie
        resp.addCookie(c);
        resp.sendRedirect(req.getContextPath()+"/jsps/main.jsp");
      }
    }else{
      //登录失败
      req.getSession().setAttribute("msg", "用户名或密码错误");
      resp.sendRedirect(req.getContextPath()+"/index.jsp");
    }
  }

  
}

LogoutServlet:

@WebServlet(name="LogoutServlet",urlPatterns="/LogoutServlet")
public class LogoutServlet extends HttpServlet {

  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    System.err.println("用户退出");
    //删除整个session
    req.getSession().invalidate();
    Cookie c = new Cookie("autoLogin","ddd");
    c.setMaxAge(0);
    c.setPath(req.getContextPath());
    resp.addCookie(c);
    //用户退出动作的标识
    req.getSession().setAttribute("exit",true);
    resp.sendRedirect(req.getContextPath()+"/index.jsp");
  }

}

过滤器:

public class AutoLoginFilter implements Filter{

  @Override
  public void init(FilterConfig filterConfig) throws ServletException {
    
  }

  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    // 在这儿读取cookie
    HttpServletRequest req = (HttpServletRequest)request;
    // 获取用户请求的uri
    String uri = req.getRequestURI();//AutoLogin/index.jsp

    //1.对于登录、退出,直接放行
    if(req.getSession().getAttribute("exit")==null){ //退出过来的
       if(req.getSession().getAttribute("user")==null){
         if(!uri.endsWith("index.jsp")){
         //获取所有的cookie
           Cookie[] cookies = req.getCookies();
           if(cookies != null){
             for (Cookie cookie : cookies) {
               if(cookie.getName().equals("autoLogin")){//如果存在自动登录的cookie
                 String usernameAndPassword = cookie.getValue();//用户名密码 base64username_md5password
                 String username = usernameAndPassword.split("_")[0];//base64用户名
                 String password = usernameAndPassword.split("_")[1];//md5密码
                 
                 //解码用户名
                 username  = Base64Util.decode(username);
                 //根据用户名查询,这里模拟。123的md5:ICy5YqxZB1uWSwcVLSNLcA==
                 if("lhy".equals(username) && "ICy5YqxZB1uWSwcVLSNLcA==".equals(password)){
                   //登录成功
                   User u = new User();
                   u.setUsername(username);
                   req.getSession().setAttribute("user", u);
                   break ;
                 }
               }
             }
           }
         }
       }
      }else{
         //退出过来的,清除session里exit
         req.getSession().removeAttribute("exit");
    }
    //不管是否自动登录成
    chain.doFilter(request, response);
  }

  @Override
  public void destroy() {
  }

}

编码加密工具类:

public class Base64Util {

  //编码    中文 -------------5Lit5paH
  public static String encode(String str){
      BASE64Encoder b64= new BASE64Encoder();
      return b64.encode(str.getBytes());
  }
  
  //解码   5Lit5paH----中文 
  public static String decode(String str){
      try {
          BASE64Decoder b64decoder = new BASE64Decoder();
          byte [] afterStr = b64decoder.decodeBuffer(str);
          return new String(afterStr);
      } catch (IOException e) {
          e.printStackTrace();
          throw new RuntimeException(e);
      }
  }
  
 
  public void testEncode(){
     
  }
  public static void main(String[] args) {
    String str = Base64Util.encode("中文");
    System.out.println(str);
    
    
    String newString = Base64Util.decode(str);
    
    System.out.println(newString);
  }
}
public class Md5Util {

    //md5加密的方法
    public static String encode(String old){
        try {
            MessageDigest md5 = MessageDigest.getInstance("md5");
            byte newStr[] = md5.digest(old.getBytes());
            
            BASE64Encoder b64= new BASE64Encoder();
            return b64.encode(newStr);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
    public static void main(String[] args) {
      String s = Md5Util.encode("123");
      System.err.println(s);//ICy5YqxZB1uWSwcVLSNLcA==
    }
}

用到了 jar包:sun.misc.BASE64Decoder.jar

过滤器配置:

 <filter>
     <filter-name>autoLogin</filter-name>
     <filter-class>com.lhy.filter.AutoLoginFilter</filter-class>
 </filter>
 <filter-mapping>
     <filter-name>autoLogin</filter-name>
     <!-- <url-pattern>*.jsp</url-pattern> -->
     <url-pattern>/*</url-pattern>
 </filter-mapping>

登录表单:

<body>
    <c:if test="${not empty sessionScope.msg}"> 
                   <font color="red">
                       ${sessionScope.msg}
                   </font>
                   <c:remove var="msg" scope="session"/>
               </c:if>
            <form name="x" method="post" action="<c:url value='/LoginServlet'/>">
                Name:<input type="text" name="username"/><br/>
                Password:<input type="password" name="password"/><br/>
                auto:<input type="radio" name="auto" value="-1">不自动登录
                <br/>
                <input type="radio" name="auto" value="1">1天<br/>
                <input type="radio" name="auto" value="7">1周<br/>
                <input type="submit"/>
            </form>
  </body>

main.jsp:

<body>
        这是首页,欢迎你:${user.username}  | <a href="LogoutServlet">退出</a>
  </body>

只是记录下学习到这个知识点,解决这个问题的思路,肯定还不完善,有错误清指出!谢谢!

 

欢迎关注个人公众号一起交流学习: