一、过滤器

过滤器是可用于 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. selenium 之 ActionChains (二)

    今天,小编为大家介绍的是标题中的三个新方法,以及一个老方法 以下方法都需要操作一个名为Keys的包,先来简单认识下 ALT = u'\ue00a' CONTROL = u'\ue009' ENTER ...

  2. sql2012笔记

    收缩数据库日志文件1.数据库右键-->Options-->Revovery model =Full 改成 Simple2.数据库右键-->Tasks-->Shrink--> ...

  3. 什么是Node.js?带你初识Node

    什么是Node.js Nodejs是一个基于Chrome v8引擎的JavaScript运行环境 Node.js使用了一个事件驱动,非阻塞式I/O的模型,使其轻量又高效. Node.js 的包管理器 ...

  4. 【解决方案】纯js动态克隆表一行元素

    1 m = 0 ;// 用于区分input // 新增一条录入 function AddTR(){ m += 1; var tableObject = document.getElementById( ...

  5. 用python画一朵玫瑰花

    废话不多说,直接上代码 from turtle import * import time setup(600,800,0,0) speed(0) penup() seth(90) fd(340) se ...

  6. AES高级加密标准简析

    1 AES高级加密标准简介 1.1 概述 高级加密标准(英语:Advanced Encryption Standard,缩写:AES),在密码学中又称Rijndael加密法,是美国联邦政府采用的一种区 ...

  7. Python测试开发之random模块

    random模块是一个生成随机数.随机字符的模块,平时被使用的也非常多,下面是random模块的常用方法: random.random()生成一个0-1的随机小数,如果想要对随机小数保留两位小数,可以 ...

  8. NYOJ 119 士兵杀敌(三) RMQ ST

    NYOJ 119 士兵杀敌(三) RMQ ST 题目链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=119 思路: ST在线 预处理O(nlog ...

  9. php接入支付宝的流程

    php接入支付宝的流程写在这里供像我一样的小白参考. 1.首先要有一个创建一个应用(选好自己想要的功能,关于支付的功能,貌似都需要签约) 2.下载SDK&Dome(网址https://doc. ...

  10. UWP 共享文件——接收者

    UWP上共享,分为接收者(别人共享数据给你,你接收了,然后在做你的处理)和发送者(你给别人发送数据,就像你的App支持图片共享到微信好友或者朋友圈那样,虽然UWP上的微信并不支持这样子) 很简单(参考 ...