Filter过滤器

当访问服务器资源的时候,过滤器可以将i气你个球拦截下来,完成一些特殊的功能

过滤器的作用:

  一般用于完成通用的操作,如验证登陆,统一的编码处理,敏感字符过滤。就是打游戏骂人,会出现****

快速入门

  步骤:1定义一个类,实现接口Filter

     2 复写方法

      3 配置拦截资源,包括注解配置和,web.xml配置

1111

2222

package com.quan.web.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException; @WebFilter("/*")
public class FilterDemo implements Filter {
public void destroy() {
}
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
System.out.println("FilterDemo被执行了。。。。"); }
@Override
public void init(javax.servlet.FilterConfig config) throws ServletException { } }

333注解:

@WebFilter("/*") 拦截所有请求:

测试

自行加入sevlet容器管理 Tomcat ;

运行

拦截器进行放行操作

再上面的doFilter方法中加入

chain.doFilter(req,resp);

测试

filter的web.xml配置

和sevlet的配置差不多,只是这个是拦截的路径

   <filter>
<filter-name>FilterDemo</filter-name>
<filter-class>com.quan.web.filter.FilterDemo</filter-class>
</filter>
<filter-mapping>
<filter-name>FilterDemo</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

  

过滤器的执行流程

我们可以新建一个filter

@WebFilter("/*")
public class FilterDemo2 implements Filter {
public void destroy() {
} public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
//对request对象请求消息增强
System.out.println("filterDemo2 doing.....");
chain.doFilter(req, resp); //对response对象的响应消息增强
System.out.println("filterDemo2 ending....");
} public void init(FilterConfig config) throws ServletException { } }

修改一下index.jsp

<html>
<head>
<title>$Title$</title>
</head>
<body>
index.jsp.....
<%
System.out.println("index.jsp....");
%>
</body>
</html>

备注:两个百分号之间,用于输出到控制台

运行结果;

filterDemo2 doing.....
index.jsp....
filterDemo2 ending....

由上面的测试可以知道

filter执行的过程是,到达filter,

11进行一些请求增强操作,

22然后通过放行到后端的servlet 或者资源,

33再回到filer中放行之后的操作

filter的生命周期

11再服务器启动后,创建Filter对象,然后调用init方法,用于加载资源

22每一次请求拦截资源时候,会执行

33服务器关闭后,Filter对象被销毁,,释放资源

过程理解

@WebFilter("/*")
public class FilterDemo3 implements Filter {
/**
* 服务器关闭后,Filter对象被销毁,,释放资源
* 如果服务器是正常关闭,则会执行destroy方法
* 只执行一次
*/
public void destroy() {
System.out.println("destroy.....");
} /**
* 每一次请求拦截资源时候,会执行
* @param req
* @param resp
* @param chain
* @throws ServletException
* @throws IOException
*/
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
System.out.println("doFilter....");
chain.doFilter(req, resp);
} /**
* 再服务器启动后,创建Filter对象,然后调用init方法,用于加载资源
* 只执行一次
* @param config
* @throws ServletException
*/
public void init(FilterConfig config) throws ServletException {
System.out.println("init....");
} }

查看日志

过滤器配置----拦截路径配置

1具体路径配置

/index.jsp  只有访问index.jsp资源时,过滤器才会被执行

2目录拦截配置

