java ee 中文乱码的问题

时间:2023-03-09 16:32:13
java ee  中文乱码的问题
java ee  中文乱码的问题

发生中文乱码的三种情况

(一) 表单form

Post 方法

直接在服务器中设置

request.setCharacterEncoding("utf-8");

get方法 自己转码,下面是方法.

public class HuanMa{

public static String getUTF8(String str){

        String s="";

        try {

              s= new String(str.getBytes("iso-8859-1"),"utf-8");

        } catch (UnsupportedEncodingException e) {

               // TODO Auto-generated catch block

               e.printStackTrace();

        }

        return s;

}

}

(二) 超链接

<a href=http://www.sohu.com?name=周海/>你好</a>

超链接的转码和表单中的get方法是一样的

(三) sendRedirect() 发生乱码

response.sendRedirect(“servlet地址?userName=周海”);

浏览器的utf-8 到 服务器时就变成了,"iso-8859-1" 了 , 当上面的方法运行后,服务器会返回“servlet地址?userName=周海” 但是返回的是"iso-8859-1"码. 浏览器会再次的进入 servlet地址.进入服务器.并且还是"iso-8859-1" 只要像 get方法 去转码就可以了

//这个是 response.sendRedirect()方法转码

              //response.sendRedirect("/encoding/Main?user="+request.getParameter("user"));

              response.sendRedirect("/encoding/Main?user="+new String("我是好人".getBytes("utf-8"),"iso-8859-1"));