不好意思问一下啊; 我现在是用HttpRequest在两个页面之间传递数据, 两个页面的编码均为UTF-8; 中间要通过一个类Action的东西; 地址栏的URL为 ".do?action=displayAll&dept=某某部门" 这样的. 但是到了Action里面这个 "某某部门" 就成了乱码... 但这个属性的信息很重要, 不用不行. 在网上搜索了一些方法, 比如 "new String(httpRequest.getParameter("dept").getBytes("UTF-8"))" 或者 "request.setCharacterEncoding("UTF-8")" 这样的, 都不行 (我也试了填入他编码)... 请问这个大概是要怎么解决一下呢? 谢谢大家了!!!

解决方案 »

  1.   

    请参考我们教程中的相关讨论。http://family168.com/tutorial/jsp/html/jsp-ch-02.html#jsp-ch-02-02
      

  2.   

    一、
    汉字是gbk或gb2312,转为UTF8
    public static String GBKtoUTF8(String s) {
            StringBuffer sb = new StringBuffer();
            for (int i=0;i<s.length();i++) {
                char c = s.charAt(i);
                if (c >= 0 && c <= 255) {
                    sb.append(c);
                } else {
                    byte[] b;
                    try {
                        b = Character.toString(c).getBytes("UTF-8");
                    } catch (Exception ex) {
                        System.out.println(ex);
                        b = new byte[0];
                    }
                    for (int j = 0; j < b.length; j++) {
                        int k = b[j];
                        if (k < 0) k += 256;
                        sb.append("%" + Integer.toHexString(k).toUpperCase());
                    }
                }
            }
            return sb.toString();
        }
    二、
    如果是页面上汉字通过程序存数据库,为了在数据库中是汉字,从页面上得到的汉字把GBK格式字符串转换为ISO-8859-1格式,再存入,一般是在IO中看到是汉字,存到数据库中会是乱码,不大确定,你看下!
    public static String GBKtoISO(String szSource){
            if(szSource==null || szSource.trim().equals("")) return "";
            try{
                return new String(szSource.getBytes("GBK"),"8859_1");
            }catch(Exception e){
                return null;
            }
        }
    在IO输出中汉字是乱码,想看到再转GBK
    public static String ISOtoGBK(String szSource){
            if(szSource==null || szSource.trim().equals("")) return "";
            try{
                return new String(szSource.getBytes("8859_1"),"GBK");
            }catch(Exception e){
                return null;
            }
        }
    这是我在用的网上资源,多谢原创者,希望对你有帮助
      

  3.   

    还有一种encode方式,在后台在反译过来,网上有写好的反译代码可搜搜
      

  4.   

    String dept= request.getParameter("dept");
    dept=new String(dept.getBytes("ISO-8859-1"),"utf-8");
      

  5.   

    写个过滤器,在过滤器里 用 request.setChar........()去设置编码,
      

  6.   

    最简单最有效的方法 
    response.setContextType("GBK");当让 写个过滤器 
    或者 String dept= request.getParameter("dept"); 
    dept=new String(dept.getBytes("ISO-8859-1"),"utf-8");
    这样都行 
      

  7.   

    谢谢大家的回复! 刚才试了, 用 "String dept = new String(dept.getBytes("ISO-8859-1"),"GBK")" 是可以的. 其实也挺奇怪的... 现在用的是公司自己的框架, 编码的过滤器是有的, 但好像没什么用的样子... 反正我也喜欢自己纯手工做东西... 总之谢谢大家了!