2014年5月3日星期六

Glassfish_008:中文乱码问题的最佳解决办法

环境:Glassfish 4.0。

在Glassfish上运行Web应用时,遇到了中文乱码问题。
现象很简单:用户在文本框输入中文,提交后,再在页面上显示时发现是乱码。

解决方法1:自定义一个StringConverter,这也是大多数人的解决办法。

(1)StringConverter.java

package com.eventown.caigou.utils;

import java.io.UnsupportedEncodingException;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

/**
 * 中文乱码转换器
 *
 */
public class StringConverter implements Converter {

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String newValues) {
        String newstr = "";
        if (newValues == null) {
            newValues = "";
        }
        byte[] byte1 = null;
        try {
            byte1 = newValues.getBytes("ISO-8859-1");
            newstr = new String(byte1, "UTF-8");
            UIInput input = (UIInput) component;
            input.setSubmittedValue(newstr);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return newstr;
    }

    @Override
    public String getAsString(FacesContext fc, UIComponent uic, Object Values) {
        return (String) Values;
    }
}

(2)在faces-config.xml文件中注册该StringConverter

<converter>
            <converter-id>com.eventown.caigou.utils.StringConverter</converter-id>
            <converter-class>com.eventown.caigou.utils.StringConverter</converter-class>
        </converter>

(3)在用户可能输入中文的组件上设置StringConverter
 <h:inputText id="email" required="true" value="#{testValidationBean.email}" 
                         requiredMessage="#{res['global.required']}"
                         validatorMessage="email must like abc@abc.com">
                <f:converter converterId="com.eventown.caigou.utils.StringConverter"/>
                <f:validator validatorId="emailValidator"/>
            </h:inputText> 

解决方法2:在glassfish-web.xml中,设置default-charset="UTF-8" 
方法1虽然解决了问题,但是总感觉不够好,因为要在每一个输入组件上加converter。
几经研究,终于发现了一个更好的解决办法:在glassfish-web.xml中,设置默认的字符编码
<parameter-encoding default-charset="UTF-8" />

没有评论: