注意:乱码和request的具体实现类有关,现在已经查到的是RequestDispatcher.forward调用前使用的是org.apache.catalina.connector.RequestFacade类而RequestDispatcher.forward调用后使用的是org.apache.catalina.core.ApplicationHttpRequest,他们内部在ParseParameter的时候, 用来解码的默认的编码逻辑不同,使用不同的协议时,影响乱码的因素不同! 
具体参考:Tomcat源码分析--ServletRequest.getParameterValues内部分析,Request字符集&QueryStringEncoding

乱码的产生 
譬如汉字“中”,以UTF-8编码后得到的是3字节的值%E4%B8%AD,然后通过GET或者POST方式把这3个字节提交到Tomcat容器,如果你不告诉Tomcat我的参数是用UTF-8编码的,那么tomcat就认为你是用ISO-8859-1来编码的,而ISO8859-1(兼容URI中的标准字符集US-ASCII)是兼容ASCII的单字节编码并且使用了单字节内的所有空间,因此Tomcat就以为你传递的用ISO-8859-1字符集编码过的3个字符,然后它就用ISO-8859-1来解码,得到中-,解码后。字符串中-在Jvm是以Unicode的形式存在的,而HTTP传输或者数据库保存的其实是字节,因此根据各终端的需要,你可以把unicode字符串中-用UTF-8编码后得到相应的字节后存储到数据库(3个UTF-8字符),也可以取得这3个字符对应的ISO-8859-1的3个字节,然后用UTF-8重新编码后得到unicode字符“中”(特性:把其他任何编码的字节流当作ISO-8859-1编码看待都没有问题),然后用response传递给客户端(根据你设置的content-type不同,传递的字节也是不同的!) 
总结:

下面的代码显示,使用不同的编码来Encoder会得到不同的结果,同时如果Encoder和Decoder不一致或者使用的汉字在编码ISO-8859-1中不存在时,都会表现为乱码的形式!

Java代码  
  1. try {
  2. // 汉字“中”用UTF-8进行URLEncode的时候,得到%e4%b8%ad(对应的ISO-8859-1的字符是中)
  3. String item = new String(new byte[] { (byte) 0xe4, (byte) 0xb8, (byte) 0xad }, "UTF-8");
  4. // 中
  5. System.out.println(item);
  6. item = new String(new byte[] { (byte) 0xe4, (byte) 0xb8, (byte) 0xad }, "ISO-8859-1");
  7. // 中
  8. System.out.println(item);
  9. System.out.println(new BigInteger("253").toByteArray());
  10. System.out.println(Integer.toBinaryString(253));
  11. // 中
  12. item = new String(item.getBytes("ISO_8859_1"), "UTF-8");
  13. System.out.println(item);
  14. // 中
  15. item = new String(item.getBytes("UTF-8"), "ISO_8859_1");
  16. System.out.println(item);
  17. // 汉字中以UTF-8编码为     %E4%B8%AD(3字节)
  18. System.out.println(URLEncoder.encode("中", "UTF-8"));
  19. // 汉字中以UTF-8编码为     %3F      (1字节 这是由于汉字在ISO-8859-1字符集中不存在,返回的是?在ISO-8859-1下的编码)
  20. System.out.println(URLEncoder.encode("中", "ISO-8859-1"));
  21. // 汉字中以UTF-8编码为     %D6%D0        (2字节)
  22. System.out.println(URLEncoder.encode("中", "GB2312"));
  23. // 把汉字中对应的UTF-8编码                 %E4%B8%AD 用UTF-8解码得到正常的汉字 中
  24. System.out.println(URLDecoder.decode("%E4%B8%AD", "UTF-8"));
  25. // 把汉字中对应的ISO-8859-1编码    %3F       用ISO-8859-1解码得到?
  26. System.out.println(URLDecoder.decode("%3F", "ISO-8859-1"));
  27. // 把汉字中对应的GB2312编码                 %D6%D0        用GB2312解码得到正常的汉字 中
  28. System.out.println(URLDecoder.decode("%D6%D0", "GB2312"));
  29. // 把汉字中对应的UTF-8编码                 %E4%B8%AD 用ISO-8859-1解码
  30. // 得到字符中(这个就是所谓的乱码,其实是3字节%E4%B8%AD中每个字节对应的ISO-8859-1中的字符)
  31. // ISO-8859-1字符集使用了单字节内的所有空间
  32. System.out.println(URLDecoder.decode("%E4%B8%AD", "ISO-8859-1"));
  33. // 把汉字中对应的UTF-8编码                 %E4%B8%AD 用GB2312解码
  34. // 得到字符涓?,因为前2字节 %E4%B8对应的GB2312的字符就是涓,而第3字节%AD在GB2312编码中不存在,故返回?
  35. System.out.println(URLDecoder.decode("%E4%B8%AD", "GB2312"));
  36. } catch (UnsupportedEncodingException e) {
  37. // TODO Auto-generated catch block
  38. e.printStackTrace();
  39. }

