【Question03】使用 Spring mvc 框架的時候如何處理亂碼問題
阿新 • • 發佈:2019-02-01
開篇
如題,反正亂碼問題是很常見的,那就記錄一下吧。在使用 Spring mvc 的框架過程中,我們經常會出現亂碼問題,反正是層出不窮的。這裡提供如下的解決方案。
GET 請求亂碼問題
在 tomcat 的安裝目錄下,找到 conf 資料夾,然後開啟 server.xml,利用編輯器的檢索功能找到如下程式碼:
<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>
將其替換成:
<Connector URIEncoding="UTF-8" connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443" />
GET 請求再無亂碼!I promise!
POST 請求亂碼問題
這個就很好解決啦,一般亂碼都是配置一個過濾器,Spring mvc 也不例外。在專案的 web.xml 檔案中做如下配置:
<filter> <filter-name>CharacterFilter</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>CharacterFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
bingo,一勞永逸,繼續去寫程式碼!