一、过滤器

过滤器是可用于 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() { }
}

JAVA入门[15]-过滤器filter的更多相关文章

  1. Java基础95 过滤器 Filter

    1.filter 过滤器的概述 filter过滤器:是面向切面编程的一种实现策略,在不影响原来的程序流程的前提下,将一些业务逻辑切入流程中,在请求达到目标之前进行处理,一般用于编码过滤.权限过滤... ...

  2. java中的过滤器 --Filter

    package filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.Filter ...

  3. 【java web】过滤器filter

    一.过滤器简介 过滤器filter依赖于servlet容器 所谓过滤器顾名思义是用来过滤的,Java的过滤器能够为我们提供系统级别的过滤,也就是说,能过滤所有的web请求, 这一点,是拦截器无法做到的 ...

  4. Java Web(四) 过滤器Filter

    Filter概述 Filter意为滤镜或者过滤器,用于在Servlet之外对request或者response进行修改.Filter提出了过滤链的概念.一个FilterChain包括多个Filter. ...

  5. 使用java的自定义过滤器Filter 处理请求request 并响应response

    package com.enation.eop; import java.io.BufferedReader; import java.io.IOException; import java.io.I ...

  6. Java 中的过滤器Filter 和拦截器 Interceptor

    1.先说拦截器 Interceptor 本项目以springboot为例: 新建 InterceptorConfig package com.opendev.mystudy.MyInterceptor ...

  7. JAVA入门--目录

    在此记录自己的JAVA入门笔记,备忘 JAVA入门[1]--安装JDK JAVA入门[2]-安装Maven JAVA入门[3]—Spring依赖注入 JAVA入门[4]-IntelliJ IDEA配置 ...

  8. java之过滤器Filter

    Java三大器之过滤器(Filter)的工作原理和代码演示   一.Filter简介 Filter也称之为过滤器,它是Servlet技术中最激动人心的技术之一,WEB开发人员通过Filter技术,对w ...

  9. java过滤器Filter笔记

    一.Filter简介 Filter也称之为过滤器,它是Servlet技术中最激动人心的技术之一,WEB开发人员通过Filter技术,对web服务器管理的所有web资源:例如Jsp,Servlet, 静 ...

随机推荐

  1. [转载] Rss 与 Feed 的概念区别

    转载自http://www.chinaz.com/news/2011/0831/207961.shtml 可能很多刚刚接触博客的童鞋们,也和我一样不太了解:rss和feed概念或者说不了解rss和fe ...

  2. Python之numpy模块array简短学习

    1.简介 Python的lists是非常的灵活以及易于使用.但是在处理科学计算相关大数量的时候,有点显得捉襟见肘了. Numpy提供一个强大的N维数组对象(ndarray),包含一些列同类型的元素,这 ...

  3. [转]ORACLE递归查询

    转自:http://www.oracle.com/technetwork/cn/articles/hartley-recursive-086819-zhs.html 递归数据库处理,也称为材料清单 或 ...

  4. .NET自带缓存机制实例

    using System;using System.Web;using System.Web.Caching;using System.Collections.Generic;using System ...

  5. 关于node的前端项目编译时内存溢出问题

    最近在做一个基于vue 的多页面项目  , 页面n++多,编译时发生node内存溢出问题,继而百度之,得到解答,故记录之. '如图' 只需在 package.json 里面   加上    --max ...

  6. Python crawler access to web pages the get requests a cookie

    Python in the process of accessing the web page,encounter with cookie,so we need to get it. cookie i ...

  7. python学习笔记 map&&reduce

    ---恢复内容开始--- 1.map 1)map其实相当对吧运算符进行一个抽象,返回的是一个对象,但是这里不知道为什么不可以对一个map返回变量打印两次,难道是因为回收了? def f(x): ret ...

  8. Python中的单例模式

    在 Python 中,我们可以用多种方法来实现单例模式: 使用模块 使用 __new__ 使用装饰器(decorator) 使用元类(metaclass) # mysingleton.py class ...

  9. React Native学习——动画Animated(笔记)

    很多地方都需要用到动画,先看下文档吧. 一.两个互补的动画系统 LayoutAnimation:用于全局的布局动画 Animated:用于创建更精细的交互控制的动画(主要是这个) 二.Animated ...

  10. GIT常用命令(图片版)

    Git 是一个很强大的分布式版本控制系统.它不但适用于管理大型开源软件的源代码,管理私人的文档和源代码也有很多优势. 本来想着只把最有用.最常用的 Git 命令记下来,但是总觉得这个也挺有用.那个也用 ...