代码改变世界

JAVAWEB开发之HttpServletResponse和HttpServletRequest详解(上)(各种乱码、验证码、重定向和转发)

2017-06-18 22:25  GarfieldEr007  阅读(666)  评论(0编辑  收藏  举报

 HttpServletResponse简介

  • Web服务器收到客户端的http请求,会针对每一次请求,分别创建一个用于代表请求的request对象、和代表响应的response对象
  • request和response对象即然代表请求和响应,那我们要获取客户机提交过来的数据,只需要找request对象就行了。要向客户机输出数据,只需要找response对象就行了
  • HttpServletResponse对象服务器的响应。这个对象中封装了向客户端发送数据、发送响应头,发送响应状态码的方法。
 响应:
* 响应行
* 状态码:
void setStatus(int sc) 设置状态码 常用的状态码:200、302、304、404、500

* 响应头(key:value的形式,一个key对应一个value,一个key对应多个value)
* 设置头信息
void setHeader(String name, String value)  (一个key对应一个value)经常使用的
setHeader("aa","bb");
setHeader("aa","cc");
结果:aa:cc

void setIntHeader(String name, int value)  
void setDateHeader(String name, long date) 值是毫秒值(int 秒long 毫秒)

void addHeader(String name, String value)  (一个key对应多个value)
addHeader("aa","bb");
addHeader("aa","cc");
结果:aa:bb,cc

void addIntHeader(String name, int value)  
void addDateHeader(String name, long date)  

* 响应体
ServletOutputStream getOutputStream()  字节输出流
PrintWriter getWriter()  字符输出流

HttpServletResponse继承自ServletResponse
 
 
 

HttpServletResponse使用案例(一)——重定向(登录页面)

登录页面重定向
状态码302    响应头location
需求:登录页面,用户名和密码的登录页面,用户名和密码都是admin,如果有一个不是,重定向到登录页面,重新登录。
方法一:
    // 设置302的状态码
    response.setStatus(302);
    //  设置地址
    response.setHeader("location","/day10/response/login.html");
方法二:使用自带的方法sendRedirect() 方法,(实质是封装了设置状态码302和头信息location的代码)
    response.sendRedirect("/day10/response/login.html");

HttpServletResponse使用案例(二)——页面定时刷新(页面读秒操作)

响应的头refresh
<meta http-equiv="refresh" content="5;url=/day10/response/login.html"> (客户端meta中设置头信息refresh)
response.setHeader("refresh", "5;url=/day6/hello.html"); (或者在服务器端为客户端设置实现)

HttpServletResponse使用案例(三)——禁用浏览器缓存(三个头信息)

禁用缓存就是禁止浏览器缓存当前文档内容,包含如下三个头信息:
Cache-Control:no-cache
Expires:-1   值是日期类型(setDateHeader)
Pragma:no-cache  
实例方法如下:
// 设置response 的三个头信息
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache");
// Expires 要求格式 日期格式
// 通过setDateHeader设置一个毫秒信息,自动转换日期格式
response.setDateHeader("Expires", -1);

HttpServletResponse使用案例(四)——向页面输出中文(字节流和字符流)

(1)字节流输出中文 ServletOutputStream getOutputStream()
  • 乱码和浏览器的编码有关
  • 设置浏览器默认打开时候的编码集
  • 获取字符串byte数组时,传入一个编码集
    字节输出中文是否一定乱码呢?
     不一定乱码,但有时候会乱码,跟浏览器的编码有关
    解决方法:
       设置浏览器打开文件时所采用的的编码
           response.setHeader("Content-Type", "text/html;charset=UTF-8");
       获取字符串byte数组编码和打开文件时编码一致
           "哈喽我的".getBytes("UTF-8")
 
(2)字符流输出中文 PrintWriter getWriter()  
  字符输出中文一定乱码,因为response的字符流缓冲区的编码,默认值是ISO-8859-1,是不支持中文的。
  解决方法:
  •   设置response缓冲区编码: response.setCharacterEncoding("UTF-8");
  •   设置浏览器打开文件时所采用的的编码:response.setHeader("Content-Type","text/html;charset=UTF-8");  
  •   简写方式:response.setContentType("text/html;charset=UTF-8");(等效于以上两句代码)
(3)response生成响应的注意事项
  • getOutputStream和getWriter方法分别用于得到输出二进制数据、输出文本数据的ServletOutputStream、PrintWriter对象。
  • getOutputStream和getWriter这两个方法相互排斥,调用了其中任何一个方法后,就不能再调用另一方法。
  • Servlet程序向ServletOutputStream或PrintWriter对象中写入的数据将被Servlet引擎从response中获取,Servlet引擎将这些数据当做响应消息的正文,然后再与响应状态行和各响应头组合后输出到客户端。
  • Servlet的service方法结束后,Servlet引擎将检查getWriter或getOutputStream方法返回的输出流对象是否已经调用过close方法,如果没有,Servlet引擎Tomcat将调用close方法关闭该输出流对象。调用close的时候,应该会调用flushBuffer

HttpServletResponse使用案例(五)——文件下载(字节流和字符流)

(1)超链接下载
     如果浏览器不能识别的格式,会弹出下载窗口。但是如果浏览器识别的话,会默认打开文件。
(2)后台程序下载(弹出下载窗口)
  • 设置头信息response.setHeader("Content-Disposition","attatchment;filename="+文件名称);
  • 通过response.getOutputStream()向浏览器输出
文件下载
[java] view plain copy
 
  1. <span style="font-size:18px;">文件下载  
  2. // Test1:  
  3. String realpath = this.getServletContext().getRealPath(  
  4. "/download/11.jpg");  
  5. String filename = realpath.substring(realpath.lastIndexOf("\\") + 1);  
  6.   
  7. response.setHeader("content-disposition", "attachment;filename="+filename);  
  8.   
  9. FileInputStream fis = new FileInputStream(realpath);  
  10. int len = 0;  
  11. byte[] buf = new byte[1024];  
  12. OutputStream os = response.getOutputStream();  
  13. while((len=fis.read(buf))!=-1){  
  14. os.write(buf, 0, len);  
  15. }  
  16. fis.close();  
  17.   
  18. Test2:文件名中文  
  19. String realpath = this.getServletContext().getRealPath(  
  20. "/download/11.jpg");  
  21. String filename = realpath.substring(realpath.lastIndexOf("\\") + 1);  
  22.   
  23. response.setHeader("content-disposition", "attachment;filename="+URLEncoder.encode(filename, "utf-8"));  
  24.   
  25. FileInputStream fis = new FileInputStream(realpath);  
  26. int len = 0;  
  27. byte[] buf = new byte[1024];  
  28. OutputStream os = response.getOutputStream();  
  29. while((len=fis.read(buf))!=-1){  
  30. os.write(buf, 0, len);  
  31. }  
  32. fis.close();  
  33.   
  34. Test3:字符流下载  
  35. String realpath = this.getServletContext().getRealPath(  
  36. "/download/11.jpg");  
  37. String filename = realpath.substring(realpath.lastIndexOf("\\") + 1);  
  38.   
  39. response.setHeader("content-disposition", "attachment;filename="+URLEncoder.encode(filename, "utf-8"));  
  40.   
  41. FileReader fis = new FileReader(realpath);  
  42. int len = 0;  
  43. char[] buf = new char[1024];  
  44. PrintWriter os = response.getWriter();  
  45. while((len=fis.read(buf))!=-1){  
  46. os.write(buf, 0, len);  
  47. }  
  48. fis.close();  
  49. </span>  
 
注意:下载文件时中文名乱码的问题:
[java] view plain copy
 
  1. <span style="font-size:18px;">// 解决各浏览器的中文乱码问题  
  2.         String agent = request.getHeader("User-Agent");  
  3.         // 处理safari的乱码问题  
  4.         byte[] bytes = agent.contains("MSIE") ? filename.getBytes() : filename  
  5.                 .getBytes("UTF-8");  
  6.         filename = new String(bytes, "ISO-8859-1");// 各浏览器基本都支持ISO编码  
  7. </span>  

HttpServletResponse使用案例(六)——图片验证码

(1)输出图片验证码的大致步骤
在内存中生成图片
   可以使用BufferedImage对象
   该对象可以获取画笔对象  getGraphics()
随机生成字母或数字
   可以使用Random对象
把生成的数字或字母写在图片上 (通过画笔中的方法)
把图片生成到页面上   (可以使用ImageIO对象)
(2)输出图片验证码的具体细节:
  1) 建立BufferedImage对象:指定图片的长度宽度和类型
     BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
  2) 取得Graphics画笔对象,用来绘制图片
     Graphics  graphics = image.getGraphics();
  3) 绘制背景颜色
    graphics.setColor(Color.WHITE);
    graphics.fillRect(0,0,width,hight);
  4) 绘制边界
    graphics.setColor(Color.BLUE);
    graphics.drawRect(0,0,width,height);
  5) 生成随机数
    Random random = new Random();
    random.nextInt(n); // 生成0到n(不包括n)之间的随机数 前闭后开
  6) 绘制干扰线
    graphics.drawLine(x1,y1,x2,y2);
  7)设置字体 
    graphics.setFont(new Font("Times New Roman", Font.PLAIN, 18));
    如果验证码是中文,要使用中文的字体库
    通过词库生成随机验证码内容
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
    汉字:\u4e00 —— \u9fa5
    graphics.drawString(str, x, y);
 8)设置旋转
     Graphics2D graphics = (Graphics2D) image.getGraphics();
      graphics.rotate(theta, x, y);
 9) 释放此图形的上下文以及它使用的所有系统资源
       graphics.dispose();
 10) 通过ImageIO对象的write静态方法将图片输出 
     ImageIO.write(image, "jpg", resp.getOutputStream());
