用过滤器解决全站中文数据提交乱码问题

package cn.lfd.web.filter;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

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;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
/*
 * 解决全站中文数据提交乱码问题过滤器
 */
public class CharacterEncodingFilter implements Filter{//实现filter接口

	@Override
	public void destroy() {
		
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;//强转为HttpServletRequest
		HttpServletResponse response = (HttpServletResponse) resp;
		
		//这三行代码解决post提交中文乱码问题,但不能解决get提交中文乱码问题
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		
		MyCharacterEncodingRequest MyRequest = new MyCharacterEncodingRequest(request);
		chain.doFilter(MyRequest, response);//放行
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		
	}
}
//对HttpServletRequest对象中的getParameter方法进行增强
class MyCharacterEncodingRequest extends HttpServletRequestWrapper {

	public MyCharacterEncodingRequest(HttpServletRequest request) {
		super(request);
	}

	@Override
	public String getParameter(String name) {
		try {
			String value = super.getParameter(name);//调用父类得到数据
			if(value==null) {//如果没有返回数据,直接返回null
				return null;
			}
			if(!super.getMethod().equalsIgnoreCase("get")) {//如果是以post提交,直接返回value
				return value;
			}
			//进入下面说明是以get方式提交
			value = new String(value.getBytes("iso-8859-1"),"UTF-8");//把数据进行iso-8859-1解码并以UTF-8进行编码解决中文乱码
			return value;
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
	}
}

你可能感兴趣的:(filter,javaweb,乱码,过滤器,中文数据提交乱码)