只是快速浏览了一下,知道个概念,不想操作了。还是上班好玩一下,放假好无聊。
一、resonse
1、输出中文问题:ResponseDemo1.java
- 两边默认的都是gb2312,所以可以输出“中国”。
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String data = "中国"; OutputStream out = response.getOutputStream(); out.write(data.getBytes()); }
- 改成,“UTF-8”,输出就变成“涓浗”了。因为一个用的是gb2312,一个用的是UTF-8。
解决:把浏览器的 --> 编码 改为 “UTF-8”,就能正常显示“中国”了。String data = "中国"; OutputStream out = response.getOutputStream(); out.write(data.getBytes("UTF-8"));
- 不可能每次都去浏览器改码表吧,所以专业的做法是:向浏览器发送数据的时候,告诉它我是utf-8
在服务器端,数据是以哪个码表输出的,就要控制浏览器已哪个码表打开。protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String data = "中国"; response.setHeader("content-type", "text/html;charset=UTF-8"); OutputStream out = response.getOutputStream(); out.write(data.getBytes("UTF-8")); }
- 使用html语言里面的<meta>标签来控制浏览器行为(模拟http响应头)
问题:在ie里面只显示“中国”,可为什么在谷歌里面却显示“String data = "中国"; OutputStream out = response.getOutputStream(); out.write("<meta http-equiv='Content-type' content='text/html;charset=UTF-8'>".getBytes()); out.write(data.getBytes("UTF-8"));
<meta http-equiv='Content-type' content='text/html;charset=UTF-8'>涓浗
”呢?
- 同时发两个头:
private void test3(HttpServletResponse response) throws IOException, UnsupportedEncodingException { String data = "中国"; OutputStream out = response.getOutputStream(); out.write("<meta http-equiv='Content-type' content='text/html;charset=gb2312'>" .getBytes()); response.setHeader("Content-type", "text/html;charset=UTF-8"); out.write(data.getBytes("UTF-8")); }
- 用字符流输出数据:
小细节:private void test4(HttpServletResponse response) throws IOException, UnsupportedEncodingException { String data = "中国"; //通知浏览器以utf-8打开 response.setHeader("Content-type", "text/html;charset=UTF-8"); //通知response以utf-8输出 response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); //iso8859-1 ?? out.write(data); }
//response.setHeader("Content-type", "text/html;charset=UTF-8"); response.setContentType("text/html;charset=UTF-8");
private void test5(HttpServletResponse response) throws IOException, UnsupportedEncodingException { response.getOutputStream().write(1); //在浏览器看不到1 response.getOutputStream().write((1 + "").getBytes()); //这样就看到1了 }
2、文件下载
3、response生成随机图片
4、请求重定向
- 应用:登录
- 特点:浏览器向服务器发送了两次请求;浏览器地址栏会发生改变。
- 能不用尽量不用。