先记住下面这几点:
1、filter是servlet,jsp里面的东西,应该说是属于规范了,而拦截器是struts的东西,不通用。
2、一个请求,get,post等方式,到后台,必须先经过filter,然后经过Interceptor,最后在通过在filter或者Interceptor里面的跳转,跳到指定的页面或者action或者servlet中。
3、Interceptor只能拦截action请求,而filter是万能的,是请求就能拦截。
4、filter是链式处理的,也就是一个filter过滤完后,如果还有过滤,那就得继续。顺序根据web.xml里面的顺序来
5、filter是servlet包里面的一个借口,写一个filter,只要实现它,然后实现它的几个方法就算一个filter了。别忘记还得再web.xml里面配置
一个示例图 ,不是很正确,能看懂就看,看不懂就算了。请求先经过filter,再经过interceptor,再跳到相应页面。
现在写个简单也filter给大家看看:
- package com.wyp12.filter;
- 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;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- public class RequestFilter implements Filter {
- private FilterConfig config;
- public void destroy() {
- System.out.println("listener destory");
- config = null;
- }
- public void doFilter(ServletRequest paramServletRequest,
- ServletResponse paramServletResponse, FilterChain paramFilterChain)
- throws IOException, ServletException {
- HttpServletRequest request = (HttpServletRequest) paramServletRequest;
- System.out.println("do filter");
- System.out.println(request.getServletPath());
- HttpServletResponse response = (HttpServletResponse) paramServletResponse;
- System.out.println(config.getInitParameter("say"));
- response.sendRedirect("index.jsp");
-
-
-
-
- paramFilterChain.doFilter(paramServletRequest, paramServletResponse);
- }
- public void init(FilterConfig paramFilterConfig) throws ServletException {
- this.config = paramFilterConfig;
- }
- }
下面是配置文件
- <filter>
- <filter-name>myFilter</filter-name>
- <filter-class>com.wyp12.filter.RequestFilter</filter-class>
- <init-param>
- <param-name>say</param-name>
- <param-value>hello world !</param-value>
- </init-param>
- </filter>
- <filter-mapping>
- <filter-name>myFilter</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>