过滤器实现自动登录(过滤器filter)

本文介绍了如何通过创建实体类、login.jsp页面、过滤器filter和LoginServlet来实现自动登录功能。登录成功后用户将被重定向到login1.jsp首页,失败则返回login.jsp。
摘要由CSDN通过智能技术生成

自动登录

  1. 创建实体类entity新建user类
    package entity;
    
    public class User {
        private String username;
        private String password;
    
        public User() {
        }
    
        public User(String username, String password) {
            this.username = username;
            this.password = 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;
        }
    }
    
    

  2. 创建login.jsp页面以post提交传值到LoginServlet类
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
      <head>
        <title>$Title$</title>
        <style>
          *{
            text-align: center;
          }
        </style>
      <body>
      <h1>登录</h1>
      <form action="LoginServlet" method="post">
        <h2>userName:<input type="text" name="username" placeholder="用户名"> <br/></h2>
    
        <h2>passWord:<input type="password" name="password" placeholder="密码"> <br/></h2>
    
        <h2>AutoLogin:<input type="checkbox" name="autologin" value="autologin" style="width: 20px;height: 20px"><br/></h2>
    
        <input type="submit" value="登录" style="width: 100px;height: 50px"/>
      </form>
      </body>
      </body>
    </html>
    
    

  3. 创建过滤器filter过滤login.jsp传过来的值
    package filter;
    
    
    import entity.User;
    
    import javax.servlet.*;
    import javax.servlet.annotation.WebFilter;
    import javax.servlet.annotation.WebInitParam;
    import javax.servlet.http.Cookie;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    
    @WebFilter(filterName = "LoginSerlvet",urlPatterns = "/login1.jsp")
    public class LoginFilter implements Filter {
    
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
    
        }
    
        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            HttpServletRequest request=(HttpServletRequest)servletRequest;
            HttpServletResponse response=(HttpServletResponse)servletResponse;
            //获得一个名为autologin的cookie
            Cookie[]cookies=request.getCookies();
            String autologin=null;
            for(int i=0;cookies!=null&&i<cookies.length;i++){
                    if("autologin".equals(cookies[i].getName())){
                        autologin=cookies[i].getValue();
                        break;
                    }
            }
                    if(autologin!=null){
                        String[] parts=autologin.split("-");
                        String username=parts[0];
                        String password=parts[1];
                        if("admin".equals(username)&&"123456".equals(password)){
                            //验证成功
                            //该用户状态user对象存入session域
                            User user=new User();
                            user.setUsername(username);
                            user.setPassword(password);
                            request.getSession().setAttribute("user",user);
                        }
                    }
                        filterChain.doFilter(request,response);
        }
    
        @Override
        public void destroy() {
            System.out.println("销毁");
        }
    }
    
    

  4. 创建servlet包新建LoginServlet类接受login.jsp传过来的值
    package servlet;
    
    import entity.User;
    
    import javax.print.DocFlavor;
    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 java.io.IOException;
    @WebServlet("/LoginServlet")
    public class LoginServlet 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");
            System.out.println(username+password);
            //验证用户名和密码
            if ("admin".equals(username) && "123456".equals(password)){
            //验证成功
            //将用户状态存入session域
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            req.getSession().setAttribute("user", user);
            //发送自动的cookie
            String autologin = req.getParameter("autologin");
            System.out.println("autologin=" + autologin);
            if (autologin != null) {
                Cookie cookie = new Cookie(autologin, username + "-" + password);
                cookie.setMaxAge(100);
                System.out.println("hello");
                cookie.setPath(req.getContextPath());
                resp.addCookie(cookie);
                resp.sendRedirect(req.getContextPath()+"/login1.jsp");
            }
            //跳转到首页
        }else{
            req.setAttribute("errerMsg", "用户名密码错误");
            req.getRequestDispatcher("/login.jsp").forward(req, resp);
            }
        }
    }
    
    

    登录成功跳转到login1.jsp首页,登录失败跳回ligin.jsp原页面

  5. 首页logion1.jsp
    <%--
      Created by IntelliJ IDEA.
      User: 黄珮
      Date: 2021/9/16
      Time: 16:03
      To change this template use File | Settings | File Templates.
    --%>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <html>
    <head>
        <title>首页</title>
    </head>
    <body>
    首页
    <c:if test="${empty user}">
        <a href="login.jsp">请登录</a>
    </c:if>
    <c:if test="${not empty user}">
        欢迎:${user.username }
    </c:if>
    </body>
    </html>
    
    

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值