对Mybatis数据库数据查询乱码处理
Java代码
public class StringTypeHandler implements TypeHandler<Object> { private static Logger logger = org.slf4j.LoggerFactory.getLogger(StringTypeHandler.class); private static String ISO88591_ENCODE = "ISO8859_1"; private static String UTF8_ENCODE = "UTF-8"; private static String GBK_ENCODE = "GBK"; public void setParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException { try { String paramStr = null; if (null != parameter) { paramStr = (String) parameter; if (GBK_ENCODE.equals(getEncode(paramStr))) { if (null != parameter) { ps.setString(i, new String(((String) parameter).getBytes(GBK_ENCODE), ISO88591_ENCODE)); } } } else { ps.setString(i, (String) parameter); } } catch (UnsupportedEncodingException e) { ps.setString(i, (String) parameter); logger.debug("StringTypeHandler encode Exception"); } } public Object getResult(ResultSet rs, String columnName) throws SQLException { try { if (null != rs.getString(columnName)) { String columnValue = rs.getString(columnName); if (ISO88591_ENCODE.equals(getEncode(columnValue))) { return new String(rs.getString(columnName).getBytes(ISO88591_ENCODE), GBK_ENCODE); } } } catch (UnsupportedEncodingException e) { logger.debug("StringTypeHandler encode Exception"); } return rs.getString(columnName); } public Object getResult(CallableStatement cs, int columnIndex) throws SQLException { return cs.getString(columnIndex); } //返回编码格式 private String getEncode(String str) { String encode = null; if (verifyEncode(str, GBK_ENCODE)) { encode = GBK_ENCODE; } else if (verifyEncode(str, ISO88591_ENCODE)) { encode = ISO88591_ENCODE; } else if (verifyEncode(str, UTF8_ENCODE)) { encode = UTF8_ENCODE; } return encode; } //判断编码格式是否相符 private boolean verifyEncode(String str, String encode) { try { if (str.equals(new String(str.getBytes(encode), encode))) { return true; } } catch (UnsupportedEncodingException e) { logger.debug("StringTypeHandler encode UnsupportedEncoding"); } return false; }
配置文件
<typeHandlers> <typeHandler javaType="String" jdbcType="VARCHAR" handler="com.betdemo.interceptor.StringTypeHandler" /> </typeHandlers>
相关推荐
Lzs 2020-10-23
聚合室 2020-11-16
零 2020-09-18
Justhavefun 2020-10-22
jacktangj 2020-10-14
ChaITSimpleLove 2020-10-06
Andrea0 2020-09-18
周游列国之仕子 2020-09-15
afanti 2020-09-16
88234852 2020-09-15
YClimb 2020-09-15
风雨断肠人 2020-09-04
卖口粥湛蓝的天空 2020-09-15
stulen 2020-09-15
pythonxuexi 2020-09-06
abfdada 2020-08-26
梦的天空 2020-08-25