Filter过滤器实现自动登录

Filter介绍
问题:Filter是什么,它能做什么?
    1.从两个方面来解析Filter是什么?
       1.功能  可以帮助我们对请求与响应操作进行过滤。
       2.技术  Sun公司定义的一个接口,javax.servlet.Filter

   2.Filter能完成什么操作?
       常用示例:
       1.通用编码过滤器.
       2.粗粒度的权限控制(url级别)
       3.过滤一些敏感字

Filter创建步骤:
        1.创建一个类实现javax.servlet.Filter接口。
        2.重写Filter接口中三个方法  init  doFilter  destroy.
        3.在web.xml文件中配置Filter

为什么在web.xml文件中配置Filter?
        1.Filter也是一个资源,也要被服务器加载,所以要在web.xml文件中配置.

        2.我们在web.xml文件中配置Filter的另一个目的是用来设置Filter拦截什么资源。


实例:需求:网站登录的时候当用户勾选自动登录选框之后,当用户再来登录,自动登录进网站。

      准备:简单的模拟如下页面:

     

  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>  
  3. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  4. <html>  
  5.   <head>  
  6.     <title></title>  
  7.     <meta http-equiv="pragma" content="no-cache">  
  8.     <meta http-equiv="cache-control" content="no-cache">  
  9.     <meta http-equiv="expires" content="0">      
  10.       </head>  
  11.   <body>  
  12.     <h3>这里是最美网</h3>  
  13.         <c:if test="${ not empty existUser}">       
  14.             <h2>欢迎您:${existUser.nickname }</h2>  
  15.         </c:if>  
  16.         <c:if test="${empty existUser }">  
  17.             <a href="${pageContext.request.contextPath }/login.jsp">请登录</a>  
  18.         </c:if>  
  19.     <h3>新闻标题</h3>  
  20.     <h2>大阅兵</h2>  
  21.   </body>  
  22. </html>  

    
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2.   
  3. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  4. <html>  
  5.   <head>  
  6.     <title></title>  
  7.     <meta http-equiv="pragma" content="no-cache">  
  8.     <meta http-equiv="cache-control" content="no-cache">  
  9.     <meta http-equiv="expires" content="0">      
  10.       </head>  
  11.   <body>  
  12.   <form action="${pageContext.request.contextPath }/login" method="post">  
  13.         <p style="color:red">${msg }</p>  
  14.         用户名:<input type="text" id="username" name = "username"><br>  
  15.         密码:<input type="password" id="password" name="password"><br>  
  16.         <input type="checkbox" name="autologin" value="auto_ok">自动登录<br>  
  17.         <button type="submit" value="登录">登录</button>  
  18.     </form>  
  19.   </body>  
  20. </html>  

   过滤器:

  1. public class myFilter implements Filter {  
  2.   
  3.     public void destroy() {  
  4.           
  5.     }  
  6.   
  7.     public void doFilter(ServletRequest request, ServletResponse response,  
  8.             FilterChain chain) throws IOException, ServletException {  
  9.           
  10.         /** 
  11.          * 从session中获取existUser 
  12.          * 如果不为空,说明已经登录并且没有关闭浏览器,放行 
  13.          * 如果为空说明没有登录,获取指定名称的cookie 
  14.          *   *如果找不到该cookie说明用户没有开启自动登录功能 ,放行 
  15.          *   *如果不为空,从cookie中拿到用户名和密码从数据库中查询 
  16.          *    *如果查不到 ,则用户名或密码改变了,不处理  放行 
  17.          *    *如果查到了放到session中,放行 
  18.          *  
  19.          */  
  20.           
  21.         //从session中获取用户existUser  
  22.         HttpServletRequest req =(HttpServletRequest) request ;  
  23.         HttpSession session = req.getSession();  
  24.         User existUser  =(User) session.getAttribute("existUser");  
  25.           
  26.         if (existUser!=null) {  
  27.               
  28.             chain.doFilter(req, response);  
  29.               
  30.         }else {  
  31.             //为空,说明没有登录  
  32.             //获取指定cookie  
  33.             //获取保存cookie的数组  
  34.             Cookie []cookies =  req.getCookies();  
  35.               
  36.             Cookie cookie =MyCookieUtile.findCookieByName(cookies, "autologin");  
  37.               
  38.             //判断cookie是否为空  
  39.             if (cookie==null) {  
  40.                   
  41.                 chain.doFilter(req, response);  
  42.                   
  43.             }else{  
  44.                   
  45.                 //获取cookie的value值  
  46.                 String value = cookie.getValue();  
  47.                 String username = value.split(":")[0];  
  48.                 String password = value.split(":")[1];  
  49.                   
  50.                 //拿到cookie中的用户名和密码去数据库中查  
  51.                 UserDao dao = new UserDao();  
  52.                   
  53.                 try {  
  54.                     User user = dao.checkUser(username, password);  
  55.                       
  56.                     if (user==null) {  
  57.                         chain.doFilter(req, response);  
  58.                     }else{  
  59.                         //说明成功,自动登录  
  60.                         session.setAttribute("existUser",user);  
  61.                         //放行  
  62.                         chain.doFilter(req, response);  
  63.                           
  64.                     }  
  65.                       
  66.                 } catch (SQLException e) {  
  67.                     // TODO Auto-generated catch block  
  68.                     e.printStackTrace();  
  69.                 }  
  70.                   
  71.             }                     
  72.               
  73.         }  
  74.           
  75.     }  
  76.   
  77.     public void init(FilterConfig filterConfig) throws ServletException {  
  78.           
  79.     }  
  80.   
  81. }  
       
  1. public class MyCookieUtile {  
  2.       
  3.     /** 
  4.      * 通过传入的cookie名称从传入的cookie数组中查找cookie 
  5.      * 如果数组为空,则没有找到返回为null 
  6.      * 如果不为空,找到返回cookie 
  7.      * @param cookies 
  8.      * @param cookiename 
  9.      * @return 
  10.      */   
  11.     public static Cookie findCookieByName(Cookie []cookies,String cookiename){  
  12.           
  13.         if (cookies==null) {  
  14.             return null;              
  15.         }else{    
  16.               
  17.             for (Cookie cookie : cookies) {  
  18.                 //获取cookie的名称和传入的名称对比  
  19.                 if (cookiename.equals(cookie.getName()) ) {  
  20.                     //相同则返回  
  21.                     return cookie;                    
  22.                 }  
  23.             }  
  24.             return null;  
  25.         }                 
  26.     }  
  27. }  

     servlet:

  1. public class LoginServlet extends HttpServlet {  
  2.   
  3.     public void doGet(HttpServletRequest request, HttpServletResponse response)  
  4.             throws ServletException, IOException {  
  5.           
  6.         /** 
  7.          * 接收参数 
  8.          * 根据用户名和密码查询数据库 
  9.          * 如果成功,返回到content页 
  10.          * 如果不成功,返回登录页继续登录 
  11.          */  
  12.         //解决中文乱码问题  
  13.         request.setCharacterEncoding("UTF-8");        
  14.         String username = request.getParameter("username");  
  15.         String password = request.getParameter("password");       
  16.         //调用dao层查询  
  17.         UserDao dao = new UserDao();  
  18.         try {  
  19.             User existUser = dao.checkUser( username, password);  
  20.               
  21.             if (existUser==null) {  
  22.                 request.setAttribute("msg""用户名或密码错误");  
  23.                 request.getRequestDispatcher("/login.jsp").forward(request, response);  
  24.                   
  25.             }else{  
  26.                 //登录成功  
  27.                   
  28.                 //回写cookie  
  29.                 String autologin = request.getParameter("autologin");  
  30.                   
  31.                 if ("auto_ok".equals(autologin)) {  
  32.                       
  33.                     String value = username+":"+password;  
  34.                     Cookie cookie = new Cookie("autologin", value);                   
  35.                     //设置有效时间  
  36.                     cookie.setMaxAge(60*60);  
  37.                     //设置有效路径  
  38.                     cookie.setPath("/");                      
  39.                     //回写到客户端  
  40.                     response.addCookie(cookie);       
  41.                       
  42.                 }                 
  43.                 request.getSession().setAttribute("existUser", existUser);                
  44.                   
  45.                 //重定向到content页面  
  46.                 response.sendRedirect(request.getContextPath()+"/content.jsp");  
  47.                   
  48.             }                 
  49.               
  50.         } catch (SQLException e) {  
  51.             e.printStackTrace();  
  52.         }         
  53.     }  
  54.   
  55.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  56.             throws ServletException, IOException {  
  57.         this.doGet(request, response);  
  58.   
  59.     }  
  60. }  


         最后在配置文件中web.xml文件中配置filter。这样当用户勾选了自动登录,关闭浏览器之后,再次访问即可自动登录进网站。

      在我们创建一个Filter时,要重写接口中的方法,有一个方法doFilter,它就是用于拦截操作的方法。在配置Filter时,可以指定拦截什么资源,当浏览器访问这个资源时,Filter的doFilter方法就会执行拦截操作。

      我们如果在Filter中,它的doFilter方法执行了,代表拦截操作开始了,如果想要让其可以继续向下访问资源,就需要通过doFilter方法的第三个参数FilterChain类型,调用它的doFilter方法,完成向下执行操作。

      总结:

   1.在Filter中具体的拦截操作是由doFilter方法执行的。  如果要想访问资源,需要chain.doFilter()放行.
   2.拦截什么资源是由web.xml文件中配置的Filter确定的。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值