response中文输出
1.字节输出流:ServletOutputStream————getOutputStream()
public class Demo6Servlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.getOutputStream().write("中国".getBytes());//查看String类的getBytes方法可以看到使用的是当前系统默认的编码进行解码即当前是gbk
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
这样一定会乱码吗?
不一定。字节流输出中文还和浏览器的解析有关。如果浏览器的解析编码和字节流的getBytes()时的编码相同就不会乱码
正确姿势如下:
1.设置浏览器打开文件时的编码
2.设置获取字符串byte数组时的编码和浏览器解析编码相同
public class RequestDemo4 extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置浏览器打开文件时的编码
response.setHeader("Content-Type", "text/html;charset=UTF-8");
//获得输出流
OutputStream os = response.getOutputStream();
//输出
os.write("是否乱码".getBytes("UTF-8"));
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
2.字符输出流
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().write("是否乱码");
}
这个会乱码吗?
肯定乱码。
正确姿势如下:
1.设置浏览器打开文件解析时的编码
response.setHeader("Content-Type", "text/html;charset=UTF-8");
2.设置response缓冲区的编码
response.setCharacterEncoding("UTF-8");
上面两句的简写形式:response.setContentType("text/html;charset=UTF-8");
/**
* 处理字符输出乱码
* 肯定乱码
* 因为response缓冲区的编码,默认是ISO-8859-1
* 1.设置response缓冲编码就好了
* response.setCharacterEncoding("UTF-8")
* 2.设置浏览器打开文件时的编码
* response.setHeader();
*
* 1和2两步可以合并为一句简写形式response.setContentType("text/html;charset=UTF-8");
* @param response
* @throws IOException
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/* //设置reponse缓冲区的编码
response.setCharacterEncoding("UTF-8");
//设置浏览器打开文件所采用编码
response.setHeader("Content-Type", "text/html;charset=UTF-8");*/
//上面两句的简写形式
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write("是否乱码");
}
request获取中文数据
POST提交:
设置request缓冲区的编码
request.setCharacterEncoding("utf-8");
GET提交:
String构造方法
username = new String(username.getBytes("ISO-8859-1"),"utf-8");
(这里是指拿到这个可能乱码的username以后重构它的String编码为UTF-8)