filter-2

Filter的生命周期

当tomcat启动时,通过反射机制调用Filter的无参构造函数创建实例化对象,同时调用init方法实现初始化,doFilter方法调用多次,当tomcat关闭时调用destroy来销毁Filter对象。

无参构造函数:只调用一次,当tomcat启动时调用(Filter一定要进行配置)。

init方法:只调用一次,当Filter实例化对象创建完成后调用。
doFilter方法:调用多次,访问Filter的业务逻辑全写在Filter中。 destroy:只调用一次,Tomcat关闭时调用。

同时配置多个filter,filter
的调用顺序时由web.xml中的配置顺序来决定的,写在上面的配置先调用,因为web.xml是从上到下顺序读取的。

通过注解@WebFilter("/download.jsp")

实际开发中Filter的使用场景是:

1.统一处理中文乱码

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    servletResponse.setCharacterEncoding("UTF-8");
    servletRequest.setCharacterEncoding("UTF-8");
    servletResponse.setContentType("text/html;charset=UTF-8;pageEncoding=UTF-8");
    filterChain.doFilter(servletRequest, servletResponse);
}

2.屏蔽敏感词

    servletRequest.setCharacterEncoding("utf-8");
    //将敏感词替换成”***“
    String name = servletRequest .getParameter("name");
     name = name.replaceAll("敏感词","***");
     servletRequest.setAttribute("name",name);
    filterChain.doFilter(servletRequest,servletResponse);
}

3.控制资源的访问权限(登陆允许下载等)


 public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
 //强转使用HttpServlet里的方法
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取name、password值
        HttpSession session = request.getSession();
        String name = (String) session.getAttribute("name");
        String password = (String) session.getAttribute("password");
        //判断用户是否登录
        if (name == null && password == null) {
            //不是登陆状态
            response.sendRedirect("/login.jsp");
        }
        else{
            //name不为空放行
            filterChain.doFilter(servletRequest, servletResponse);
        }
上一篇:SpringBoot使用过滤器


下一篇:Java 防止SQL注入