标签:过滤器解决中文乱码问题
package cn.itcast.demo1;
import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
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;
/**
* Servlet Filter implementation class EncodingFilter
*/
public class EncodingFilter implements Filter {
/**
* Default constructor.
*/
public EncodingFilter() {
// TODO Auto-generated constructor stub
}
/**
* @see Filter#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
}
/**
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
//1、创建被代理对象
//强转
final HttpServletRequest hsr = (HttpServletRequest) request;
//2、创建代理对象
HttpServletRequest proxyhsr = (HttpServletRequest) Proxy.newProxyInstance(hsr.getClass().getClassLoader(), hsr.getClass().getInterfaces(),new InvocationHandler() {
/**
* 处理程序
*
* 只需要增强getParameter方法
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if("getParameter".equals(method.getName())){
//增强
//分开解决乱码
//判断 请求方式
String m = hsr.getMethod();
if("GET".equalsIgnoreCase(m)){
//1、获取之前乱码值
String temp = (String) method.invoke(hsr, args);
//2、处理乱码
temp = new String(temp.getBytes("iso8859-1"),"utf-8");
return temp;
}else if("POST".equalsIgnoreCase(m)){
hsr.setCharacterEncoding("utf-8");
return method.invoke(hsr, args);
}else{
//如果是其他提交方式,不处理乱码,直接运行
return method.invoke(hsr, args);
}
}else{
//如果是其他方法,直接运行,不增强
return method.invoke(hsr, args);
}
}
});
chain.doFilter(proxyhsr, response);
}
/**
* @see Filter#init(FilterConfig)
*/
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
}
}
本文出自 “11768969” 博客,请务必保留此出处http://11778969.blog.51cto.com/11768969/1829118
标签:过滤器解决中文乱码问题
原文地址:http://11778969.blog.51cto.com/11768969/1829118