<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/AServlet" method="post">
用户名:<input type="text" name="username" value="李四"/><br/>
<input type="submit" value="提交">
</form>
<hr/>
<a href="/AServlet?username=张三">GET</a>
</body>
</html>
1 @WebServlet(name = "AServlet",urlPatterns = "/AServlet") 2 public class AServlet extends HttpServlet { 3 public void doPost(HttpServletRequest request, HttpServletResponse response) 4 throws ServletException, IOException { 5 request.setCharacterEncoding("utf-8"); 6 String username = request.getParameter("username"); 7 response.setContentType("text/html;charset=utf-8"); 8 PrintWriter out = response.getWriter(); 9 out.print(username); 10 System.out.println(username); 11 } 12 13 protected void doGet(HttpServletRequest request, HttpServletResponse response) 14 throws ServletException, IOException { 15 String name = request.getParameter("username"); 16 response.setContentType("text/html;charset=utf-8"); 17 PrintWriter out = response.getWriter(); 18 out.print(name); 19 System.out.println(name); 20 } 21 }
1、运行环境:
操作系统系统:Mac OS X10.12.6,语言:英文
开发工具:IntelliJ IDEA 2017.2.2,默认编码:UTF-8
Tomcat:9.0.0.M26
2、问题:运行Web项目时,控制台输出乱码。
3、解决方法:
设置Servlet的VM options(虚拟机选项)为:-Dfile.encoding=UTF-8
![](https://images2017.cnblogs.com/blog/1184735/201708/1184735-20170831103247312-1767697384.png)
使用:chrome Version 60.0.3112.113,结果:控制台输出正常。
使用:QQBrowser Version 4.2.4761.400 (64-bit),结果:控制台输出正常。
使用:Safari Version 10.1.2 (12603.3.8),结果:控制台输出正常。
使用:Firefox 55.0.3 (64 位),结果:控制台输出正常。
更换操作系统为中文,结果一致,排除系统语言方面原因。
注意:如果使用doPost()方法获取表单,则需在获取参数前设置: request.setCharacterEncoding("utf-8"); 否则会控制台会出现乱码。
参考:http://blog.csdn.net/rznice/article/details/41006913