自动登录功能实现

  1. 自动登录
    在用户登录后进入首页,关闭浏览器后,下次打开浏览器进入首页时,往往需要重新登录,自动登录功能:再次打开浏览器的时候,不需要重新登录就可以进入首页。
  2. 实现原理
    在用户登录后,将用户的用户名和密码保存到cookie中发送给浏览器,浏览器下次再次访问的时候会把cookie内容带回来,服务器从cookie中区出用户名和密码进行验证,如果验证通过,则允许进入首页等,从而达到自动登录的目的。
  3. 代码实现
    (1)登录页面表单:
method="post" action="login"> 用户名:type="text" name="username" >
密码:type="text" name="password" >
自动登录:type="checkbox" name="auto" value="auto" >
type="submit" value="登录">
(2)模拟后台service登录方法:
package com.service;

public class LoginServiceImpl {

    public boolean login(String username,String password) {
        return "root".equals(username)&&"1234".equals(password);
    } 

}

(3)后台Controller:

package com.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.service.LoginServiceImpl;

@WebServlet("/login")
public class LoginController extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String auto = req.getParameter("auto"); //是否自动登录

        if(new LoginServiceImpl().login(username, password)) {//如果登录成功
            req.getSession().setAttribute("username", username);
            if(auto==null) {
                Cookie cookie = new Cookie("auto", null);
                cookie.setMaxAge(60*60*24);//cookie有效时间
                cookie.setPath(req.getContextPath()+"/");
                resp.addCookie(cookie);
            }else {
                Cookie cookie = new Cookie("auto", username+"_"+password);
                cookie.setMaxAge(60*60*24);//cookie有效时间
                cookie.setPath(req.getContextPath()+"/");
                resp.addCookie(cookie);
            }
            resp.sendRedirect("index.jsp");
        }else {
            resp.sendRedirect("login.jsp");
        }
    }
}
(4)拦截器
package com.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.service.LoginServiceImpl;
import com.util.CookieUitl;

@WebFilter("/*")
public class LoginFiler implements Filter {

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        if(request.getRequestURI().contains("login")) {//如果访问login
            chain.doFilter(request, response);
            return;
        }else {
            String username = (String) request.getSession().getAttribute("username");
            if(username==null) {
                String val = CookieUitl.getCookieValByKey("auto", request);
                if(val!= null&& !val.equals("")) {
                    String name = val.split("_")[0];
                    String pass = val.split("_")[1];

                    if(new LoginServiceImpl().login(name, pass)) {
                        request.getSession().setAttribute("username", name);
                        chain.doFilter(request, response);
                        return;
                    }else {
                        response.sendRedirect("login.jsp");
                    }
                }else {
                    response.sendRedirect("login.jsp");
                }
            }else {
                chain.doFilter(request, response);
                return;
            }
        }
    }

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

(5)CookieUtil

package com.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

public class CookieUitl {

    public static String getCookieValByKey(String key,HttpServletRequest request) {

        String value = null;
        Cookie[] cookies = request.getCookies();
        if(cookies!= null && cookies.length>0) {
            for (Cookie cookie : cookies) {
                if(key.equals(cookie.getName())){
                    value = cookie.getValue();
                }
            }
        }
        return value;
    }
}
(6)index.jsp中欢迎页面   
<body>
欢迎你:${username }
body>

注:在实际开发中,用户名和密码不是明文放在cookie中的,需要先进行加密处理后再存入cookie中。

你可能感兴趣的:(java)