(3)使用旋转的技巧
通过Graphics2D对象的  void rotate(double theta, double x, double y) 画旋转。
Theta代表弧度。
弧度的公式:弧度=角度 * PI / 180
// 加入字体旋转 角度-30 --- 30之间
   int jiaodu = random.nextInt(60) - 30;
// 转换角度为弧度
   double theta = jiaodu * Math.PI / 180;
// 获取img标签对象   获得src的属性  动态src属性赋值
  var img = document.getElementById("imgId");
  img.src = "/day08/response7?"+new Date().getTime();
 (4)代码示例
[plain] view plain copy
 
  1. <span style="font-size:18px;">public void doGet(HttpServletRequest request, HttpServletResponse response)  
  2.             throws ServletException, IOException {  
  3.         // 禁止浏览器缓存 验证码图片  
  4.         // response.setHeader("cache-control", "no-cache");  
  5.         // response.setHeader("pragma", "no-cache");  
  6.         // response.setDateHeader("expires", -1);  
  7.   
  8.         // 生成图片。使用Java图形界面技术awt、swing 包  
  9.         // 1 创建内存中图片  
  10.         int width = 120;  
  11.         int height = 30;  
  12.         BufferedImage bufferedImage = new BufferedImage(width, height,  
  13.                 BufferedImage.TYPE_INT_RGB);  
  14.   
  15.         // 2 绘制图片背景色  
  16.         Graphics2D graphics2d = (Graphics2D) bufferedImage.getGraphics();  
  17.         // 指定颜色  
  18.         graphics2d.setColor(Color.GRAY);  
  19.         graphics2d.fillRect(0, 0, width, height);  
  20.   
  21.         // 3、绘制边框  
  22.         graphics2d.setColor(Color.yellow);  
  23.         graphics2d.drawRect(0, 0, width - 1, height - 1);  
  24.   
  25.         // 4、向图片中生成验证码内容  
  26.         graphics2d.setColor(Color.BLUE);  
  27.         graphics2d.setFont(new Font("新宋体", Font.BOLD, 18));  
  28.         // String word =  
  29.         // "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";  
  30.         // 如果使用汉字,字体必须要支持汉字  
  31.         String word = "\u7684\u4e00\u4e86\u662f\u6211\u4e0d\u5728\u4eba\u4eec\u6709\u6765\u4ed6\u8fd9\u4e0a\u7740\u4e2a\u5730\u5230\u5927\u91cc\u8bf4\u5c31\u53bb\u5b50\u5f97\u4e5f\u548c\u90a3\u8981\u4e0b\u770b\u5929\u65f6\u8fc7\u51fa\u5c0f\u4e48\u8d77\u4f60\u90fd\u628a\u597d\u8fd8\u591a\u6ca1\u4e3a\u53c8\u53ef\u5bb6\u5b66\u53ea\u4ee5\u4e3b\u4f1a\u6837\u5e74\u60f3\u751f\u540c\u8001\u4e2d\u5341\u4ece\u81ea\u9762\u524d\u5934\u9053\u5b83\u540e\u7136\u8d70\u5f88\u50cf\u89c1\u4e24\u7528\u5979\u56fd\u52a8\u8fdb\u6210\u56de\u4ec0\u8fb9\u4f5c\u5bf9\u5f00\u800c\u5df1\u4e9b\u73b0\u5c71\u6c11\u5019\u7ecf\u53d1\u5de5\u5411\u4e8b\u547d\u7ed9\u957f\u6c34\u51e0\u4e49\u4e09\u58f0\u4e8e\u9ad8\u624b\u77e5\u7406\u773c\u5fd7\u70b9\u5fc3\u6218\u4e8c\u95ee\u4f46\u8eab\u65b9\u5b9e\u5403\u505a\u53eb\u5f53\u4f4f\u542c\u9769\u6253\u5462\u771f\u5168\u624d\u56db\u5df2\u6240\u654c\u4e4b\u6700\u5149\u4ea7\u60c5\u8def\u5206\u603b\u6761\u767d\u8bdd\u4e1c\u5e2d\u6b21\u4eb2\u5982\u88ab\u82b1\u53e3\u653e\u513f\u5e38\u6c14\u4e94\u7b2c\u4f7f\u5199\u519b\u5427\u6587\u8fd0\u518d\u679c\u600e\u5b9a\u8bb8\u5feb\u660e\u884c\u56e0\u522b\u98de\u5916\u6811\u7269\u6d3b\u90e8\u95e8\u65e0\u5f80\u8239\u671b\u65b0\u5e26\u961f\u5148\u529b\u5b8c\u5374\u7ad9\u4ee3\u5458\u673a\u66f4\u4e5d\u60a8\u6bcf\u98ce\u7ea7\u8ddf\u7b11\u554a\u5b69\u4e07\u5c11\u76f4\u610f\u591c\u6bd4\u9636\u8fde\u8f66\u91cd\u4fbf\u6597\u9a6c\u54ea\u5316\u592a\u6307\u53d8\u793e\u4f3c\u58eb\u8005\u5e72\u77f3\u6ee1\u65e5\u51b3\u767e\u539f\u62ff\u7fa4\u7a76\u5404\u516d\u672c\u601d\u89e3\u7acb\u6cb3\u6751\u516b\u96be\u65e9\u8bba\u5417\u6839\u5171\u8ba9\u76f8\u7814\u4eca\u5176\u4e66\u5750\u63a5\u5e94\u5173\u4fe1\u89c9\u6b65\u53cd\u5904\u8bb0\u5c06\u5343\u627e\u4e89\u9886\u6216\u5e08\u7ed3\u5757\u8dd1\u8c01\u8349\u8d8a\u5b57\u52a0\u811a\u7d27\u7231\u7b49\u4e60\u9635\u6015\u6708\u9752\u534a\u706b\u6cd5\u9898\u5efa\u8d76\u4f4d\u5531\u6d77\u4e03\u5973\u4efb\u4ef6\u611f\u51c6\u5f20\u56e2\u5c4b\u79bb\u8272\u8138\u7247\u79d1\u5012\u775b\u5229\u4e16\u521a\u4e14\u7531\u9001\u5207\u661f\u5bfc\u665a\u8868\u591f\u6574\u8ba4\u54cd\u96ea\u6d41\u672a\u573a\u8be5\u5e76\u5e95\u6df1\u523b\u5e73\u4f1f\u5fd9\u63d0\u786e\u8fd1\u4eae\u8f7b\u8bb2\u519c\u53e4\u9ed1\u544a\u754c\u62c9\u540d\u5440\u571f\u6e05\u9633\u7167\u529e\u53f2\u6539\u5386\u8f6c\u753b\u9020\u5634\u6b64\u6cbb\u5317\u5fc5\u670d\u96e8\u7a7f\u5185\u8bc6\u9a8c\u4f20\u4e1a\u83dc\u722c\u7761\u5174\u5f62\u91cf\u54b1\u89c2\u82e6\u4f53\u4f17\u901a\u51b2\u5408\u7834\u53cb\u5ea6\u672f\u996d\u516c\u65c1\u623f\u6781\u5357\u67aa\u8bfb\u6c99\u5c81\u7ebf\u91ce\u575a\u7a7a\u6536\u7b97\u81f3\u653f\u57ce\u52b3\u843d\u94b1\u7279\u56f4\u5f1f\u80dc\u6559\u70ed\u5c55\u5305\u6b4c\u7c7b\u6e10\u5f3a\u6570\u4e61\u547c\u6027\u97f3\u7b54\u54e5\u9645\u65e7\u795e\u5ea7\u7ae0\u5e2e\u5566\u53d7\u7cfb\u4ee4\u8df3\u975e\u4f55\u725b\u53d6\u5165\u5cb8\u6562\u6389\u5ffd\u79cd\u88c5\u9876\u6025\u6797\u505c\u606f\u53e5\u533a\u8863\u822c\u62a5\u53f6\u538b\u6162\u53d4\u80cc\u7ec6";  
  32.         Random random = new Random();  
  33.         int x = 5;  
  34.         for (int i = 0; i < 4; i++) {  
  35.             // 加入字体旋转 角度-30 --- 30之间  
  36.             int jiaodu = random.nextInt(60) - 30;  
  37.             // 转换角度为弧度  
  38.             double theta = jiaodu * Math.PI / 180;  
  39.   
  40.             int randomIndex = random.nextInt(word.length());// 生成下标  
  41.             char c = word.charAt(randomIndex);  
  42.             // 将字符写入图片  
  43.             graphics2d.rotate(theta, x, 20);  
  44.             graphics2d.drawString(c + "", x, 20);  
  45.             graphics2d.rotate(-theta, x, 20);  
  46.             x += 30;  
  47.         }  
  48.   
  49.         // 5 绘制干扰线  
  50.         graphics2d.setColor(Color.LIGHT_GRAY);  
  51.         int x1;  
  52.         int x2;  
  53.         int y1;  
  54.         int y2;  
  55.         for (int i = 0; i < 10; i++) {  
  56.             x1 = random.nextInt(width);  
  57.             x2 = random.nextInt(width);  
  58.             y1 = random.nextInt(height);  
  59.             y2 = random.nextInt(height);  
  60.   
  61.             graphics2d.drawLine(x1, y1, x2, y2);  
  62.         }  
  63.         // 释放内存中资源  
  64.         graphics2d.dispose();  
  65.   
  66.         // 生成图片到浏览器  
  67.         ImageIO.write(bufferedImage, "jpg", response.getOutputStream());  
  68.     }  
  69.   
  70.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  71.             throws ServletException, IOException {  
  72.         doGet(request, response);  
  73.     }  
  74.   
  75.     public static void main(String[] args) {  
  76.         System.out.println('\u9fa5');  
  77.         System.out.println('\u9fa4');  
  78.         System.out.println('\u9fa3');  
  79.     }  
  80.   
  81. HTML:  
  82. <script type="text/javascript">  
  83.     // 点击切换验证码原理 ,重新载入图片  
  84.     function change(){  
  85.         // 获得id为myimg对象 ,重新加载Servlet程序  
  86.         document.getElementById("myimg").src= "/day6/response7?"+new Date().getTime();  
  87.     }  
  88. </script>  
  89. </head>  
  90. <body>  
  91. <!-- 引用一张图片,显示网页上 -->  
  92. <img src="/day6/response7" onclick="change();" id="myimg" style="cursor: pointer;"/>  
  93. </body>  
  94.   
  95. </span>  

  HttpServletRequest对象简介

  HttpServletRequest对象代表客户端请求,当客户端通过HTTP协议访问服务器时,,HTTP请求中的所有信息都封装在这个对象中,我们可以通过这个对象的方法 获取客户端的请求信息。它继承于ServletRequest类
