D:\Tomcat\apache-tomcat-9.0.0.M15\conf\server.xml
<Connector port="8080" protocol="HTTP/1.1" URIEncoding="UTF-8"
connectionTimeout="20000"
redirectPort="8443" />
特别引起我注意的是 URIEncoding="UTF-8" ,如果不设置,url上传递的中文就不能被正确解码。
提醒各位使用utf-8编码的朋友注意使用tomcat的这个设置。
也可以如下设置:
useBodyEncodingForURI,就在获取请求参数前使用setCharacterEncoding来解决乱码。
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443"
useBodyEncodingForURI="true"
/>
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置响应内容格式
response.setContentType("text/html;charset=utf-8");
//取得输出对象
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>get</title>");
out.println("</head>");
out.println("<body>");
//取得请求参数
request.setCharacterEncoding("UTF-8");
String name = request.getParameter("name");
//name = new String(name.getBytes("ISO-8859-1"), "UTF-8");
out.println("</body>");
out.println("<h1>您的姓名是:" + name + "</h1>");
out.println("</html>");
out.close();
}
对于post方式
request.setCharacterEncoding("UTF-8");