Servlet Java Web开发(3) request response

编码

 这里例子依然是在一个HttpServlet类的doGet方法中,

一般如果直接发送数据

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

response.getWriter.printf("中文编码");

}

浏览器访问会得到乱码。

解决方案:response.setCharacterEncoding("utf-8");只是把字符转为utf-8格式,浏览器依然会按照gbk解析。

在发送之前使用

response.setHeader("Content-Type", "text/html;charset=utf-8");
//或者
response.setContentType("text/html;charset=utf-8");
//这两者一样

他们的效果不仅起到response.setCharacterEncoding("utf-8");的作用,还会在http 响应头中增加Content-Type: text/html;charset=utf-8,这样浏览器就会正确解析。

猜你喜欢

转载自www.cnblogs.com/legion/p/9056015.html