Tomcat关于encoding编码的默认设置以及相关标准: 
对于Get请求,"URI Syntax"规范规定HTTP query strings(又叫GET parameters)使用US-ASCII编码,所有不在这个编码范围内的字符,必须经常一定的转码:%61的形式(encode)。又由于ISO-8859-1 and ASCII对于0x20 to 0x7E范围内的字符是兼容的,大部分的web容器譬如Tomcat容器默认使用ISO-8859-1解码URI中%xx部分的字节。可以使用Connector中的URIEncoding来修改这个默认用来解码URI中%xx部分字节的字符集。URIEncoding要和get请求query string中encode的编码一直,或者通过设置Content-Type来告诉容器你使用什么编码来转码url中的字符

POST请求应该自己通过参数Content-Type指定所使用的编码,由于许多客户端都没有设置一个明确的编码,tomcat就默认使用ISO-8859-1编码。注意:用来对URI进行解码的字符集,Request字符集,Response字符集的区别!不同的Request实现中,对于上述3个编码的关系是不同的

对于POST请求,ISO-8859-1是Servlet规范中定义的HTTP request和response的默认编码。如果request或者response的字符集没有被设定,那么Servlet规范指定使用编码ISO-8859-1,请求和相应指定编码是通过Content-Type响应头来设定的。

如果Get、Post请求没有通过Content-Type来设置编码的话,Tomcat默认使用ISO-8859-1编码。可以使用SetCharacterEncodingFilter来修改Tomcat请求的默认编码设置(encoding:使用的编码, ignore:true,不管客户端是否指定了编码都进行设置, false,只有在客户端没有指定编码的时候才进行编码设置, 默认true) 
注意:一般这个Filter建议放在所有Filter的最前面(Servlet3.0之前基于filter-mapping在web.xml中的顺序, Servlet3.0之后有参数可以指定顺序),因为一旦从request里面取值后,再进行设置的话,设置无效。因为在第一次从request取值时,tomcat会把querystring或者post方式提交的变量,用指定的编码转成从parameters数组,以后直接从这个数组中获取相应参数的值!

到处都使用UTF-8建议操作:

  • 1, Set URIEncoding="UTF-8" on your <Connector> in server.xml.使得Tomcat Http Get请求使用UTF-8编码
  • 2, Use a character encoding filter with the default encoding set to UTF-8. 由于很多请求本身没有指定编码, Tomcat默认使用ISO-8859-1编码作为HttpServletRequest的编码,通过filter修改
  • 3, Change all your JSPs to include charset name in their contentType. For example, use <%@page contentType="text/html; charset=UTF-8" %> for the usual JSP pages and <jsp:directive.page contentType="text/html; charset=UTF-8" /> for the pages in XML syntax (aka JSP Documents). 指定Jsp页面使用的编码
  • 4, Change all your servlets to set the content type for responses and to include charset name in the content type to beUTF-8. Use response.setContentType("text/html; charset=UTF-8") or response.setCharacterEncoding("UTF-8"). 设置Response返回结果的编码
  • 5, Change any content-generation libraries you use (Velocity, Freemarker, etc.) to use UTF-8 and to specify UTF-8 in the content type of the responses that they generate.指定所有模版引擎佘勇的编码
  • 6, Disable any valves or filters that may read request parameters before your character encoding filter or jsp page has a chance to set the encoding to UTF-8. SetCharacterEncodingFilter一般要放置在第一位,否则可能无效
