JSF输入的汉字编码

时间:2012-12-18 14:15:26

标签: mysql hibernate jsf character-encoding

尝试通过JSF和Hibernate输入并将中文字符串保存到MySQL时遇到问题。

实际上,在使用JSF输入字段输入我(我)之后但保存到数据库之前,我使用了“System.out.print”并检测到乱码。以下是代码的一部分: 的index.xhtml

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html">
    <h:head>
        <title>Facelet Title</title>
    </h:head>
    <h:body>
        <h:form>
            <h:panelGrid columns="2">
                <h:outputText value="Input"/>
                <h:inputText value="#{showBean.input}" />
            </h:panelGrid>
            <h:commandLink action="#{showBean.show()}" value="Show"/>

        </h:form>
    </h:body>
</html>

ShowBean.java

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
@ManagedBean
@SessionScoped
public class showBean {
    String input;
    public showBean() {
        input = null;
    }

    public String getInput() {
        return input;
    }

    public void setInput(String input) {
        System.out.println("set input " + input);
        this.input = input;
    }

    public String show(){
        System.out.println("show input " + input);
        return "";
    }
}

控制台输出是: 设置输入???è??è?????è??è????? 显示输入???è??è?????è??è?????

2 个答案:

答案 0 :(得分:0)

如果您确实使用Facelets(默认情况下使用UTF-8)并且未使用PrimeFaces ajax(which is known to messup request body encoding),则您的问题有两个原因:

  1. MySQL JDBC驱动程序字符编码未设置为UTF-8。这导致数据库中出现乱码。

  2. Eclipse控制台字符编码未设置为UTF-8。这导致System.out中出现乱码。

  3. 解决方案是:

    1. useUnicode=yescharacterEncoding=UTF-8参数添加到JDBC连接。您可以将其指定为JDBC URL中的查询字符串

      jdbc:mysql://hostname:3306/db_name?useUnicode=yes&characterEncoding=UTF-8
      

      或作为JDBC数据源中的连接属性,与指定用户名,密码等完全相同。

    2. 告诉Eclipse使用UTF-8作为控制台编码 Window&gt;偏好&gt;一般&gt;工作区&gt;文本文件编码

      enter image description here

    3. 另见:

答案 1 :(得分:0)

如果您使用glassfish,只需将以下代码添加到glassfish-web.xml

<glassfish-web-app>
   <parameter-encoding default-charset="UTF-8" />
</glassfish-web-app>
相关问题