相信许多开发JSP和Servlet网站的人都会碰到一个问题:中文乱码
今天遇到这个问题,研究了一下,并简单地实现了自己的乱码拦截器,先记录下来,日后再慢慢细化!
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.Map;
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.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet Filter implementation class CharSetFilter 自定义字符拦截器,防止页面乱码
*/
@WebFilter("/*")
public class CharSetFilter implements Filter {
/**
* Default constructor.
*/
public CharSetFilter() {
// 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 {
// TODO Auto-generated method stub
// 获取HTTP请求
HttpServletRequest httpRequest = (HttpServletRequest) request;
// 获取HTTP请求的方法
String requestMethod = httpRequest.getMethod();
// 判断请求方法,根据方法不同执行不同的解码
if (requestMethod.equals("POST")) {
httpRequest.setCharacterEncoding("utf-8");// 当请求为POST时
} else if (requestMethod.equals("GET")) {// 当请求为GET时
this.getDecode(httpRequest);
}
// pass the request along the filter chain
chain.doFilter(httpRequest, response);
}
/** 对get请求参数进行解码 */
@SuppressWarnings("rawtypes")
public void getDecode(HttpServletRequest request)
throws UnsupportedEncodingException {
Enumeration enu = request.getParameterNames();
while (enu.hasMoreElements()) {
String paraName = (String) enu.nextElement();
String paraValue = request.getParameter(paraName);
paraValue = new String(paraValue.getBytes("iso-8859-1"), "utf-8");
request.setAttribute(paraName, paraValue);
}
}
/**
* @see Filter#init(FilterConfig)
*/
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
}
}