Java代码  
  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one or more
  3. * contributor license agreements.  See the NOTICE file distributed with
  4. * this work for additional information regarding copyright ownership.
  5. * The ASF licenses this file to You under the Apache License, Version 2.0
  6. * (the "License"); you may not use this file except in compliance with
  7. * the License.  You may obtain a copy of the License at
  8. *
  9. *     http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. package filters;
  18. import java.io.IOException;
  19. import javax.servlet.Filter;
  20. import javax.servlet.FilterChain;
  21. import javax.servlet.FilterConfig;
  22. import javax.servlet.ServletException;
  23. import javax.servlet.ServletRequest;
  24. import javax.servlet.ServletResponse;
  25. /**
  26. * <p>Example filter that sets the character encoding to be used in parsing the
  27. * incoming request, either unconditionally or only if the client did not
  28. * specify a character encoding.  Configuration of this filter is based on
  29. * the following initialization parameters:</p>
  30. * <ul>
  31. * <li><strong>encoding</strong> - The character encoding to be configured
  32. *     for this request, either conditionally or unconditionally based on
  33. *     the <code>ignore</code> initialization parameter.  This parameter
  34. *     is required, so there is no default.</li>
  35. * <li><strong>ignore</strong> - If set to "true", any character encoding
  36. *     specified by the client is ignored, and the value returned by the
  37. *     <code>selectEncoding()</code> method is set.  If set to "false,
  38. *     <code>selectEncoding()</code> is called <strong>only</strong> if the
  39. *     client has not already specified an encoding.  By default, this
  40. *     parameter is set to "true".</li>
  41. * </ul>
  42. *
  43. * <p>Although this filter can be used unchanged, it is also easy to
  44. * subclass it and make the <code>selectEncoding()</code> method more
  45. * intelligent about what encoding to choose, based on characteristics of
  46. * the incoming request (such as the values of the <code>Accept-Language</code>
  47. * and <code>User-Agent</code> headers, or a value stashed in the current
  48. * user's session.</p>
  49. *
  50. * @author Craig McClanahan
  51. * @version $Id: SetCharacterEncodingFilter.java 939521 2010-04-30 00:16:33Z kkolinko $
  52. */
  53. public class SetCharacterEncodingFilter implements Filter {
  54. // ----------------------------------------------------- Instance Variables
  55. /**
  56. * The default character encoding to set for requests that pass through
  57. * this filter.
  58. */
  59. protected String encoding = null;
  60. /**
  61. * The filter configuration object we are associated with.  If this value
  62. * is null, this filter instance is not currently configured.
  63. */
  64. protected FilterConfig filterConfig = null;
  65. /**
  66. * Should a character encoding specified by the client be ignored?
  67. */
  68. protected boolean ignore = true;
  69. // --------------------------------------------------------- Public Methods
  70. /**
  71. * Take this filter out of service.
  72. */
  73. public void destroy() {
  74. this.encoding = null;
  75. this.filterConfig = null;
  76. }
  77. /**
  78. * Select and set (if specified) the character encoding to be used to
  79. * interpret request parameters for this request.
  80. *
  81. * @param request The servlet request we are processing
  82. * @param result The servlet response we are creating
  83. * @param chain The filter chain we are processing
  84. *
  85. * @exception IOException if an input/output error occurs
  86. * @exception ServletException if a servlet error occurs
  87. */
  88. public void doFilter(ServletRequest request, ServletResponse response,
  89. FilterChain chain)
  90. throws IOException, ServletException {
  91. // Conditionally select and set the character encoding to be used
  92. if (ignore || (request.getCharacterEncoding() == null)) {
  93. String encoding = selectEncoding(request);
  94. if (encoding != null)
  95. request.setCharacterEncoding(encoding);
  96. }
  97. // Pass control on to the next filter
  98. chain.doFilter(request, response);
  99. }
  100. /**
  101. * Place this filter into service.
  102. *
  103. * @param filterConfig The filter configuration object
  104. */
  105. public void init(FilterConfig filterConfig) throws ServletException {
  106. this.filterConfig = filterConfig;
  107. this.encoding = filterConfig.getInitParameter("encoding");
  108. String value = filterConfig.getInitParameter("ignore");
  109. if (value == null)
  110. this.ignore = true;
  111. else if (value.equalsIgnoreCase("true"))
  112. this.ignore = true;
  113. else if (value.equalsIgnoreCase("yes"))
  114. this.ignore = true;
  115. else
  116. this.ignore = false;
  117. }
  118. // ------------------------------------------------------ Protected Methods
  119. /**
  120. * Select an appropriate character encoding to be used, based on the
  121. * characteristics of the current request and/or filter initialization
  122. * parameters.  If no character encoding should be set, return
  123. * <code>null</code>.
  124. * <p>
  125. * The default implementation unconditionally returns the value configured
  126. * by the <strong>encoding</strong> initialization parameter for this
  127. * filter.
  128. *
  129. * @param request The servlet request we are processing
  130. */
  131. protected String selectEncoding(ServletRequest request) {
  132. return (this.encoding);
  133. }
  134. }