/user/*    访问/user下的所有资源时,过滤器都会被执行

3后缀名拦截:

*.jsp    访问所有后缀名为jsp资源时,过滤器都会被执

4拦截所有资源:

/*      访问所有资源时,过滤器都会被执行

//@WebFilter("/index.jsp")   只有访问index.jsp资源时,过滤器才会被执行
//@WebFilter("/user/*") 访问/user下的所有资源时,过滤器都会被执行
@WebFilter("*.jsp") //访问所有后缀名为jsp资源时,过滤器都会被执行
public class FilterDemo4 implements Filter {
public void destroy() {
} public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
System.out.println("filterDemo4");
chain.doFilter(req, resp);
} public void init(FilterConfig config) throws ServletException { } }

过滤器配置----拦截方式配置

资源被访问的方式

注解配置:

dispatcherTypes = DispatcherType.REQUEST
@WebServlet("/user/updateServlet")
public class ServletDemo2 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("updateServlet"); //转发到index.jsp
request.getRequestDispatcher("/index.jsp").forward(request,response);
} protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}
//浏览器直接请求index.jsp资源时,该过滤器才会被执行
@WebFilter(value = "/index.jsp",dispatcherTypes = DispatcherType.REQUEST)
public class FilterDemo5 implements Filter {
public void destroy() {
} public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
System.out.println("filterDemo5....");
chain.doFilter(req, resp);
} public void init(FilterConfig config) throws ServletException { } }

直接访问时:

http://localhost:8080/quan/index.jsp

结果:

通过间接转发访问时:

http://localhost:8080/quan/user/updateServlet

dispatcherTypes = DispatcherType.FORWARD
只有转发访问index.jsp时,该过滤器才会被执行
@WebFilter(value = "/index.jsp",dispatcherTypes = DispatcherType.FORWARD)
dispatcherTypes可以配置多个值
@WebFilter(value = "/index.jsp",dispatcherTypes = {DispatcherType.FORWARD,DispatcherType.REQUEST})

web.xml配置

  <filter>
<filter-name>FilterDemo</filter-name>
<filter-class>com.quan.web.filter.FilterDemo</filter-class>
</filter>
<filter-mapping>
<filter-name>FilterDemo</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>FORWARD</dispatcher>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
<dispatcher> 标签也是有五个值得。

过滤器链(配置多个过滤器)

执行顺序

编写第一个过滤器:

package com.quan.web.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException; @WebFilter("/*")
public class FilterDemo6 implements Filter {
public void destroy() {
} public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
System.out.println("FilterDemo6执行!!!!!!!!!!!");
chain.doFilter(req, resp);
System.out.println("FilterDemo6回来执行!!!!!!!!!!!"); } public void init(FilterConfig config) throws ServletException { } }

编写第二个过滤器:

package com.quan.web.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException; @WebFilter("/*")
public class FilterDemo7 implements Filter {
public void destroy() {
} public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
System.out.println("FilterDemo7执行!!!!!!!!!!!");
chain.doFilter(req, resp);
System.out.println("FilterDemo7回来执行!!!!!!!!!!!"); } public void init(FilterConfig config) throws ServletException { } }

测试访问路径:

http://localhost:8080/quan/index.jsp

日志输出:

FilterDemo6执行!!!!!!!!!!!
FilterDemo7执行!!!!!!!!!!!
index.jsp....
FilterDemo7回来执行!!!!!!!!!!!
FilterDemo6回来执行!!!!!!!!!!!

过滤器先后顺序问题:

  

Filter的小案例------登陆验证

Listener

监听器的使用步骤

web.xml配置

<!--    配置监听器-->
<listener>
<listener-class>com.quan.web.listener.ListenerDemo1</listener-class>
</listener> <!-- 资源文件-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>application.xml</param-value>
</context-param>

监听器内容:

public class ListenerDemo1 implements ServletContextListener {

    // Public constructor is required by servlet spec
public ListenerDemo1() {
} // // -------------------------------------------------------
// 监听ServletContext对象创建的,ServletContext对象服务器启动后自动创建
// 服务器启动后自动调用
// -------------------------------------------------------
public void contextInitialized(ServletContextEvent sce) {
System.out.println("ServletContextEvent done.....");
//一般会进行资源的加载文件
//1获取ServletContext对象
ServletContext servletContext = sce.getServletContext();
//2加载资源文件
String contextConfigLocation = servletContext.getInitParameter("contextConfigLocation");
//3获取真实路径
InputStream fis = servletContext.getResourceAsStream(contextConfigLocation); System.out.println(fis); } /**
* 再服务器关闭后,ServletContext对象被销毁,
* 当服务器正常关闭后,该方法被调用
* @param sce
*/
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("ServletContextEvent out....");
} }

