Servlet中文乱码问题
1.request请求乱码
(1)如果是POST提交, 不管是哪个版本的tomcat服务器, 通过POST提交的中文数据, 在接收时都会出现乱码问题。
解决方式:只需要在任何获取参数的代码之前设置一行代码即可:
request.setCharacterEncoding(“utf-8”);//只对POST有效
(2)如果是GET提交, 并且是tomcat8.0及以后的版本中, 通过GET提交的中文数据, 在接收时默认是没有乱码的(tomcat8.0设置了GET提交时的编码, 所以没有乱码)
(3)如果是GET提交, 并且是tomcat7.0及以前的版本中, 通过GET提交的中文数据, 在接收时也是有中文乱码问题的。解决方案是:
在Connector标签里面加一个属性,并设置值为URIEncoding=“UTF-8”
2.response响应乱码
(1)通知服务器使用utf-8发数据给浏览器
(2)还要通知浏览器使用utf-8接收服务器发送过来的数据
response.setContentType(“text/html;charset=utf-8”);//解决返回页面请求乱码
response.setContentType(“application/json;charset=UTF-8”);//解决返回json数据中文乱码
3.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 TestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//>>处理POST请求参数乱码
request.setCharacterEncoding("utf-8");
//>>处理响应正文乱码
response.setContentType("text/html;charset=utf-8");
//TODO...
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}