alibaba/druid
https://github.com/alibaba/druid
- 中文 https://github.com/alibaba/druid/wiki/%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98
- English https://github.com/alibaba/druid/wiki/FAQ
编码过滤器
首先这是druid 提供的功能
<bean id="xxx" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> ... <property name="filters" value="stat,encoding"></property> <property name="connectionProperties" value="serverEncoding=ISO-8859-1;clientEncoding=GBK"></property> ... </bean>
对于文本的解析,可以具体查看 DruidDataSource 对应的setter 方法
1 开启 过滤器
需要配置filters 以逗号分隔,别名及具体的类配置在jar包下 META-INF/druid-filter.properties 中
常用的2个是
druid.filters.stat=com.alibaba.druid.filter.stat.StatFilter druid.filters.encoding=com.alibaba.druid.filter.encoding.EncodingConvertFilter
2 配置服务端和客户端编码
格式为:
k1=v1;k2=v2
解析代码:
public void setConnectionProperties(String connectionProperties) { if (connectionProperties == null || connectionProperties.trim().length() == 0) { setConnectProperties(null); return; } String[] entries = connectionProperties.split(";"); Properties properties = new Properties(); for (int i = 0; i < entries.length; i++) { String entry = entries[i]; if (entry.length() > 0) { int index = entry.indexOf('='); if (index > 0) { String name = entry.substring(0, index); String value = entry.substring(index + 1); properties.setProperty(name, value); } else { // no value is empty string which is how java.util.Properties works properties.setProperty(entry, ""); } } } setConnectProperties(properties); }
public class CharsetParameter { public static final String CLIENTENCODINGKEY = "clientEncoding"; public static final String SERVERENCODINGKEY = "serverEncoding"; ... }
ali.charset.converter 只有在服务端和客户端编码不一致时才会生效
3 encode 和 decode
查询时 encode ,返回string 时 decode
/** * 字符串编码 * * @param s String * @return String * @throws UnsupportedEncodingException */ public String encode(String s) throws UnsupportedEncodingException { if (enable && !isEmpty(s)) { s = new String(s.getBytes(clientEncoding), serverEncoding); } return s; } /** * 字符串解码 * * @param s String * @return String * @throws UnsupportedEncodingException */ public String decode(String s) throws UnsupportedEncodingException { if (enable && !isEmpty(s)) { s = new String(s.getBytes(serverEncoding), clientEncoding); } return s; }
实战说明
天津数据是Oralce ,字符集是 ZHS16GBK
测试环境字符集是
NLS_CHARACTERSET = WE8MSWIN1252
通过配置 serverEncoding=ISO-8859-1;clientEncoding=GBK 乱码问题解决了