近日使用ajax請求springmvc后臺查詢mysql數(shù)據(jù)庫,頁面顯示中文出現(xiàn)亂碼
最初在mybatis配置如下
1
2
3
|
<select id= "queryContentById" resultType = "java.lang.String" parameterType= "String" > select text from News where id=#{o} </select> |
其中表News的text字段為blob類型
如此查出的text值在控制臺中一直顯示亂碼。
之后google查找相關(guān)resultType=blob相關(guān)內(nèi)容無果,遂將其改為resultType = "java.util.Map" ,且
1
2
|
byte [] b = ( byte []) map.get( "text" ); String s = new String(b, "utf-8" ); |
打印出s,此時中文正常顯示,但頁面顯示依舊亂碼。
因此處為ajax請求,遂檢查響應(yīng)頭信息,查出如下
1
|
Content-Typetext/html;charset=ISO- 8859 - 1 |
由于數(shù)據(jù)庫中統(tǒng)一為編碼為utf-8,故修改響應(yīng)頭信息
1
2
3
4
5
6
7
|
@RequestMapping (value = "/queryContentById" , method = RequestMethod.GET,produces = "text/plain;charset=UTF-8" ) public @ResponseBody String queryContentById( @RequestParam ( "id" ) String id) throws SQLException, UnsupportedEncodingException { Map map = (Map) ndrService.queryContentById(id); byte [] b = ( byte []) map.get( "text" ); String s = new String(b, "utf-8" ); return s; } |
我們再來看下另外一個示例的問題
1、SpringMVC的Controller得到的是亂碼:
(1)在web.xml加上字符集過濾器:
(2)在JSP等頁面上修改:charset=UTF-8"和pageEncoding="UTF-8"
2、Controller讀取到的是正確的中文,但是保存到數(shù)據(jù)庫后變成“??”
(1)修改數(shù)據(jù)庫連接jdbc_url=jdbc:mysql://localhost:3306/mybatistest?useUnicode=yes&characterEncoding=UTF8("&":在xml文件中表示"&")
(2)修改數(shù)據(jù)庫的字符集為utf-8:打開mysql根目錄下my.ini(mysql5.6為my-default.ini,要把它copy一份命名為my.ini),在下面具體位置添加(或修改):
這樣設(shè)置在我這邊就沒什么問題了。
綜述:
通常中文亂碼問題都是由于字符編碼設(shè)置不對導(dǎo)致的,我這里無論是數(shù)據(jù)庫還是java文件、jsp文件,都統(tǒng)一成UTF-8。最后問題解決了。