/**
* 前后端数据乱码问题
* 解决办法1:
* 乱码原因:一编一解码型不一致导致。
* [main description]
* @param {[type]} String[] args [description]
* @return {[type]} [description]
*/
public static void main(String[] args) {
String name = "您好,中国!";
String striso8859,strgb2312,strgbk,strutf16,strutf8 = "";
byte[] iso8859,gb2312,gbk,utf16,utf8;
try {
/**
* String.getBytes("");
* String:当前乱码的数据字符串。
* String.getBytes(String str):将乱码的数据字符串转换为byte数组。
* String.getBytes(String str)中的参数str是当前编码类型。(这个类型是当前乱码的类型)
*/
iso8859 = name.getBytes("ISO-8859-1");
gb2312 = name.getBytes("GB2312");
gbk = name.getBytes("GBK");
utf16 = name.getBytes("UTF-16");
utf8 = name.getBytes("UTF-8");
/**
* String(Byte [] byte,String str)
* String提供将不同编码格式的byte数组转化为字符串数据的构造函数,其中:
* byte是转换后的乱码byte数组,String类型的str则是声明即将要转换成为编码格式。
*/
striso8859 = new String(iso8859,"UTF-8");
strgb2312 = new String(gb2312,"UTF-8");
strgbk = new String(gbk,"UTF-8");
strutf16 = new String(utf16,"UTF-8");
strutf8 = new String(utf8,"UTF-8");
System.out.println(striso8859);
System.out.println(strgb2312);
System.out.println(strgbk);
System.out.println(strutf16);
System.out.println(strutf8);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
/**
* 前后端数据乱码问题
* 解决办法2:
* 乱码原因:一编一解码型不一致导致。
*/
HttpServletRequest.setCharacterEncoding("utf-8");
HttpServletResponse.setCharacterEncoding("utf-8");