乱码解决方案:
代码详解:
1 package com.bjpowernode.javaweb.servlet; 2 3 import java.io.IOException; 4 5 import javax.servlet.ServletException; 6 import javax.servlet.http.HttpServlet; 7 import javax.servlet.http.HttpServletRequest; 8 import javax.servlet.http.HttpServletResponse; 9 10 public class SaveDeptServlet extends HttpServlet { 11 12 private static final long serialVersionUID = 1L; 13 14 15 16 @Override 17 protected void doGet(HttpServletRequest request, HttpServletResponse response) 18 throws ServletException, IOException { 19 //Tomcat配置文件中的URIEncoding修改后,doGet方法就已经解决了编码问题 20 String dname = request.getParameter("dname"); 21 System.out.println(dname); 22 } 23 24 @Override 25 protected void doPost(HttpServletRequest request, HttpServletResponse response) 26 throws ServletException, IOException { 27 28 /* 29 String dname = request.getParameter("dname"); 30 31 //第一种解决方式:万能解决方案,post和get都可以使用 32 byte[] bytes = dname.getBytes("ISO-8859-1"); //解码 33 dname = new String(bytes, "UTF-8"); //编码方式需要同浏览器的的编码方式一致 34 System.out.println(dname); 35 */ 36 37 //第二种解决方案:调用request的setCharacterEncoding方法,但是这种方式只适合POST请求,只对请求体编码 38 //告诉Tomcat服务器,请求体中的数据采用UTF-8的方式进行编码 39 request.setCharacterEncoding("UTF-8"); 40 String dname = request.getParameter("dname"); 41 System.out.println(dname); 42 } 43 }