1 package six.four.five.web; 2 3 import javax.servlet.ServletException; 4 import javax.servlet.annotation.WebServlet; 5 import javax.servlet.http.HttpServlet; 6 import javax.servlet.http.HttpServletRequest; 7 import javax.servlet.http.HttpServletResponse; 8 import java.io.IOException; 9 import java.io.PrintWriter; 10 11 @WebServlet(name = "ServletDemo3") 12 public class ServletDemo3 extends HttpServlet { 13 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 14 // 设置响应内容类型 15 response.setContentType("text/html;charset=UTF-8"); 16 17 PrintWriter out = response.getWriter(); 18 String title = "使用 GET 方法读取表单数据"; 19 String name =new String(request.getParameter("name").getBytes("ISO8859-1"),"UTF-8"); 20 // 处理中文 21 String docType = "<!DOCTYPE html> "; 22 out.println(docType + 23 "<html> " + 24 "<head><title>" + title + "</title></head> " + 25 "<body bgcolor="#f0f0f0"> " + 26 "<h1 align="center">" + title + "</h1> " + 27 "<ul> " + 28 " <li><b>站点名</b>:" 29 + name + " " + 30 " <li><b>网址</b>:" 31 + request.getParameter("url") + " " + 32 "</ul> " + 33 "</body></html>"); 34 } 35 36 // 处理 POST 方法请求的方法 37 public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 38 doGet(request, response); 39 } 40 }
19行的语句解决不了乱码问题。
参照网上找到了解决的方法:找到Tomcat安装目录下的conf文件中的server.xml
1 <Connector port="8080" protocol="HTTP/1.1" 2 connectionTimeout="20000" 3 redirectPort="8443" />
添加两行代码:URIEncoding="UTF-8" useBodyEncodingForURI="true"
添加后如下
<Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" URIEncoding="UTF-8" useBodyEncodingForURI="true" redirectPort="8443" />
解决如图