Filter实现自动登录

释放双眼,带上耳机,听听看~!

user类

package p01_user;

public class User {
    private String UserName;
    private String Password;

    public String getUserName() {
        return UserName;
    }
    public void setUserName(String username) {
        UserName = username;
    }
    public String getPassword() {
        return Password;
    }
    public void setPassword(String password) {
        Password = password;
    }


}

登录界面(login.jsp)

<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8" import="java.util.*"%>
<html>
<head></head>
<center><h3>用户登录</h3></center>
<body style="text-align: center;">
<%--${pageContext.request.contextPath 获取项目名【其实是获取根目录资源名】} --%>
    <form action="${pageContext.request.contextPath }/LoginServlet" method="post">
    <table border="1" width="600px" cellpadding="0" cellspacing="0" align="center" >
        <tr>
            <td height="30" align="center">用户名:</td>
            <td>  
            <input type="text" name="username" />${errorMsg }</td>
        </tr>
        <tr>
            <td height="30" align="center">密     码:</td>
            <td>  
              <input type="password" name="password" /></td>
        </tr>
        <tr>
            <td height="35" align="center">自动登录时间</td>
            <td>
                <input type="radio" name="autologin" 
                      value="${60*60*24*31 }" />一个月
                <input type="radio" name="autologin" 
                      value="${60*60*24*31*3 }" />三个月
                <input type="radio" name="autologin" 
                      value="${60*60*24*31*6 }" />半年
                <input type="radio" name="autologin" 
                      value="${60*60*24*31*12 }" />一年
            </td>
        </tr>
        <tr>
            <td height="30" colspan="2" align="center">
                      <input type="submit" value="登录" />
                  
                <input type="reset" value="重置" />
            </td>
        </tr>
    </table>
    </form>
</body>
<html>

成功登录界面(index.jsp)

<%@ 
page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8" import="java.util.*"
%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
    <title>显示登录的用户信息</title>
</head>
<body>
    <br />
    <center>
        <h3>欢迎光临</h3>
    </center>
    <br />
    <br />
    <c:choose>
        <%--用户信息为空 --%>
        <c:when test="${sessionScope.user==null }">
           <a href="${pageContext.request.contextPath }/login.jsp">用户登录</a>
        </c:when>
        <c:otherwise>
        <%--用户信息不为空 --%>
        欢迎你,${sessionScope.user.getUserName()}!
           <a href="${pageContext.request.contextPath }/LogoutServlet">注销</a>
        </c:otherwise>
    </c:choose>
    <hr />
</body>
</html>

信息检验

package p02_servlet;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;

import p01_user.User;
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    public LoginServlet() {
        super();
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取用户名和密码(从浏览器请求中获取)
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //判断用户名和密码是否正确
        if("111".equals(username)&&"222".equals(password)) {
            //创建user对象来封装正确的用户信息。
            User u = new User();
    
              try { 
                  BeanUtils.populate(u, request.getParameterMap()); 
                  }
              catch(IllegalAccessException e) { 
                  e.printStackTrace(); } 
              catch(InvocationTargetException e) { 
                      e.printStackTrace(); }
             
            /*
             * u.setUserName(username); u.setPassword(password);
             */
            //放到域对象中去,为了后面方便调用信息
            request.getSession().setAttribute("user", u);
            //获取用户是否点击了自动登录的标识符
            String autoLogin = request.getParameter("autologin");
            if(autoLogin!=null) {
                //说明用户点击了自动登录,这时候就要把信息保存到cookie中去
                Cookie c = new Cookie("autologin", username+"_"+password);
                int auto_save_time = Integer.parseInt(autoLogin);
                c.setMaxAge(auto_save_time);
                //设置路径,可以省略
                c.setPath(request.getContextPath());
                //响应到浏览器
                response.addCookie(c);
            }
            //重定向到主页面.getcontextPath是获取项目名称【站点目录名称】
            response.sendRedirect(request.getContextPath()+"/index.jsp");
        }else {
            //登陆失败了
            request.setAttribute("errorMsg", "用户名或密码错误");
            RequestDispatcher rd = request.getRequestDispatcher("/login.jsp");
            rd.forward(request, response);
        }

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

}

过滤cookie实现自动登录

package p03_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.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;

import p01_user.User;

/**
 * Servlet Filter implementation class AutoLoginFilter
 */
public class AutoLoginFilter implements Filter {
    public AutoLoginFilter() {
    }
    public void destroy() {
    }
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        //1,获取所有的cookie,在ServletRequest中没有获取所有cookie的方法
        HttpServletRequest req = (HttpServletRequest)request;
        Cookie[] cs = req.getCookies();
        //遍历cookie,找到自动登录的cookie
        String autologin = null;//cookie名称
        String user_massage = null;//保存在cookie中的用户信息
        for(int i = 0 ;cs!=null&&i<cs.length;i++) {
            String cookie_name = cs[i].getName();
            if("autologin".equals(cookie_name)) {
                user_massage = cs[i].getValue();
            }
        }


        if(user_massage!=null) {
            String[] msg = user_massage.split("_");
            String user_name = msg[0];
            String user_password = msg[1];
    
            if("111".equals(user_name)&&"222".equals(user_password)) {
                //创建user对象来封装正确的用户信息。
                User u = new User();
                u.setUserName(user_name);
                u.setPassword(user_password);
                //放到域对象中去,为了后面方便调用信息
                req.getSession().setAttribute("user", u);
            }
        }
        chain.doFilter(request, response);
    }

    /**
     * @see Filter#init(FilterConfig)
     */
    public void init(FilterConfig fConfig) throws ServletException {
        // TODO Auto-generated method stub
    }

}

登出

package p02_servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class LogoutServlet
 */
public class LogoutServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
   
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LogoutServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //清除session保存的用户信息
        request.getSession().removeAttribute("user");
        //清除cookie,就是创建同名的cookie
        Cookie c = new Cookie("autoLogin", "");
        c.setMaxAge(0);//0就是立马销毁
        c.setPath(request.getContextPath());
        response.addCookie(c);
        //重定向到主页面
        response.sendRedirect(request.getContextPath()+"/index.jsp");



    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

给TA买糖
共{{data.count}}人
人已赞赏
知识分享

Filter修改全站请求响应编码

2020-9-15 21:56:00

知识分享

Filter

2020-9-15 21:59:00

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索