通过Request对象进行的常用操作
  • 获取客户机信息
  • 获取请求头信息
  • 获取请求参数
  • 利用请求域传递对象
  • 重定向和转发的区别

HttpServletRequest获取客户机信息

  • getRequestURL方法返回客户端发出请求的完整URL
  • getRequestURI 方法返回请求行中的资源名部分(包含虚拟路径)
  • getQueryString 方法返回请求行中的参数部分
  • getRemoteAddr 方法返回发出请求的客户机的IP地址
  • getMethod 得到客户机的请求方式
  • getContextPath 获取工程虚拟目录的名称
URI和URL区别 ?
URI:/day6/request1
URL:http://localhost/day6/request1
URI范围比URL大,http://localhost/day6/request1 是URL也是 URI ,/day6/request1 是URI 不是 URL
 
如何获得当前请求 访问资源路径 ? 就是在服务器网站内部路径 
uri : /day6/request1
contextpath : /day6 
request.getRequestURI().substring(request.getContextPath().length()); ------ /request1 

// 获得请求方式
System.out.println("请求方式:" + request.getMethod());
// 获得协议
System.out.println("协议:" + request.getProtocol());
// 获得请求资源路径
System.out.println("请求路径:" + request.getRequestURI());
System.out.println("请求路径:" + request.getRequestURL());
// 获得请求行中参数
System.out.println("参数:" + request.getQueryString());
// 打印客户机IP
System.out.println("ip:" + request.getRemoteAddr());
// 获得工程虚拟路径名称
System.out.println("虚拟路径名称:" + request.getContextPath());
 
from: http://www.tk4479.net/u013087513/article/details/54587528