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.
Filter是针对客户端向服务器请求资源的时候,过滤和校验该请求是否有效的一种方式,其具体的实现方式是.在web.xml中定义
<filter></filter>
xml 代码
- <filter>
- <filter-name>myFilter</filter-name>
- <filter-class>com.test.MyFilter</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>myFilter</filter-name>
- <servlet-name>myServlet</servlet-name>
- </filter-mapping>
- <servlet>
- <servlet-name>myServlet</servlet-name>
- <servlet-class>com.test.MyServlet</servlet-class>
- <load-on-startup>1</load-on-startup>
- </servlet>
- <servlet-mapping>
- <servlet-name>myServlet</servlet-name>
- <url-pattern>/myServlet</url-pattern>
- </servlet-mapping>
上面是请求一个myServlet时候,myFilter对其该请求过滤.代码如下:
java 代码
- package com.test;
- import javax.servlet.Filter;
- import javax.servlet.FilterConfig;
- import javax.servlet.FilterChain;
- import javax.servlet.ServletRequest;
- import javax.servlet.ServletResponse;
- import javax.servlet.http.HttpServletResponse;
- public class MyFilter implements Filter {
- public void init(FilterConfig filterConfig) {
- }
- public void destroy() {
- }
- public void doFilter(ServletRequest request, ServletResponse response,
- FilterChain chain) {
- String testValue = request.getParameter("TestValue");
- System.out.println("TestValue="+testValue);
- try {
- if (testValue.equals("1"))
- chain.doFilter(request, response);
- else{
- ((HttpServletResponse)response).sendRedirect("index.jsp");
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }