过滤器的简单示例

1、核心配置

<filter>
   <filter-name>count</filter-name>
   <filter-class>com.my.filter.CountFilter</filter-class>
</filter>
<filter-mapping>
   <filter-name>count</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>


2、核心代码
public class CountFilter implements javax.servlet.Filter{
	
	ServletContext sc = null;
	
	public void destroy() {
		
	}
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
			
		int count = 0;
		String i = Integer.toString(count);
		HttpServletRequest req = (HttpServletRequest)request;
		HttpSession session = req.getSession();
		session.setAttribute("count", i);
		System.out.println("---------"+count);
		chain.doFilter(request, response);
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		sc = filterConfig.getServletContext();
	}
}

猜你喜欢

转载自nnbchuang.iteye.com/blog/1434530