JavaWeb--中文乱码小结
JavaWeb--中文乱码小结
出处:http://chriszz.sinaapp.com
0.纯粹html乱码:
换个editor吧(有时候notepad都比sublime_text好用),最好是在<head></head>之间添加<meta charset="utf-8">
1.jsp到jsp之间,表单
(假设包含表单的页面为a,提交的action为b)
get:不乱码
post:乱码(在b页面用<%request.setCharacterEncoding("utf-8");%>)
超链接形式的跳转,如果带有参数,本质上还是get方法,所以不会乱码
2.jsp到jsp之间,转发,转发参数乱码(<jsp:forward>+<jsp:param>)
需要在转发标签<jsp:forward>之前添加<%request.setCharacterEncoding("utf-8");%>
3.servlet页面out对象输出中文,乱码
在相应的方法中添加response.setContentType("text/hmtl;charset=UTF-8");
4.jsp提交表单到servlet,servlet获取表单变量乱码
若表单是post方法:在servlet相应方法中添加request.setCharacterEncoding("UTF-8");
若表单是get方法:在servlet相应方法中添加request.setCharacterEncoding("UTF-8");,或者用getBytes转码并构造新的String,例如;
String username = request.getParameter("username");
String name = new String(username.getBytes("ISO-8859-1"), "UTF-8");
总结一下:
对于post方法提交的表单,获取表单数据的页面都要用request.setCharacterEncoding("UTF-8");对于get方式提交的表单,获取表单数据的页面既可以用request.setCharacterEncoding("UTF-8")也可以用getBytes()的方法构造新的String;对于使用<jsp:param>传递参数的情况,需要在传递参数前设定request.setCharacterEncoding("UTF-8");
/******************************************************************************/
经过@小沫9的提醒,我写了一个编码过滤器 EncodingFilter.java,并在web.xml中进行了配置。通过测试,jsp提交表单到jsp页面、jsp提交表单到servlet、 jsp使用传递参数、Servlet页面用out对象输出,每种情况都可以不再设定 request.setCharacterEncoding(“UTF-8″),因为过滤器已经搞定了一切编码。代码入下:
1 package chris.filter 2 3 import java.io.IOException; 4 5 import javax.servlet.Filter; 6 import javax.servlet.FilterChain; 7 import javax.servlet.FilterConfig; 8 import javax.servlet.ServletException; 9 import javax.servlet.ServletRequest; 10 import javax.servlet.ServletResponse; 11 import javax.servlet.http.HttpServletRequest; 12 import javax.servlet.http.HttpServletResponse; 13 14 public class PageEncodingFilter implements Filter{ 15 16 private String encoding = "UTF-8"; 17 protected FilterConfig filterConfig; 18 19 20 public void init(FilterConfig filterConfig) throws ServletException { 21 this.filterConfig = filterConfig; 22 //本过滤器默认编码是UTF-8,但也可以在web.xml配置文件里设置自己需要的编码 23 if(filterConfig.getInitParameter("encoding") != null) 24 encoding = filterConfig.getInitParameter("encoding"); 25 } 26 27 public void doFilter(ServletRequest srequset, ServletResponse sresponse, 28 FilterChain filterChain) throws IOException, ServletException { 29 HttpServletRequest request = (HttpServletRequest)srequset; 30 request.setCharacterEncoding(encoding); 31 HttpServletResponse response = (HttpServletResponse)sresponse; 32 response.setCharacterEncoding(encoding); 33 filterChain.doFilter(srequset, sresponse); 34 } 35 36 public void destroy() { 37 this.encoding = null; 38 } 39 40 }
相应地,我在web.xml中的filter则设定为:
1 <filter> 2 <filter-name>Encoding</filter-name> 3 <filter-class>chris.filter.PageEncodingFilter</filter-class> 4 <init-param> 5 <param-name>encoding</param-name> 6 <param-value>UTF-8</param-value> 7 </init-param> 8 </filter> 9 10 <filter-mapping> 11 <filter-name>Encoding</filter-name> 12 <url-pattern>/*</url-pattern> 13 </filter-mapping>