---
title: "JSP编码过滤"
author: "minfirefox"
date: "2010-05-06T15:46:48Z"
tags: []
categories: ["企业架构"]
slug: "jsp"
draft: false
lastmod: "2010-05-06T16:03:33Z"
id: 660454
url: "https://minfirefox.iteye.com/blog/660454"
---

web.xml

```xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
	
		
	<filter> 
		<filter-name>CharacterEncoding</filter-name> 
		<filter-class>util.SetCharacterEncoding</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>GBK</param-value>
		</init-param>
	</filter>
	 
	<filter-mapping> 
		<filter-name>CharacterEncoding</filter-name> 
		<url-pattern>/*</url-pattern> 
	</filter-mapping> 
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

```

SetCharacterEncoding.java

```java
package util;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class SetCharacterEncoding implements Filter {
	protected FilterConfig filterConfig;
	private String targetEncoding="GBK";

	public void destroy() {
		this.filterConfig = null;		
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		request.setCharacterEncoding(targetEncoding);
		chain.doFilter(request, response);		
	}

	public void init(FilterConfig  config) throws ServletException {
		this.filterConfig=config;
		this.targetEncoding=config.getInitParameter("encoding");		
	}
	

}

```