在SpringMVC開發過程中,經常會出現POST與Get請求亂碼的問題,那麼我們該如何解決這一問題呢?
POST中文亂碼
我們可以通過在web.xml文件中做一些配置解決這一問題,web.xml的配置如下所示:
<!-- 解決post中文亂碼錯誤 -->
<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>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<!-- 所有 -->
<url-pattern>/*</url-pattern>
</filter-mapping>
GET中文亂碼
對於Get中文亂碼我們有兩種處理辦法。
1、修改Tomcat文件編碼與我們的工程編碼一致
<Connector URIEncoding="utf-8" connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>
2、對請求的參數進行重新編碼
String userName new String(request.getParamter("userName").getBytes("ISO8859-1"),"utf-8")