package com.kt.filter;

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;
import javax.servlet.http.HttpServletRequest;


public class EncodingFilter implements Filter {


	public void destroy() {
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		//设置响应编码
		response.setContentType("text/html;charset=utf-8");
		//把传进来的ServletRequest对象强转为HttpServletRequest类型的
		HttpServletRequest req = (HttpServletRequest) request;
		//判断请求方式,根据不同的请求方式设置不同的编码
		if (req.getMethod().equals("GET")) {
			//创建EncodingRquest对象
			EncodingRequest er = new EncodingRequest(req);
			chain.doFilter(er, response);
		} else if (req.getMethod().equals("POST")) {
			request.setCharacterEncoding("utf-8");
		chain.doFilter(request, response);
		}
	}

	public void init(FilterConfig fConfig) throws ServletException {
	}

}
//--------------------------
package com.kt.filter;

import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

public class EncodingRequest extends HttpServletRequestWrapper {
	private HttpServletRequest request;

	public EncodingRequest(HttpServletRequest request) {
		super(request);
		this.request = request;
	}

	public String getParameter(String name) {
		String value = request.getParameter(name);
		if (value != null) {
			try {
				value = new String(value.getBytes("ISO-8859-1"), "UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			return value;
		} else {
			return null;
		}
	}
}
xml配置
	<filter>
		<display-name>EncodingFilter</display-name>
		<filter-name>EncodingFilter</filter-name>
		<filter-class>com.kt.filter.EncodingFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>EncodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	                 QQ1015420659,喜欢结交朋友,如您有更好的解决方式请多分享