过滤器的使用步骤:
a. 在web.xml中配置过滤器
<filter> <filter-name>checkSession</filter-name> <filter-class>com.zenisoft.usertagmng.support.CheckSessionFilter</filter-class> </filter> <filter-mapping> <filter-name>checkSession</filter-name> <url-pattern>*.do</url-pattern> </filter-mapping> |
b. 新建一个CheckSessionFilter类,实现Filter接口(Filter有三个方法:init方法,doFilter方法,destory方法。三个方法依次调用,其中init方法在服务器启动时最先调用)
c. 在web.xml中配置需要加载的参数
<context-param> <param-name>paramsPath</param-name> <param-value>/conf/params.properties</param-value> </context-param> |
d. 通过getInitparameter方法来调用web.xml中配置的参数,在web.xml中有两种参数的书写形式,在init方法中初始化这些参数,该方法使用如下:
1) <init-param>
String name=getInitParameter(“name”); 或 String name=getServletConfig().getInitParameter(“name”); |
2) <context-param>
String name=getServletContext().getInitParameter(“name”); 或 String name=getServletConfig().etServletContext().getInitParameter(“name”); |
Filter接口参数详解:
a. ServletRequest接口和ServletResponse接口:
当客户端有请求到来时,Servlet容器会创建一个ServletRequest对象来封装请求数据,同时创建一个ServletResponse对象来封装响应数据。
b. FilterChain接口:
过滤器的作用之一就是在用户的请求到达servlet之前,拦截下来做预处理,处理之后再执行” filterChain.doFilter(request,response) ” 这个方法,如果还有其他的过滤器,那么将处理好的请求传给下个过滤器,当把所有的请求处理好之后,再将处理完的请求发给servlet。