在jsp中的charset=“utf-8”
(1)如果使用post请求的参数中包含中文字符,此时需要在获取参数之前就进行编码:request.setCharacterEncoding("utf-8");然后通过request.getParameter("参数名")获取的相应的值,
(2)如果使用get请求中的参数包含中文字符,
①此时我们可以在获取到参数的值之后对其进行重新编码,即将其先转换为字节数组,再将字节数组重新解码为字符串,例如:
String rawUsername = request.getParameter("username");
byte[] rawBytes = rawUsername.getBytes("iso-8895-1");
String username = new String(rawBytes, "utf-8");
②另一种方法,我们可以先获取传递url中的包含的字符串,然后进行对其进行解码
String rawQueryStr = request.getQueryString();
String queryStr = URLDecoder.decode(rawQueryStr, "utf-8");
String[] params = queryStr.split("&");
for(String param: params){
String[] values = param.split("=");
if(values[0].equals("username")){
String username = values[1];
system.out.println(username);
}
}
(3)当需要向浏览器中添加cookie时同样存在着编译码的问题,此时我只要通过(1)(2)中的方法获取的正确编码的字符串,然后在添加cookie是使用
Cookie cName = new Cookie("name", URLEncoder.encode(name, "utf-8"));
//对cookie读取时进行相应的解码即可
Cookie[] cookies = request.getCookies();
for(Cookie cookie : cookies){
out.println(cookie.getName());
out.println("--------->");
out.println(URLDecoder.decode(cookie.getValue(), "utf-8"));
}