環境介紹
kindeditor + springMVC + mybatis + mysql
問題介紹
在我本地使用正常,在服務器上卻出現亂碼。 本地數據庫類型使用varcher存儲內容,服務器使用類型blob(二進制)存儲。
前臺頁面編輯時文字正常顯示,存入數據之前未亂碼,存入數據後出現亂碼,獲取數據解碼也亂碼。反查取回查看會亂碼。亂碼如圖:
原因分析
當字符串轉變爲二進制存入blog中,獲取的時候卻認爲是String,所以顯示亂碼。String存到varchar直接存就行,都是字符串。但 String 存入blog(二進制)需要特殊處理。
錯誤嘗試
取出數據庫中二進制,通過utf-8 編碼爲文字展示。自己實驗失敗。
解決方案
- 自定義typehandler,解決mybatis存儲blob字段 實用相同的utf-8編碼和解碼,防止出現亂碼的問題
- mapper.xml 配置blog字段使用 <result property=“content” column=“CONTENT” typeHandler=“cn.ffcs.drive.common.util.ConvertBlobTypeHandler”/>
package cn.ffcs.drive.common.util;
import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
/**
* className:ConvertBlobTypeHandler
*
* 自定義typehandler,解決mybatis存儲blob字段後,出現亂碼的問題
* 配置mapper.xml: <result typeHandler="cn.ffcs.drive.common.util.ConvertBlobTypeHandler"/>
*
*/
public class ConvertBlobTypeHandler extends BaseTypeHandler<String> {
//###指定字符集
private static final String DEFAULT_CHARSET = "utf-8";
@Override
public void setNonNullParameter(PreparedStatement ps, int i,
String parameter, JdbcType jdbcType) throws SQLException {
ByteArrayInputStream bis;
try {
//###把String轉化成byte流
bis = new ByteArrayInputStream(parameter.getBytes(DEFAULT_CHARSET));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Blob Encoding Error!");
}
ps.setBinaryStream(i, bis, parameter.length());
}
@Override
public String getNullableResult(ResultSet rs, String columnName)
throws SQLException {
Blob blob = rs.getBlob(columnName);
byte[] returnValue = null;
if (null != blob) {
returnValue = blob.getBytes(1, (int) blob.length());
}
try {
//###把byte轉化成string
return new String(returnValue, DEFAULT_CHARSET);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Blob Encoding Error!");
}
}
@Override
public String getNullableResult(CallableStatement cs, int columnIndex)
throws SQLException {
Blob blob = cs.getBlob(columnIndex);
byte[] returnValue = null;
if (null != blob) {
returnValue = blob.getBytes(1, (int) blob.length());
}
try {
return new String(returnValue, DEFAULT_CHARSET);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Blob Encoding Error!");
}
}
@Override
public String getNullableResult(ResultSet arg0, int arg1)
throws SQLException {
// TODO Auto-generated method stub
return null;
}
}
參考文檔:http://blog.csdn.net/p793049488/article/details/37818989