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. [Java]Thinking in Java 练习2.14

    题目 在文档中加入各项的HTML列表. 代码 1 // object/Documentation4.java 2 // TIJ4 Chapter Object, Exercise 14, page 9 ...

  2. [杂记]LeTeX中使用tikz画图的一些实例

    出处:http://www.texample.net/tikz/examples/all/ 上述网站中的实例非常丰富,将代码修改一下再编译就能明白是什么意思,故不再赘述.

  3. 【C# TAP 异步编程】四、SynchronizationContext 同步上下文|ExecutionContext

    一.同步上下文(SynchronizationContext)概述 由来 多线程程序在.net框架出现之前就已经存在了.这些程序通常需要一个线程将一个工作单元传递给另一个线程.Windows程序以消息 ...

  4. redis主从复制,哨兵以及集群搭建部署

    redis主从复制 1.redis支持多实例的功能,一台机器上,可以运行多个单个的redis数据库 环境准备,运行3个redis数据库,达到 1主 2从的配置 主库 6379.conf port 63 ...

  5. docker学习笔记(5)——docker场景问题汇总(docker权限问题、docker文件目录、查看docker历史日志文件)

    参考资料: 1.博客1:https://www.jianshu.com/p/d645e2ed4bb1 使用docker的时候有一些常见问题: docker权限问题:一般输入docker命令前面都要加s ...

  6. 让Node.js支持ES6的语法

    使用命令,全局安装es-checker: cnpm install -g es-checker 安装好之后,执行以下命令来查看Node.js对ES6的支持情况. es-checker 可以从输出中查看 ...

  7. 转 Autofac怎么依赖注入ASP.NET MVC5类的静态方法

    之前我有介绍过怎么在ASP.NET mvc5中实现的Controller的依赖注入.一般是通过Contrller的构造函数的参数或者属性来注入,但是这有一个共同点就是调用这个类的方法一般都是实例方法, ...

  8. c/c++(c++和网络编程)日常积累(三)

    asio::transfer_all() 有空研究一下这个字段 malloc和new的区别 https://blog.csdn.net/weixin_39411321/article/details/ ...

  9. linux作业--第三周

    1.统计出/etc/passwd文件中其默认shell为非/sbin/nologin的用户个数,并将用户都显示出来 [root@localhost ~]# cat /etc/passwd | grep ...

  10. 微信小程序发布列表页面处理

    wxml: <!--pages/good_index/good_index.wxml--> <view class='list'> <block wx:for='{{in ...