概述
A filter is an object that performs filtering tasks on either the request to a resource (a servlet or static content), or on the response from a resource, or both. Filters perform filtering in the doFilter method. Every Filter has access to a FilterConfig object from which it can obtain its initialization parameters, and a reference to the ServletContext which it can use, for example, to load resources needed for filtering tasks. Examples that have been identified for this design are: Authentication Filters Logging and Auditing Filters Image conversion Filters Data compression Filters Encryption Filters Tokenizing Filters Filters that trigger resource access events XSL/T filters Mime-type chain Filter
开发步骤
①定义FIlter类实现Filter接口
@WebServlet("/demo01") public class Demo01Servlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("Demo01Servlet"); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } }
②编写web.xml
<filter> <filter-name>Demo01Filter</filter-name> <filter-class>com.atguigu.filter.Demo01Filter</filter-class> </filter> <filter-mapping> <filter-name>Demo01Filter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
相关配置
①初始化参数
<filter> <filter-name>Demo03Filter</filter-name> <filter-class>com.atguigu.filter.Demo03Filter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>Demo03Filter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
public class Demo03Filter implements Filter { private String encoding; @Override public void init(FilterConfig filterConfig) throws ServletException { encoding = filterConfig.getInitParameter("encoding"); System.out.println("encoding = " + encoding); Enumeration<String> initParameterNames = filterConfig.getInitParameterNames(); while (initParameterNames.hasMoreElements()) { String initParameterName = initParameterNames.nextElement(); String initParameterValue = filterConfig.getInitParameter(initParameterName); System.out.println("initParameterName = " + initParameterName + " , initParameterValue = " + initParameterValue); } } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println("encoding = " + encoding); chain.doFilter(request, response);//相当于执行Demo01Servlet } }
②过滤路径
<filter> <filter-name>Demo04Filter</filter-name> <filter-class>com.atguigu.filter.Demo04Filter</filter-class> </filter> <!--2.1,完全匹配:以"/"开头--> <!-- <filter-mapping> <filter-name>Demo04Filter</filter-name> <url-pattern>/demo01</url-pattern> </filter-mapping> --> <!--2.2,目录匹配:以"/"开头,以"*"结尾--> <!-- <filter-mapping> <filter-name>Demo04Filter</filter-name> <url-pattern>/a/b/c/*</url-pattern> </filter-mapping> --> <!--2.3,后缀名匹配: 以"*"开头,以"后缀名"结尾--> <!-- <filter-mapping> <filter-name>Demo04Filter</filter-name> <url-pattern>*.html</url-pattern> </filter-mapping> --> <!--2.4,过滤指定Servlet--> <filter-mapping> <filter-name>Demo04Filter</filter-name> <servlet-name>Demo01Servlet</servlet-name> <servlet-name>Demo02Servlet</servlet-name> </filter-mapping>
概述
执行顺序
原因分析
代码实现
public class Demo05Filter implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println("Demo05Filter 过滤"); chain.doFilter(request, response);//相当于执行Demo01Servlet System.out.println("Demo05Filter 放行"); } }
public class Demo06Filter implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println("Demo06Filter 过滤"); chain.doFilter(request, response);//相当于执行Demo01Servlet System.out.println("Demo06Filter 放行"); } }
<filter> <filter-name>Demo05Filter</filter-name> <filter-class>com.atguigu.filter.Demo05Filter</filter-class> </filter> <filter-mapping> <filter-name>Demo05Filter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter> <filter-name>Demo06Filter</filter-name> <filter-class>com.atguigu.filter.Demo06Filter</filter-class> </filter> <filter-mapping> <filter-name>Demo06Filter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
概述
拦截行为
①REQUEST : 默认值,过滤请求
<!--①REQUEST : 默认值,过滤请求--> <filter-mapping> <filter-name>Demo07Filter</filter-name> <url-pattern>/*</url-pattern> <dispatcher>REQUEST</dispatcher> </filter-mapping>
②ERROR : 过滤跳转全局错误页面
<!--②ERROR : 过滤跳转全局错误页面--> <filter-mapping> <filter-name>Demo07Filter</filter-name> <url-pattern>/*</url-pattern> <dispatcher>REQUEST</dispatcher> <dispatcher>ERROR</dispatcher> </filter-mapping>
③FORWARD :过滤请求转发
<!--③FORWARD :过滤请求转发--> <filter-mapping> <filter-name>Demo07Filter</filter-name> <url-pattern>/*</url-pattern> <dispatcher>REQUEST</dispatcher> <dispatcher>FORWARD</dispatcher> </filter-mapping>
④INCLUDE : 过滤请求包含
<!--④INCLUDE : 过滤请求包含--> <filter-mapping> <filter-name>Demo07Filter</filter-name> <url-pattern>/*</url-pattern> <dispatcher>REQUEST</dispatcher> <dispatcher>INCLUDE</dispatcher> </filter-mapping>
概述
源码
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface WebFilter { WebInitParam[] initParams() default {}; String filterName() default ""; String[] servletNames() default {}; String[] value() default {}; String[] urlPatterns() default {}; DispatcherType[] dispatcherTypes() default {DispatcherType.REQUEST}; }
代码实现1
@WebFilter( filterName = "Demo08Filter", urlPatterns = { "/demo01", "/demo02" }, initParams = { @WebInitParam( name = "encoding", value = "utf-8" ), @WebInitParam( name = "encoding2", value = "gbk" ) }, dispatcherTypes = { DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.INCLUDE, DispatcherType.ERROR }, servletNames = { "Demo01Servlet", "Demo02Servlet" } ) public class Demo08Filter implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println("Demo08Filter 过滤"); chain.doFilter(request, response);//相当于执行Demo01Servlet System.out.println("Demo08Filter 放行"); } }
代码实现2
@WebFilter("/*") public class Demo09Filter implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println("Demo09Filter 过滤"); chain.doFilter(request, response);//相当于执行Demo01Servlet System.out.println("Demo09Filter 放行"); } }
概述
代码实现
public class MyServletRequestListener implements ServletRequestListener { @Override public void requestInitialized(ServletRequestEvent sre) { System.out.println("requestInitialized"); } @Override public void requestDestroyed(ServletRequestEvent sre) { System.out.println("requestDestroyed"); } }
<listener> <listener-class>com.atguigu.listener1.MyServletRequestListener</listener-class> </listener>
概述
代码实现
public class MyServletContextListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent sce) { System.out.println("contextInitialized"); } @Override public void contextDestroyed(ServletContextEvent sce) { System.out.println("contextDestroyed"); } }
<listener> <listener-class>com.atguigu.listener1.MyServletContextListener</listener-class> </listener>
概述
代码实现
public class MyServletRequestAttributeListener implements ServletRequestAttributeListener { @Override public void attributeAdded(ServletRequestAttributeEvent srae) { System.out.println("attributeAdded"); } @Override public void attributeRemoved(ServletRequestAttributeEvent srae) { System.out.println("attributeRemoved"); } @Override public void attributeReplaced(ServletRequestAttributeEvent srae) { System.out.println("attributeReplaced"); } }
<listener> <listener-class>com.atguigu.listener2.MyServletRequestAttributeListener</listener-class> </listener>
概述
代码实现
public class Student implements HttpSessionBindingListener { private Integer studentId; private String studentName; @Override public void valueBound(HttpSessionBindingEvent event) { System.out.println("Student绑定"); } @Override public void valueUnbound(HttpSessionBindingEvent event) { System.out.println("Student解绑"); } }
概述
钝化
活化
开发步骤
①JavaBean实体类实现Serializable接口
public class Teacher implements Serializable { private String teacherName; }
②编写tomcat的context.xml文件
<Manager className="org.apache.catalina.session.PersistentManager" saveOnRestart="true" maxIdleSwap="1"> <Store className="org.apache.catalina.session.FileStore" directory="E:\Program Files\apache-tomcat-9.0.56\conf\Session"/> </Manager>
概述
代码实现
public class Teacher implements Serializable , HttpSessionActivationListener { private String teacherName; @Override public void sessionWillPassivate(HttpSessionEvent se) { System.out.println("Teacher钝化"); } @Override public void sessionDidActivate(HttpSessionEvent se) { System.out.println("Teacher活化"); } }
概述
代码实现
@WebListener public class MyHttpSessionAttributeListener implements HttpSessionAttributeListener { @Override public void attributeAdded(HttpSessionBindingEvent se) { System.out.println("attributeAdded"); } @Override public void attributeRemoved(HttpSessionBindingEvent se) { System.out.println("attributeRemoved"); } @Override public void attributeReplaced(HttpSessionBindingEvent se) { System.out.println("attributeReplaced"); } }