Struts乱码问题

做法是做一个转换函数
该函数在转换时首先判断是否包含中文字符
如果包含则不转化
否则转化
然后在所有可能涉及到中文的setter中调用该方法
转换代码参考如下

/**
     * 判断输入的字符串是否包含GBK编码格式的字符。
     * 在此方法中,首先将字符串以ISO-8859-1编码格式提取并转化为byte[]数组;
     * 然后判断该数组中是否包含'?'(ASCII码值为63),如果有,则该字符串中包含GBK编码格式的字符。
     * 当然,为了排除原字符串中的'?'的干扰,应首先将'?'替换掉。
     * @param string String 字符串。
     * @throws UnsupportedEncodingException 如果系统不支持ISO-8859-1编码格式,将抛出此异常。
     * @return boolean 如果输入的字符串包含GBK编码格式的字符,则返回true;否则返回false。
     * @see Transform#toGBK
     * @see Transform#toISO_8859_1
     */

    public static boolean isGBK(String string)
        throws java.io.UnsupportedEncodingException
    {
        byte[] bytes = string.replace('?','a').getBytes(
"ISO-8859-1");
        for(int i=0;i<bytes.length;i++)
        {
            if(bytes[i]==63)
            {
                return true;
            }
        }

        return false;
    }

   
/**
     * 实现将字符串转换为GBK编码格式的字符串,并返回转换结果。
     * 如果原始字符串为ISO-8859-1编码格式的字符串,则返回转化为GBK编码格式的字符串;
     * 如果原始字符串本身即为GBK编码格式的字符串,则返回原字符串,即不进行编码格式的转换。
     * 判断字符串是否为GBK编码格式的标准是判断该字符串中是否包含GBK编码格式的字符。
     * @param string String 欲转换的字符串。
     * @throws UnsupportedEncodingException 如果系统不支持ISO-8859-1或GBK编码格式,将抛出此异常。
     * @return String 转换后的字符串。
     * @see Transform#isGBK
     * @see Transform#toISO_8859_1
     */

    public static String toGBK(String string)
        throws java.io.UnsupportedEncodingException
    {
        if(string==null) return
"";

        if(!isGBK(string))
        {
            return new String(string.getBytes(
"ISO-8859-1"),"GBK");
        }

        return string;
    }

   
/**
     * 实现将字符串转换为ISO-8859-1编码格式的字符串,并返回转换结果。
     * 如果原始字符串为GBK编码格式的字符串,则返回转化为ISO-8859-1编码格式的字符串;
     * 如果原始字符串本身即为ISO-8859-1编码格式的字符串,则返回原字符串,即不进行编码格式的转换。
     * 判断字符串是否为ISO-8859-1编码格式的标准是判断该字符串中是否未包含GBK编码格式的字符。
     * @param string String 欲转换的字符串。
     * @throws UnsupportedEncodingException 如果系统不支持ISO-8859-1或GBK编码格式,将抛出此异常。
     * @return String 转换后的字符串。
     * @see Transform#isGBK
     * @see Transform#toGBK
     */

    public static String toISO_8859_1(String string)
        throws java.io.UnsupportedEncodingException
    {
        if(string==null) return
"";

        if(isGBK(string))
        {
            return new String(string.getBytes(
"GBK"),"ISO-8859-1");
        }

        return string;
    }
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值