【收集整理】request获取参数为中文乱码解法方法

来源:互联网 发布:企业邮箱域名要备案吗 编辑:程序博客网 时间:2024/05/20 14:42

1. 转换字符编码方式

    例如: 获取中文信息的用户名文本框(UserName)的值,利用如下代码:

    将

        <%=request.getParameter("UserName")%>

    改为

        <%=new String(request.getParameter("UserName").getBytes("iso-8859-1"), "gb18030") %>

    得到UserName文本框的中文值。

    缺点:每次传值都要进行转换,适用于简单一句传值的页面中.

2. 利用SetCharacterEncoding方法

    在所有需要获取参数的命令之前加上:

        <%request.setCharacterEncoding("GB18030"); %>

    注意:1和2两种方式不能同时使用。

    缺点:每个需要传中文值的页面都需要添加此句。

 3. 利用JavaBean
    在JavaBean中写个字符编码转换类及方法,然后通过此类的方法对需要转换的字符进行转换。

    (1) 设置方法如下(在JavaBean中):
        public class CharactorEncoding {
          public String toString(String str) {
            String text="";
            if(str != null && !str.equals("")) {
              try {
                text = new String(str.getBytes("iso8859-1"), "GB18030");
              }
              catch (Exception e) {
                e.printStackTrace();
              }
            }
            return text;
          }
        }

     (2) 传递文件如下(在jsp页面中):
        <form action="student.jsp" method="post">
          姓名:<input type="text" name="name"/>
          <br/>
          <input type="submit" value="提交"/>&nbsp;&nbsp;<input type="reset" value="取消"/>
        </form>

    如果在姓名中添加中文,则需要代码转换。

    (3) 调用方法如下(在jsp页面中):
        <jsp:useBean id="student" class="zck.Bean" />
        <jsp:setProperty property="*" name="student"/><!--直接传递过来的参数不能识别中文 -->
        <jsp:useBean id="encoding" class="zck.CharactorEncoding"/>
        <%=encoding.toString(student.getName()) %>
而调用
        <%=student.getName() %>时,英文可以正常传递过来,而中文则出现乱码。

4. 未完待续....

原创粉丝点击