你的项目乱码了吗?
项目中遇到乱码很正常,特别是和别的项目对接时更是寻常,这周在项目中解决的GET乱码问题,场景是一个tomcat下运行了新老2个项目,其中老项目编码是GBK的,而新接口项目是采用UTF-8编码,现在主要的问题是因为tomcat的server.xml中的端口配置了
URIEncoding="GBK",这就会导致所有访问这个tomcat下的GET请求url参数都会被GBK格式解码,即使请求头上有Content-Type为UTF-8格式或者有request.setCharacterEncoding("UTF-8");也不好使,如下是解决方案,另加遇到post乱码时 通常解决方案
1.本项目中解决方案:
A:新加一个端口,这个端口配置URIEncoding="UTF-8",在新项目乱码的请求走这个端口
<Connector port="444" protocol="HTTP/1.1" SSLEnabled="true" URIEncoding="UTF-8"
maxThreads="500" scheme="https" secure="true"
clientAuth="false" sslProtocols="TLSv1.0,TLSv1.1,TLSv1.2" sslEnabledProtocols="TLSv1.0,TLSv1.1,TLSv1.2"
ciphers="TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384,TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,TLS_ECDHE_RSA_WITH_RC4_128_SHA,TLS_RSA_WITH_AES_128_CBC_SHA256,TLS_RSA_WITH_AES_128_CBC_SHA,TLS_RSA_WITH_AES_256_CBC_SHA256,TLS_RSA_WITH_AES_256_CBC_SHA,SSL_RSA_WITH_RC4_128_SHA"
keystoreFile="/etc/simp_fort/cacenter/server/fort.simp.com.p12" keystorePass="11111111" keystoreType="PKCS12"
truststoreFile="/etc/simp_fort/cacenter/server/truststore" truststorePass="11111111" truststoreType="JKS"/>
<Connector port="8444" protocol="HTTP/1.1" SSLEnabled="true" URIEncoding="UTF-8"
maxThreads="500" scheme="https" secure="true"
clientAuth="false" sslProtocols="TLSv1.0,TLSv1.1,TLSv1.2" sslEnabledProtocols="TLSv1.0,TLSv1.1,TLSv1.2"
ciphers="TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384,TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,TLS_ECDHE_RSA_WITH_RC4_128_SHA,TLS_RSA_WITH_AES_128_CBC_SHA256,TLS_RSA_WITH_AES_128_CBC_SHA,TLS_RSA_WITH_AES_256_CBC_SHA256,TLS_RSA_WITH_AES_256_CBC_SHA,SSL_RSA_WITH_RC4_128_SHA"
keystoreFile="/etc/simp_fort/cacenter/server/fort.simp.com.p12" keystorePass="11111111" keystoreType="PKCS12"
truststoreFile="/etc/simp_fort/cacenter/server/truststore" truststorePass="11111111" truststoreType="JKS"/>
B:请求参数用gbk格式编码
2.其它情况get请求乱码处理方案:
A:tomcat中sevice.xml对应端口配置URIEncoding="UTF-8"
B:仅限于ISO8859-1编码转GBK或者UTF-8对应方法转码new String(json.getBytes("ISO8859- 1"),"UTF-8");
(new String(json.getBytes("gbk"),"UTF-8")这个方法是把gbk编码格式转为utf-8格式,但是有个问题是GBK转UTF-8时,奇数个中文会乱码,偶数个中文不会乱码。)
3.post请求乱码处理方案:
1.使用过滤器过滤请求设置编码(传统ssm还有web.xml的项目)
<!--配置过滤器,使编码变为utf-8-->
<filter>
<filter-name>endocding</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>
</filter>
2.方法中使用request.setCharacterEncoding("UTF-8");设置请求编码 response.setCharacterEncoding("UTF-8");设置响应编码
上一篇: 有趣的题
下一篇: 面试官一问一答式的前端面试题