上篇已将介绍完了,下面来实践操作走一个:
首先在名为"com.caiduping"的包中创一个MyFilter的对象:
1 package com.caiduping;
2
3 import java.io.IOException;
4
5 import javax.servlet.Filter;
6 import javax.servlet.FilterChain;
7 import javax.servlet.FilterConfig;
8 import javax.servlet.ServletException;
9 import javax.servlet.ServletRequest;
10 import javax.servlet.ServletResponse;
11 import javax.servlet.http.HttpServletRequest;
12 import javax.servlet.ServletContext;
13
14 public class MyFilter implements Filter {
15 private int count;
16 @Override
17 public void destroy() {
18 // TODO Auto-generated method stub
19
20 }
21 //过滤处理方法
22 @Override
23 public void doFilter(ServletRequest request, ServletResponse response,
24 FilterChain chain) throws IOException, ServletException {
25 // TODO Auto-generated method stub
26 count++;
27 //将ServletRequest转化为HttpServletRequest
28 HttpServletRequest re=(HttpServletRequest) request;
29 //获取ServletContext
30 ServletContext Context=re.getSession().getServletContext();
31 //将数值存放于ServletContext中
32 Context.setAttribute("count", count);
33 //向下传递过滤器
34 chain.doFilter(request, response);
35 }
36 //初始化方法
37 @Override
38 public void init(FilterConfig filterConfig) throws ServletException {
39 // TODO Auto-generated method stub
40 //获得初始化参数
41 String paramter=filterConfig.getInitParameter("count");
42 //将字符串转化为int型
43 count=Integer.valueOf(paramter);
44 }
45
46 }
web.xml中配置为:
1 <?xml version="1.0" encoding="UTF-8"?>
2 <web-app version="3.0"
3 xmlns="http://java.sun.com/xml/ns/javaee"
4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
6 http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
7 <display-name></display-name>
8 <welcome-file-list>
9 <welcome-file>index.jsp</welcome-file>
10 </welcome-file-list>
11 <!-- 过滤声明 -->
12 <filter>
13 <filter-class>com.caiduping.MyFilter</filter-class>
14 <filter-name>count</filter-name>
15 <init-param>
16 <param-name>count</param-name>
17 <param-value>500</param-value>
18 </init-param>
19 </filter>
20 <!-- 过滤映射 -->
21 <filter-mapping>
22 <filter-name>count</filter-name>
23 <!-- 过滤URL映射 -->
24 <url-pattern>/*</url-pattern>
25 </filter-mapping>
26
27 </web-app>
run:(刷新逐渐递增)