我在使用Hibernate从表单保存数据时遇到问题,基本上编码出错了,所以奇怪的字符被保存在数据库中,并在表单输入中填充。这是我到目前为止准备的配置:
web.xml中的
<filter>
<filter-name>SetCharacterEncodingFilter</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>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>SetCharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
在applicationContext.xml中(尝试了两种模式'UTF-8'和'utf8')
<property name="url" value="jdbc:postgresql://localhost:5432/mydb?characterEncoding=UTF-8" />
...
<property name="hibernateProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQL9Dialect</prop>
<prop key="hibernate.connection.CharSet">utf8</prop>
<prop key="hibernate.connection.characterEncoding">utf8</prop>
<prop key="hibernate.cache.use_query_cache">true</prop>
<prop key="hibernate.cache.use_second_level_cache">true</prop>
<prop key="hibernate.cache.region.factory_class">
org.hibernate.cache.ehcache.EhCacheRegionFactory
</prop>
<prop key="hibernate.connection.useUnicode">true</prop>
<prop key="hibernate.temp.use_jdbc_metadata_defaults">false</prop>
<prop key="show_sql">true</prop>
<prop key="hibernate.c3p0.min_size">5</prop>
<prop key="hibernate.c3p0.max_size">20</prop>
<prop key="hibernate.c3p0.timeout">300</prop>
<prop key="hibernate.c3p0.max_statements">50</prop>
<prop key="hibernate.c3p0.idle_test_period">3000</prop>
</props>
</property>
的pom.xml
<properties>
<spring.version>4.1.2.RELEASE</spring.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
数据库,jsp文件和项目也有ut8编码,我也将URIEncoding =“UTF-8”添加到server.xml中的连接器配置中。我还需要添加什么或者我做错了什么?
答案 0 :(得分:0)
您可以设置断点并检查从字节(UTF-8)到Unicode的编码是否正确完成。 接下来要做的是检查数据库/表的排序规则。 创建数据库/表时,您指定了排序规则,相当于字符集(通常在安装期间选择默认值),如果这不支持您存储的字符,则可能会出现垃圾。
答案 1 :(得分:0)
解决方案是:
@Order(1)
public class SpringSecurityInitializer extends AbstractSecurityWebApplicationInitializer {
@Override
protected void beforeSpringSecurityFilterChain(ServletContext servletContext) {
FilterRegistration.Dynamic characterEncodingFilter = servletContext.addFilter("encodingFilter", new CharacterEncodingFilter());
characterEncodingFilter.setInitParameter("encoding", "UTF-8");
characterEncodingFilter.setInitParameter("forceEncoding", "true");
characterEncodingFilter.addMappingForUrlPatterns(null, false, "/*");
}
}
基于来自的评论 CharacterEncodingFilter don't work together with Spring Security 3.2.0