hoyong

导航

SpringMVC Controller 接收页面传递的中文参数出现乱码(转)

  在Controller中接收到的POST参数如果是中文的话,显示为乱码。已知客户端传过来时编码为UTF-8。

问题产生分析:

spring MVC中默认的编码格式为“ISO-8859-1”,因此造成乱码。

简单的解决方式:

New String(request.getParameter("xxx").getBytes("iso-8859-1"),"utf-8")

最好的解决方式:

在web.xml中配置Spring字符过滤器,添加:

    
<!-- Spring字符集过滤器 -->
      
  <filter> <filter-name>SpringEncodingFilter</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> <filter-mapping> <filter-name>SpringEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>

 

GET方法接收到中文乱码在tomcat的server.xml添加URIEncoding="utf-8"
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
 
变更为:
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" URIEncoding="utf-8"/>

 

 

  • <!-- Spring字符集过滤器 -->
  • <filter>
  • <filter-name>SpringEncodingFilter</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>
  • <filter-mapping>
  • <filter-name>SpringEncodingFilter</filter-name>
  • <url-pattern>/*</url-pattern>
  • </filter-mapping>

posted on 2020-05-28 15:49  hoyong  阅读(865)  评论(0编辑  收藏  举报