标签:解决中文乱码过滤器
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;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet Filter implementation class CharacterEncodingFilter
*/
public class CharacterEncodingFilter implements Filter {
/**
* Default constructor.
*/
public CharacterEncodingFilter() {
// TODO Auto-generated constructor stub
}
/**
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest)req;
HttpServletResponse response = (HttpServletResponse)res;
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
CharacterEncodingRequest characterEncodingRequest = new CharacterEncodingRequest(request);
chain.doFilter(characterEncodingRequest, response);
}
public void destroy() {
// TODO Auto-generated method stub
}
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
}
class CharacterEncodingRequest extends HttpServletRequestWrapper {
private HttpServletRequest request;
public CharacterEncodingRequest(HttpServletRequest request) {
super(request);
this.request = request;
}
@Override
public String getParameter(String name) {
String value = this.request.getParameter(name);
if (value == null) {
return null;
}
if (!this.request.getMethod().equalsIgnoreCase("get")) {
return value;
}
try {
value = new String(value.getBytes("ISO-8859-1"), this.getRequest()
.getCharacterEncoding());
} catch (Exception e) {
throw new RuntimeException(e);
}
return value;
}
}
本文出自 “德泽无忧” 博客,谢绝转载!
标签:解决中文乱码过滤器
原文地址:http://dezewuyou.blog.51cto.com/2628602/1829009