乱码问题:
获取请求参数中的乱码问题;
POST请求:request.setCharacterEncoding(“utf-8”);
GET请求:newString(request.getParameter(“xxx”).getBytes(“iso-8859-1”), “utf-8”);
响应的乱码问题:response.setContextType(“text/html;charset=utf-8”)。
基本上在每个Servlet中都要处理乱码问题,所以应该把这个工作放到过滤器中来完成。
package cn.itcast.web.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 { // 处理post请求编码问题,只对post请求起作用 request.setCharacterEncoding("utf-8"); HttpServletRequest req = (HttpServletRequest) request; /* * 调包request * 1. 写一个request的装饰类 * 2. 在放行时,使用我们自己的request */ if(req.getMethod().equals("GET")) { EncodingRequest er = new EncodingRequest(req);//调包request chain.doFilter(er, response); } else if(req.getMethod().equals("POST")) { chain.doFilter(request, response); } } public void init(FilterConfig fConfig) throws ServletException { } }
装饰者模式实现增强的request类 ,覆写getParameter方法
package cn.itcast.web.filter; import java.io.UnsupportedEncodingException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; /** * 装饰reqeust * @author cxf * */ public class EncodingRequest extends HttpServletRequestWrapper { private HttpServletRequest req; public EncodingRequest(HttpServletRequest request) { super(request); this.req = request; } public String getParameter(String name) { String value = req.getParameter(name); // 处理编码问题 try { value = new String(value.getBytes("iso-8859-1"), "utf-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } return value; } }
一般如果method设置为“post”,将不会出现乱码,如果将method设置为“get”,可能在汉字传入到后台后会出现乱码问题。
get方式传递中文参数乱码后台可以
将请求参数使用ISO-8859-1分解成字节数组,再将字节数组解码成字符串
String name = new String(request.getParameter("name").getBytes("ISO-8859-1"),"utf-8");
本文出自 “点滴积累” 博客,请务必保留此出处http://tianxingzhe.blog.51cto.com/3390077/1677824