zpjx 发表于 2017-2-3 10:47:08

Tomcat Web项目中文乱码问题解决方案

Tomcat常见乱码解决方案:(建议按顺序来看,逐个排除)
1.在项目中的web.xml中增加过滤器Filter
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
2.修改Tomcat的server.xml(用eclipse或类似的IDE,会有一个Servers项目,修改其下的server.xml;其它直接修改Tomcat下的)

找到这句话,增加一个属性
<Connector URIEncoding="UTF-8" connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/> 红色部分为需要增加的属性
3.通过ajax传输时乱码解决方案:
$.ajax( {
url:'test.htm',
      contentType : "application/x-www-form-urlencoded;charset=utf-8",
type: "POST",
dataType : 'json',
data: {
    'key1' : 'value1',
    'key2' : 'value2'
},
async: false,
cache:false,
success: function(data) {
         //to do someThing
      }
   红字标识的为特别注意的,设置请求的编码。

PS:ajax参数传递时data:应写成json的格式,如上。不能这样写:
data: 'key1' ='value1'+'&key2='+ 'value2',
即使一个参数也不能这样写。
正确: data: {
    'key1' : 'value1'
},
错误:data: 'key1' ='value1',

按照错误的写法,即使ajax传输方法为post,实际上也是用get方法传输的,即使加上contentType : "application/x-www-form-urlencoded;charset=utf-8",
经测试:还是乱码。貌似encode不了。改成正确的date数据,乱码解决。

4.用js函数对中文进行编码
传递参数的时候,对参数进行编码 paramName=encodeURI(OldparamName);也可用encodeURIComponent()
   服务器端无需做其他处理:String paramName=request.getParameter("paramName");
页: [1]
查看完整版本: Tomcat Web项目中文乱码问题解决方案