设置相同字符集UFT-8 TomCat8.0默认设置
1.POST中文乱码
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 中文乱码的解决方案
*/
@WebServlet("/req4")
public class RequestDemo4 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.解决乱码:POST,getReader()
request.setCharacterEncoding("UTF-8");//设置字符输入流的编码
//2.获取username
String username = request.getParameter("username");
System.out.println(username);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}
HTML设置
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/tomcat_demo1_war/req4" method="get">
<input type="text" name="username"><br>
<input type="password" name="password"><br>
<input type="checkbox" name="hobby" value="1">游泳
<input type="checkbox" name="hobby" value="1">爬山<br>
<input type="submit">
</form>
</body>
</html>
2.GET中文乱码
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 中文乱码的解决方案
*/
@WebServlet("/req4")
public class RequestDemo4 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//2.获取username
String username = request.getParameter("username");
System.out.println("解决乱码前:" + username);
//3.GET,获取参数的方式:getQueryString
// 乱码原因:tomcat进行URL解码,默认的字符集是ISO-8859-1 8.0之后默认是UTF-8
//3.1 先对乱码数据进行编码:转换字节数组
// byte[] bytes = username.getBytes("ISO-8859-1");
// //3.2字节数组解码
// username = new String(bytes,"UTF-8");
username = new String(username.getBytes("ISO-8859-1"),"utf-8");
System.out.println("解决乱码后" + username);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}
更容易理解:
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
public class URLDemo {
public static void main(String[] args) throws UnsupportedEncodingException {
String username = "张三";
//1.URL编码
String encode = URLEncoder.encode(username, "utf-8");
System.out.println(encode);
//2.URL解码
String decode = URLDecoder.decode(encode, "ISO-8859-1");
System.out.println(decode);
//3.转换为字节数据,编码
byte[] bytes = decode.getBytes("ISO-8859-1");
// for (byte b : bytes){
// System.out.print(b + " ");
// }
//4.将字节数组转换为字符串,解码
String s = new String(bytes, "utf-8");
System.out.println(s);
}
}
输出结果:
总结: