学习相关资料:

Java web开发——过滤器Filter的常见使用

简单通俗易懂的理解,就是类似于杀毒软件对电脑系统的功能和作用。即程序中的防火墙。

过滤器运行原理:

 

若有多个过滤器,则按顺序进行执行,直到最后一个过滤器通过后,才可进行下一步的请求。

项目要求和功能:

1.编码过滤器,对乱码进行过滤

2.登录权限过滤器,只有用户登陆后,才可以访问相关页面

项目思路:

1.在Filter中将reques和response进行强制转换

2.将所需要过滤的东西(本体为编码格式,和验证用户登录)的相关代码放入Filter中

3.对Filter设置适用范围,排除不用过滤的界面

项目源码:

对编码格式的过滤:

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.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet Filter implementation class LoginFilter
 */
@WebFilter(filterName="CodeFilter",urlPatterns="/*")//设置适用的范围
public class CodeFilter implements Filter {

    /**
     * Default constructor. 
     */
    public CodeFilter() {
        // TODO Auto-generated constructor stub
    }

    /**
     * @see Filter#destroy()
     */
    public void destroy() {
        // TODO Auto-generated method stub
    }

    /**
     * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
     */
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // TODO Auto-generated method stub
        
        HttpServletRequest req=(HttpServletRequest) request;
        HttpServletResponse res=(HttpServletResponse) response;
        
        //用户请求编码设置
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("ytf-8");
        response.setContentType("text/html;charset=utf-8");
        
        System.out.println("进入编码过滤器......");
        chain.doFilter(request, response);
        System.out.println("退出编码过滤器......");
        
    }

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

}
CodeFilter

对用户登录权限的过滤:

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.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet Filter implementation class LoginServlet
 */
@WebFilter(filterName="LoginFilter",
            urlPatterns="/*",
            initParams= {
                      @WebInitParam(name="noFilterUrl",value="login.jsp,LoginSErvlet")
              })//设置适用的范围,排除登录权限的过滤
public class LoginFilter implements Filter {

    private String[] noFilter;
    /**
     * Default constructor. 
     */
    public LoginFilter() {
        // TODO Auto-generated constructor stub
    }

    /**
     * @see Filter#destroy()
     */
    public void destroy() {
        // TODO Auto-generated method stub
    }

    /**
     * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
     */
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // TODO Auto-generated method stub
        //首先强制转换request,response
        HttpServletRequest req=(HttpServletRequest) request;
        HttpServletResponse res=(HttpServletResponse) response;
        
        //获取sessionz中的数值
        HttpSession session=req.getSession();
        String username=(String)req.getAttribute("username");
        
        //判断是否登录
        if(username!=null) {
            //已登录继续执行
        chain.doFilter(request, response);
        }else {
            //未登录,页面跳转
            String url=req.getRequestURI();//获取用户地址
            for(String temp:noFilter)
            {
                if(url.indexOf(temp)!=-1)
                {
                    chain.doFilter(request, response);//直接放行
                    return;
                }
            }
            res.sendRedirect("login.jsp");
        }
    }

    /**
     * @see Filter#init(FilterConfig)
     */
    public void init(FilterConfig fConfig) throws ServletException {
        //排除相关几年的过滤,以便正常运行
        // TODO Auto-generated method stub
        noFilter=fConfig.getInitParameter("noFilerUrl").split(",");//将数组noFilerUrl用","进行分割
    }

}
LoginFilter

servlet:

package com.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

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

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        
        System.out.println("进入servlet......");
        //接受用户登录信息
        String username=request.getParameter("username");
        String password=request.getParameter("password");
        //然后输出
        response.getWriter().print("用户名:"+username);
        response.getWriter().print("<br/>");
        response.getWriter().print("密码:"+password);
        
        //将用户信息放入到session中
        HttpSession session=request.getSession();
        session.setAttribute("username", username);
        //设置session的有效时间为10秒
        session.setMaxInactiveInterval(10);
        
        System.out.println("退出servlet......");
    }

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

}
FilterServlet

运行项目跟踪的测试顺序截图:

 

 遇到的问题:

原因:当设置用户登录权限的过滤器时,没有排除非不必过滤的代码和访问页面,从而造成了页面的死循环

 

解决方法:在LoginFilter进行排除不该受权限的内容

 1.

 2.

 

 3.

 

 

 解决时间:由于初次学Filter,所以解决的时间有点长,大约20分钟。通过查阅相关资料说,这种死循环错误在登录用户过滤器中是很常见的问题。特别注意。

 

posted on 2020-03-16 14:36  阡陌祁画  阅读(1272)  评论(0编辑  收藏  举报