乱码解决方案:
代码详解:
package com.bjpowernode.javaweb.servlet; import java.io.IOException; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class SaveDeptServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//Tomcat配置文件中的URIEncoding修改后,doGet方法就已经解决了编码问题
String dname = request.getParameter("dname");
System.out.println(dname);
} @Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { /*
String dname = request.getParameter("dname"); //第一种解决方式:万能解决方案,post和get都可以使用
byte[] bytes = dname.getBytes("ISO-8859-1"); //解码
dname = new String(bytes, "UTF-8"); //编码方式需要同浏览器的的编码方式一致
System.out.println(dname);
*/ //第二种解决方案:调用request的setCharacterEncoding方法,但是这种方式只适合POST请求,只对请求体编码
//告诉Tomcat服务器,请求体中的数据采用UTF-8的方式进行编码
request.setCharacterEncoding("UTF-8");
String dname = request.getParameter("dname");
System.out.println(dname);
}
}