• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
敬YES
Now Or Never
博客园    首页       联系   管理    订阅  订阅
JAVA入门[15]-过滤器filter

一、过滤器

过滤器是可用于 Servlet 编程的 Java 类,可以实现以下目的:

  • 在客户端的请求访问后端资源之前,拦截这些请求。
  • 在服务器的响应发送回客户端之前,处理这些响应。

参考:http://www.journaldev.com/1933/java-servlet-filter-example-tutorial

二、如何实现和配置过滤器

1.定义过滤器

过滤器实现接口: javax.servlet.Filter

示例:定义过滤器实现计数器,counterFilter实现Filter接口

public class counterFilter implements Filter {
    ServletContext context;
    int count;
    public void init(FilterConfig filterConfig) throws ServletException {
        context=filterConfig.getServletContext();
        String initCount=filterConfig.getInitParameter("count");
        count= Integer.valueOf(initCount);
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        context.log("===counterFilter do Filter====");
        count++;
        context.setAttribute("count",count);
        filterChain.doFilter(servletRequest,servletResponse);
    }

    public void destroy() {
    }
}

  

jsp调用:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<div>欢迎,您是第 <%=application.getAttribute("count")%> 位访客</div>

  

2.配置web.xml

过滤器是可插拔的,通过web.xml来声明,然后映射到您的应用程序的部署描述符中的 Servlet 名称或 URL 模式。

当 Web 容器启动 Web 应用程序时,它会为部署描述符中声明的每一个过滤器创建一个实例。

web.xml 中的 filter-mapping 元素的顺序决定了 Web 容器应用过滤器到 Servlet 的顺序。若要反转过滤器的顺序,只需要在 web.xml 文件中反转 filter-mapping 元素即可。

<filter>
    <filter-name>counterFilter</filter-name>
    <filter-class>filter.counterFilter</filter-class>
    <init-param>
        <param-name>count</param-name>
        <param-value>100</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>counterFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

  

3.如何给过滤器设置参数?

在web.xml中用init-param节点设置参数,然后在 init 方法使用 FilterConfig 对象获取参数。

context=filterConfig.getServletContext();
String initCount=filterConfig.getInitParameter("count");

  

三、使用注解@WebFilter定义过滤器

@WebFilter注解可以实现了javax.servlet.Filter接口的类定义为过滤器组件

 

@WebFilter(filterName = "filter1",initParams =@WebInitParam(name = "count",value = "100"),urlPatterns = "/*")
public class filter1 implements Filter {
    ServletContext context;
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        context.log("filter1.doFilter()");
        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {
        context=config.getServletContext();
    }
}

  

执行顺序:默认按照filter的名字排序,如果想调整顺序,还是要配置filter-mapping节点。

<filter-mapping>
        <filter-name>filter2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <filter-mapping>
        <filter-name>filter1</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

 

查看一下Tomcat Localhost Log:

02-Jun-2017 13:26:20.182 信息 [RMI TCP Connection(3)-127.0.0.1] org.apache.catalina.core.ApplicationContext.log Initializing Spring root WebApplicationContext
02-Jun-2017 13:26:21.302 信息 [RMI TCP Connection(3)-127.0.0.1] org.apache.catalina.core.ApplicationContext.log Initializing Spring FrameworkServlet 'springmvc'
02-Jun-2017 13:26:24.716 信息 [http-nio-8092-exec-1] org.apache.catalina.core.ApplicationContext.log ===counterFilter do Filter====
02-Jun-2017 13:26:24.716 信息 [http-nio-8092-exec-1] org.apache.catalina.core.ApplicationContext.log filter2.doFilter()
02-Jun-2017 13:26:24.716 信息 [http-nio-8092-exec-1] org.apache.catalina.core.ApplicationContext.log filter1.doFilter()

  

四、一个应用场景:过滤器防止中文编码

public class EncodeFilter implements Filter {
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest)servletRequest;
        HttpServletResponse response=(HttpServletResponse)servletResponse;
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        filterChain.doFilter(request,response);;
    }

    public void destroy() {

    }
}

作者:陈敬(公众号:敬YES)
出处:http://www.cnblogs.com/janes/
博客文章仅供交流学习,请勿用于商业用途。如需转载,请务必注明出处。

posted on 2017-06-02 13:30  敬YES  阅读(450)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3