Filter过滤器
使用Filter分为两部分:编写Filter和配置Filter。
1.编写Filter:
1)实现 javax.servlet.Filter 接口
2)实现接口中方法。
public void init(FilterConfig config) throws ServletException ,
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
FilterChain filterchain) throws IOException, ServletException ,
public void destroy() 三个方法。
其中,在doFilter中,filterchain.doFilter(servletRequest, servletResponse);用于继续执行原有请求的活动。
比如你访问了网站index.jsp页面,希望在访问这个页面前对数据库进行查询来初始化这个页面,那么可以在doFilter方法中,编写数据库查询的代码。但是之后一定要写filterchain.doFilter(servletRequest, servletResponse);这样页面才会在执行完数据库查询后跳转至index.jsp。即在filter后继续执行原有的请求。
注意:在doFilter的参数中的request和response参数为ServletRequest 和ServletResponse,如需获取session,可将它们转换为HttpServletRequest和HttpServletResponse。再通过request.getSession()获取HttpSession。
代码例子:
- import java.io.IOException;
- import javax.servlet.Filter;
- import javax.servlet.FilterChain;
- import javax.servlet.FilterConfig;
- import javax.servlet.ServletContext;
- import javax.servlet.ServletException;
- import javax.servlet.ServletRequest;
- import javax.servlet.ServletResponse;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import javax.servlet.http.HttpSession;
-
- public class UserroleFilter implements Filter{
-
- public void destroy() {
-
- }
-
- public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
- FilterChain filterchain) throws IOException, ServletException {
-
- HttpServletResponse response = (HttpServletResponse) servletResponse;
- HttpServletRequest request = (HttpServletRequest)servletRequest;
- HttpSession session = request.getSession();
-
- filterchain.doFilter(servletRequest, servletResponse);
- }
-
- public void init(FilterConfig config) throws ServletException {
-
- }
- }
2.配置Filter:
在web.xml中配置哪些请求需要使用过滤器进行过滤。
代码例子:
- <filter>
- <filter-name>selfTestFilter</filter-name>
- <filter-class>com.maggie.filter.SelfTestFilter</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>selfTestFilter</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>