从Glassfish编码问题上的url连接读取java XML?

时间:2014-07-21 15:32:14

标签: utf-8 character-encoding glassfish-3

我尝试使用URLConnection和DocumentBuilder对象从xml url读取数据并在MySQL DB上保留。使用我的Hibernate Web应用程序。 xml元素数据包含土耳其语字符。实际上我在我的本地环境(Windows7)上实现了这个问题。所以它在我当地的MYSQL数据库上成功地存在。但是,如果我尝试在我的AWS环境中运行似乎是土耳其字符(ı,İ,ş,ç,ğ,ü,ö)的问题。 MYSQL排序规则是utf8_unicode_ci。 url上的源xml也包含utf-8编码。另外,我无法通过System.out的试验找到解决方案。可能是什么问题?谢谢 Glassfish 3.1.2 javaee5

更新:我已经通过Charset.defaultCharset()检查了jre charset。它是UTF-8

        URL url = new URL("http://domain/address");
        URLConnection urlConnection = null;
        urlConnection = url.openConnection();
        urlConnection.setRequestProperty("Accept-Charset", "UTF-8");
        urlConnection.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
        InputStream inputStream = urlConnection.getInputStream();

        db = dbf.newDocumentBuilder();
        InputSource source = new InputSource(new InputStreamReader(inputStream, "UTF-8"));
        source.setEncoding("UTF-8");
        dom = db.parse(source);
        NodeList nodeList = dom.getElementsByTagName("Product");

        Product product = null;
        for (int temp = 0; temp < nodeList.getLength(); temp++)
        {
            Node nNode = nodeList.item(temp);
            if (nNode.getNodeType() == Node.ELEMENT_NODE)
            {
                Element productNode = (Element)nNode;
                product = new Product();
                String name=productNode.getElementsByTagName("Name").item(0).getTextContent();
                System.out.println("before encoding: " + name);
                System.out.println("encoding_utf-8: " + new String (name.getBytes ("UTF-8"), "UTF-8"));
                System.out.println("encoding_iso-8859-9: " + new String (name.getBytes ("UTF-8"), "ISO-8859-9"));
                product.setBarcode(productNode.getElementsByTagName("Name").item(0).getTextContent());
...

1 个答案:

答案 0 :(得分:1)

花了好几个小时之后,终于解决了。这与jdbc连接资源有关。我在我的domain.xml文件中添加了3行粗体,如下所示。希望对某人有所帮助

    <jdbc-resource pool-name="MYQSL_accmeepool" description="" jndi-name="jdbc/accmee"></jdbc-resource>
    <jdbc-connection-pool driver-classname="" datasource-classname="com.mysql.jdbc.jdbc2.optional.MysqlXADataSource" res-type="javax.sql.XADataSource"
                          description="" name="MYQSL_accmeepool">
        <property name="user" value="root"></property>
        <property name="password" value="admin"></property>
        <property name="serverName" value="localhost"></property>
        <property name="databaseName" value="accmee"></property>
        <property name="portNumber" value="3306"></property>
        **<property name="useUnicode" value="true"/>
        <property name="characterEncoding" value="utf8"/>
        <property name="characterSetResults" value="utf8"/>**
    </jdbc-connection-pool>