Unicode字符保存不正确

时间:2010-09-23 22:24:50

标签: mysql hibernate jsf unicode jdbc

我有一个带有unicode文本字符串的mysql数据库。我的JSF应用程序(在tomcat 6上运行)可以读取这些unicode字符串并在浏览器中正确显示它们。所有html字符集都设置为UTF-8。

当我保存我的对象时,即使没有做任何更改,Hibernate也会将其保留回数据库。如果我现在直接查看数据库,我会发现带有重音的字符已经变成了垃圾。

我的数据库连接字符串是:

        <property name="hibernate.connection.url"
                  value="jdbc:mysql://database.address.com/dbname?autoReconnect=true&#38;zeroDateTimeBehavior=convertToNull&#38;useUnicode=true&#38;characterEncoding=utf8"/>

将该字符编码更改为UTF-8而不是utf8没有任何区别。

实际上它确实是在几天前工作的,但现在却没有,而且我没有想要检查什么的想法。你有什么建议吗?我可以提供任何被认为相关的进一步信息。

5 个答案:

答案 0 :(得分:1)

它只发生在某些表上吗?也许这些表的DEFAULT CHARSET与其他表不同。 (http://dev.mysql.com/doc/refman/5.1/en/charset-table.html

答案 1 :(得分:1)

我想到了一些解决这个问题的方法:

  • 如果使用facelets,请在页面顶部指定<?xml version="1.0" encoding="UTF-8"?>
  • 如果使用JSP,请指定<%@ page pageEncoding="utf-8" %>
  • 如果这不起作用,请创建一个映射到faces servlet的过滤器,然后执行request.setCharacterEncoding("utf-8")

答案 2 :(得分:0)

我和PostgreSQL有同样的问题。您可以使用如下过滤器。它对我有用。我认为它必须是更好的解决方案,但我还没有找到:/

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class UnicodeFilter implements Filter {

    @Override
    public void destroy() {}

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
         // Set the characterencoding for the request and response streams.  
         req.setCharacterEncoding("UTF-8");  
         res.setContentType("text/html; charset=UTF-8");          
         chain.doFilter(req, res);    
    }  

    @Override
    public void init(FilterConfig arg0) throws ServletException {}

}

在web.xml中:

<filter>
        <filter-name>utffilter</filter-name>
        <filter-class>utils.UnicodeFilter</filter-class>
</filter>
<filter-mapping>
        <filter-name>utffilter</filter-name>
        <url-pattern>/*</url-pattern>
</filter-mapping>

答案 3 :(得分:0)

Spring我发现的最简单的解决方案是CharacterEncodingFilter

 <filter>
     <filter-name>encoding-filter</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>
 </filter>
 <filter-mapping>
     <filter-name>encoding-filter</filter-name>
     <url-pattern>/*</url-pattern>
 </filter-mapping>

答案 4 :(得分:0)

确保UTF-8编码页面以便显示某些字符         并正确提交......

  

将此过滤器添加到web.xml。

 On the discussion with id 7, there are 4 comments with discid 1.
 On the discussion with id 2, there are 3 comments with discid 2.