轉載:https://blog.csdn.net/qq_37230121/article/details/83269157
前提:在我們使用SSM框架搭建項目中,經常會出現前端界面往數據庫插入中文顯示???等亂碼問題,解決思路如下
前端jsp界面保證字符編碼爲utf-8:
<%@ page language="java" contentType="text/html; charset=UTF-8"
採用斷點調試,觀察在SpringMVC中是否能正常接收並顯示中文參數,如果顯示亂碼,說明SpringMVC對接收的參數採取了自己默認的編碼方式:ISO-8859-1
然後我們需要在web.xml配置文件中配置一個過濾器,將請求參數在SpirngMVC中的編碼方式指定爲utf-8:
<filter>
<filter-name>encodingFilter</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>forceRequestEncoding</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>forceResponseEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
但是上述過濾器僅解決了post請求的亂碼問題,爲了解決get請求的亂碼問題,我們需要在tomcat的配置文件server.xml中找到對應端口的定義處添加編碼格式utf-8:
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443"
URIEncoding="UTF-8"/>
最關鍵的點在這裏:如果你是更改的tomcat安裝目錄的server.xml配置文件,那麼在用eclipse運行項目時會發現配置沒起作用,其實是因爲eclipse在運行項目時是用的eclipse中配置的tomcat,那麼問題就好解決了,打開eclipse中的tomcat配置文件,改爲上述配置即可。