设置utf8编码问题相关推荐

  1. python文件开头第一行设置utf-8编码

    python文件开头第一行设置utf-8编码 若不添加,文件中涉及到中文,执行会报错如下: SyntaxError: Non-ASCII character '\xe5' in file /Users ...

  2. tomcat设置UTF-8编码

    需要修改tomcat里的config.xml来修改,方法如下2种: 第一种: 1.在myclipse里,右键部署在tomcat里的项目,如下图所示,点击"浏览部署目录"(其他版本的 ...

  3. ASP .NET Core使用connection string连接MySQL/MariaDB,并设置UTF-8编码

    具体的使用文章参考我的这篇博客:ASP .NET Core Web 系列教程四:使用数据库进行交互(MySQL/MariaDB 版) 我这里介绍一下设置UTF-8的编码的Connection Stri ...

  4. Tomcat 中文乱码 设置UTF-8编码 问题解决办法

    在Java Web开发中,http请求带有中文字符的URI如果不处理容易出现乱码问题:这是因为Tomcat容器默认编码是iso-8859-1引起的,因此要避免出现乱码就要需要做相应的处理.解决办法如下 ...

  5. putty mtputty 设置utf8编码

    2013年10月30日 10:02:36 先load你指定的ip 然后选择左侧目录中的windows->translation 再在右侧选择utf-8编码 选中后,点击左侧目录中的session ...

  6. mac mysql utf 8编码_MacOS下MySQL设置UTF8编码问题

    1,检查默认安装的MySQL的字符集 mysql> show variables like '%char%'; +--------------------------+------------- ...

  7. Tomcat怎么设置UTF-8编码

    1.首先在Tomcat安装目录下面的conf文件夹下面找到server.xml文件,打开进行编辑 2.找到代码段 <Connector port="8080" protoco ...

  8. IDEA TOMCAT设置UTF-8编码

    输入-Dfile.encoding=utf-8

  9. html设置utf-8编码

    <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8&quo ...

最新文章

  1. 不得不知的小程序基本知识
  2. 开发日记-20190425 关键词 gradle基础学习 7年之约 启动篇
  3. Java 中的 Switch 都支持 String 了,为什么不支持 long?
  4. hdu 3006 位运算
  5. C++11 新特性简介
  6. MFC编程入门之十三(对话框:属性页对话框及相关类的介绍)
  7. spearman相关性分析_「同学交大经金考研」西安交通大学432统计学-必考简答题4:spearman等级相关系数...
  8. linux应用小技巧
  9. 轻量级数据sqlite的C++调用示例
  10. requestmapping注解作用_Java高级架构师-Spring 注解编程之注解属性别名与覆盖
  11. PHP设计模式——状态模式
  12. c语言单片机用法,单片机 C语音开发 sbit使用方法··
  13. 18-HTML标签的居中
  14. python虚拟变量回归_哑变量 虚拟变量 线性回归_spss 线性回归 哑变量
  15. Python tkinter库窗口化爬虫
  16. java 日期比较_java日期大小比较
  17. 谈谈测试过程中常见的几个问题
  18. HTTP/HTTPS
  19. python产生随机整数数组_生成随机整数数组
  20. 关于 QML Tumbler 自定义日历在响应onWheel事件后,其他原有mouse事件无法响应

热门文章

  1. css网格_一个CSS网格可以全部统治
  2. 02如何抓住重点,系统高效地学习数据结构与算法?
  3. 做Web前端开发的你必须会这几点!
  4. Linux Makefile 中的陷阱【转】
  5. Coding and Paper Letter(一)
  6. 算法导论 第三部分——基本数据结构——第14章:数据结构的扩张
  7. 2016年Web前端面试题
  8. Mac升级到Yosemite后默认的php版本不支持imagetfftext函数问题解决
  9. wpa_supplicant 无线网络配置
  10. locate: database too small: /var/db/locate.databas