---
title: "过滤器的简单示例"
author: "NNBchuang"
date: "2012-03-01T17:09:08Z"
tags: []
categories: ["互联网"]
slug: "untitled"
draft: false
lastmod: "2012-03-01T17:09:08Z"
id: 1434530
url: "https://nnbchuang.iteye.com/blog/1434530"
---

1、核心配置


```java
<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、核心代码

```java
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();
	}
}
```