java-web中的Filter&Listener的更多相关文章

  1. Java Web学习总结(29)——Java Web中的Filter和Interceptor比较

    1. 背景 在设计web应用的时候,用户登录/注册是必不可少的功能,对用户登录信息进行验证的方法也是多种多样,大致可以认为如下模式:前端验证+后台验证.根据笔者的经验,一般会在前端进行一些例如是否输入 ...

  2. Java web中常见编码乱码问题(一)

    最近在看Java web中中文编码问题,特此记录下. 本文将会介绍常见编码方式和Java web中遇到中文乱码问题的常见解决方法: 一.常见编码方式: 1.ASCII 码 众所周知,这是最简单的编码. ...

  3. Java Web中解决乱码的方式

    Java Web中解决乱码的方式 方式一:添加编码过滤器 package com.itmacy.dev.filter; import javax.servlet.*; import javax.ser ...

  4. 【java web】过滤器filter

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

  5. Java Web 中 过滤器与拦截器的区别

    过滤器,是在java web中,你传入的request,response提前过滤掉一些信息,或者提前设置一些参数,然后再传入servlet或者struts的 action进行业务逻辑,比如过滤掉非法u ...

  6. JAVA WEB 中的编码分析

    JAVA WEB 中的编码分析 */--> pre.src {background-color: #292b2e; color: #b2b2b2;} pre.src {background-co ...

  7. Java web中常见编码乱码问题(二)

    根据上篇记录Java web中常见编码乱码问题(一), 接着记录乱码案例: 案例分析:   2.输出流写入内容或者输入流读取内容时乱码(内容中有中文) 原因分析: a. 如果是按字节写入或读取时乱码, ...

  8. 深入分析Java Web中的编码问题

    编码问题一直困扰着我,每次遇到乱码或者编码问题,网上一查,问题解决了,但是实际的原理并没有搞懂,每次遇到,都是什么头疼. 决定彻彻底底的一次性解决编码问题. 1.为什么要编码 计算机的基本单元是字节, ...

  9. 解决java web中safari浏览器下载后文件中文乱码问题

    解决java web中safari浏览器下载后文件中文乱码问题 String fileName = "测试文件.doc"; String userAgent = request.g ...

  10. Java Web 中使用ffmpeg实现视频转码、视频截图

    Java Web 中使用ffmpeg实现视频转码.视频截图 转载自:[ http://www.cnblogs.com/dennisit/archive/2013/02/16/2913287.html  ...

随机推荐

  1. RFC3918聚合组播吞吐量测试——网络测试仪实操

    一.简介 1.RFC3918简介 历史 · 在1999年3月成为正式标准 功能 · 评测网络互连设备或网络系统的性能 · 网络设备: 交换机,路由器- 内容 · 定义了一整套测试方法,为不同厂家的设备 ...

  2. python运算符优先级及部分运算

    在python里面,有很多运算符,比如:算术运算符.赋值运算符.比较运算符.逻辑运算符.成员运算符.身份运算符和位运算符等.这里主要来看看这些运算符的优先级:从上到下优先级依次递减. 优先顺序 运算符 ...

  3. Python:使用piecewise与curve_fit进行三段拟合

    x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ,11, 12, 13, 14, 15,16,17,18,19,20,21], dtype=float) y = ...

  4. Chrome:开发者模式下选取网页元素对应的代码

    CTRL+SHIFT+C 或者 左上角的类鼠标图标

  5. LeetCode-071-简化路径

    简化路径 题目描述:给你一个字符串 path ,表示指向某一文件或目录的 Unix 风格 绝对路径 (以 '/' 开头),请你将其转化为更加简洁的规范路径. 在 Unix 风格的文件系统中,一个点(. ...

  6. C# HttpClient类库

    示例代码: 1 using System.Net.Http; 2 using System.Net.Http.Headers; 3 using System.Threading.Tasks; 4 5 ...

  7. linux作业--第十周

    1.在阿里云服务器搭建openv-p-n(有条件的同学再做) 2.通过编译.二进制安装MySQL5.7 编译安装MySQL5.7 安装相关包 yum -y install libaio numactl ...

  8. 编写第一个GET、POST接口[renren-fast框架系列(1)]

    配置好 renren-fast 脚手架,学习完 Spring MVC 架构后,我需要具体调试 renren-fast 的接口,比如要新增某个接口. 什么是前后端分离 运行 renren-fast 项目 ...

  9. const 对象的属性能否修改

    const保证的并不是变量的值不能改动,而是变量指向的那个内存地址不能改动. 对于基本类型的数据(数值.字符串.布尔值),其值就保存在变量指向的那个内存地址,因此等同于常量. 对于引用类型的数据(主要 ...

  10. sql面试 case /union all

    1.sum(case when results='胜' then 1 else 0 end) as '胜' 要求查询出结果: sql语句实现: select date, sum(case when r ...