过滤器概述
过滤器就好比应用中的保安,利用过滤器实现对请求和响应的拦截。
编写过滤器的步骤
编写一个类,实现javax.servlet.Filter接口
- package com.bjpowernode.servlet;
- import java.io.IOException;
- import javax.servlet.Filter;
- import javax.servlet.FilterChain;
- import javax.servlet.FilterConfig;
- import javax.servlet.ServletException;
- import javax.servlet.ServletRequest;
- import javax.servlet.ServletResponse;
- public class FilterDemo1 implements Filter {
- //由容器调用:完成过滤器的初始化
- public void init(FilterConfig filterConfig) throws ServletException {
- // TODO Auto-generated method stub
- }
- //由容器调用,每次请求和响应都会经过该方法
- public void doFilter(ServletRequest request, ServletResponse response,
- FilterChain chain) throws IOException, ServletException {
- System.out.println("FilterDemo1过滤器执行了");
- chain.doFilter(request, response); //放行,让下一个资源执行
- }
- //由容器调用:完成过滤器销毁时的清理工作
- public void destroy() {
- // TODO Auto-generated method stub
- }
- }
配置文件 web.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="2.5"
- xmlns="http://java.sun.com/xml/ns/javaee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
- http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
- <display-name></display-name>
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
- <filter>
- <filter-name>FilterDemo1</filter-name>
- <filter-class>com.bjpowernode.servlet.FilterDemo1</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>FilterDemo1</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- </web-app>