开发者

struts, hibernate, mysql - char encoding problem

I have a web app that gathers some data from the user and saves them to a mysql database. The problem is that for a String like "Ajánlat kiküldése", what gets stored to the database is "Ajánlat kiküldése".

For my database, i have DEFAULT CHARACTER SET utf8. For my tables i have DEFAULT CHARSET=utf8.

In my hibernate.cfg.xml i have:

<property name="hibernate.connection.useUnicode">true开发者_开发问答</property>
<property name="hibernate.connection.characterEncoding">UTF-8</property>
<property name="hibernate.connection.charSet">UTF-8</property>

If I enter "Ajánlat kiküldése" directly into the database using a mysql client, the text gets stored correctly. SO somewhere along the way inside my application the text gets changed.

I have this in my jspx page:

<meta content="text/html; charset=UTF-8" http-equiv="Content-Type"/>

For my form I use sutrts html taglib and the code is very simple:

<html:form action="/submitAddProject">
            <table>
                <tr>
                    <td>name</td>
                    <td>
                        <html:text property="projectNameToAdd"/> 
                    <td>
                 etc.

On submit, when I do myForm.getProjectNameToAdd, I have a different text than the one I enter in the form. (Ajánlat kiküldése instead of Ajánlat kiküldése )


I had a similar problem, but my problem was directly with hibernate saving the data in MySQL. The problem can be easily fixed by appending useUnicode=true&characterEncoding=UTF-8 to your connection string in configuration file.

For example: jdbc.databaseurl=jdbc:mysql://localhost:3306/myHibernateDB?useUnicode=true&characterEncoding=UTF-8

Worked for me like a piece of magic.

This is the article that talks about it: http://www.isocra.com/2007/01/utf-8-with-hibernate-30-and-mysql/


You can try to create the following filter:

public class Utf8EncodingFilter implements Filter {

 public void init(FilterConfig config) throws ServletException {}

 public void doFilter(ServletRequest request, ServletResponse response, FilterChain next)
 throws IOException, ServletException {
  request.setCharacterEncoding("utf-8");
  next.doFilter(request, response);
 }

 public void destroy(){}
}

UPDATE: You need to create Utf8EncodingFilter class, import Filter interface, exception, etc. (any modern IDE will do this for you). Then you need to add this filter into your deployment descriptor (can be found at WEB-INF/web.xml) using the following syntax:

  <filter>
    <filter-name>UTF-8 Encoding Filter</filter-name>
    <filter-class>com.example.Utf8EncodingFilter</filter-class>
  </filter>

  <filter-mapping>
    <filter-name>UTF-8 Encoding Filter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

You can read more about filters here: http://www.ibm.com/developerworks/java/library/j-pj2ee10.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