Java Web study concluded (5) - HttpServletResponse objects Detailed

A, HttpServletResponse common applications - to generate verification codes

1.1, generating a random image as the authentication code

  Picture mainly used to generate a BufferedImage class,

  

Images generated random examples:

Copy the code
 1 package gacl.response.study;
 2 
 3 import java.awt.Color;
 4 import java.awt.Font;
 5 import java.awt.Graphics2D;
 6 import java.awt.image.BufferedImage;
 7 import java.io.IOException;
 8 import java.util.Random;
 9 import javax.imageio.ImageIO;
10 import javax.servlet.ServletException;
11 import javax.servlet.http.HttpServlet;
12 import javax.servlet.http.HttpServletRequest;
13 import javax.servlet.http.HttpServletResponse;
14 
15 public class ResponseDemo03 extends HttpServlet {
16 
17     public void doGet(HttpServletRequest request, HttpServletResponse response)
18             throws ServletException, IOException {
19         
20         response.setHeader("refresh", "5");//设置refresh响应头控制浏览器每隔5秒钟刷新一次
21         //1.在内存中创建一张图片
22         BufferedImage image = new BufferedImage(80, 20, BufferedImage.TYPE_INT_RGB);
23         //2.得到图片
24         //Graphics g = image.getGraphics();
25         Graphics2D g = (Graphics2D)image.getGraphics();
26         g.setColor(Color.WHITE);//设置图片的背景色
27         g.fillRect(0, 0, 80, 20);//填充背景色
28         //3.向图片上写数据
29         g.setColor(Color.BLUE);//设置图片上字体的颜色
30         g.setFont(new Font(null, Font.BOLD, 20));
31         g.drawString(makeNum(), 0, 20);
32         //4.设置响应头控制浏览器浏览器以图片的方式打开
33         response.setContentType("image/jpeg");//等同于response.setHeader("Content-Type", "image/jpeg");
34         //5.设置响应头控制浏览器不缓存图片数据
35         response.setDateHeader("expries", -1);
36         response.setHeader("Cache-Control", "no-cache");
37         response.setHeader("Pragma", "no-cache");
38         //6.将图片写给浏览器
39         ImageIO.write(image, "jpg", response.getOutputStream());
40     }
41 
42     /**
43      * 生成随机数字
44      * @return
45      */
46     private String makeNum(){
47         Random random = new Random();
48         String num = random.nextInt(9999999)+"";
49         StringBuffer sb = new StringBuffer();
50         for (int i = 0; i < 7-num.length(); i++) {
51             sb.append("0");
52         }
53         num = sb.toString()+num;
54         return num;
55     }
56     
57     public void doPost(HttpServletRequest request, HttpServletResponse response)
58             throws ServletException, IOException {
59         doGet(request, response);
60     }
61 
62 }
Copy the code

Results are as follows:

  

Two, HttpServletResponse common applications - Set response header control browser behavior

2.1, set the http response headers to control the browser cache prohibit the current document content     

1 response.setDateHeader("expries", -1);
2 response.setHeader("Cache-Control", "no-cache");
3 response.setHeader("Pragma", "no-cache");

2.2, http response header is provided to control the timing of refreshing a web page browser (Refresh)

1 response.setHeader("refresh", "5");//设置refresh响应头控制浏览器每隔5秒钟刷新一次

 2.3, redirecting the request response achieved by

  Request redirection means: a web resource after receiving the client request, notify the client to access another web resource, which is called redirect the request.

  Scenario: a user login, the user first accesses the login page, the login is successful, it will jump to a page, this process is a process of redirection request

  Implementation: response.sendRedirect (String location), i.e., the response object call request redirection sendRedirect implemented method of
  realization of the principle of internal sendRedirect: using the status code and the response 302 is provided in response to the first location disposed redirection

E.g:

Copy the code
 1 package gacl.response.study;
 2 import java.io.IOException;
 3 import javax.servlet.ServletException;
 4 import javax.servlet.http.HttpServlet;
 5 import javax.servlet.http.HttpServletRequest;
 6 import javax.servlet.http.HttpServletResponse;
 7 
 8 public class ResponseDemo04 extends HttpServlet {
 9 
10     public void doGet(HttpServletRequest request, HttpServletResponse response)
11             throws ServletException, IOException {
12         /**
13          * 1.调用sendRedirect方法实现请求重定向,
14          * sendRedirect方法内部调用了
15          * response.setHeader("Location", "/JavaWeb_HttpServletResponse_Study_20140615/index.jsp");
16          * response.setStatus(HttpServletResponse.SC_FOUND);//设置302状态码,等同于response.setStatus(302);
17          */
18         response.sendRedirect("/JavaWeb_HttpServletResponse_Study_20140615/index.jsp");
19         
20         //2.使用response设置302状态码和设置location响应头实现重定向实现请求重定向
21         //response.setHeader("Location", "/JavaWeb_HttpServletResponse_Study_20140615/index.jsp");
22         //response.setStatus(HttpServletResponse.SC_FOUND);//设置302状态码,等同于response.setStatus(302);
23     }
24 
25     public void doPost(HttpServletRequest request, HttpServletResponse response)
26             throws ServletException, IOException {
27         doGet(request, response);
28     }
29 }
Copy the code

Three, web projects recommended wording URL address

  在JavaWeb开发中,只要是写URL地址,那么建议最好以"/"开头,也就是使用绝对路径的方式,那么这个"/"到底代表什么呢?可以用如下的方式来记忆"/":如果"/"是给服务器用的,则代表当前的web工程,如果"/"是给浏览器用的,则代表webapps目录。

3.1、"/"代表当前web工程的常见应用场景

①.ServletContext.getRealPath(String path)获取资源的绝对路径

Copy the code
1 /**
2 * 1.ServletContext.getRealPath("/download/1.JPG")是用来获取服务器上的某个资源,
3 * 那么这个"/"就是给服务器用的,"/"此时代表的就是web工程
4  * ServletContext.getRealPath("/download/1.JPG")表示的就是读取web工程下的download文件夹中的1.JPG这个资源
5 * 只要明白了"/"代表的具体含义,就可以很快写出要访问的web资源的绝对路径
6 */
7 this.getServletContext().getRealPath("/download/1.JPG");
Copy the code

②.在服务器端forward到其他页面

1 /**
2 * 2.forward
3  * 客户端请求某个web资源,服务器跳转到另外一个web资源,这个forward也是给服务器用的,
4 * 那么这个"/"就是给服务器用的,所以此时"/"代表的就是web工程
5 */
6 this.getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);

③.使用include指令或者<jsp:include>标签引入页面

1 <%@include file="/jspfragments/head.jspf" %>
1 <jsp:include page="/jspfragments/demo.jsp" />

  此时"/"代表的都是web工程。

3.2、"/"代表webapps目录的常见应用场景

①.使用sendRedirect实现请求重定向

1 response.sendRedirect("/JavaWeb_HttpServletResponse_Study_20140615/index.jsp");

  服务器发送一个URL地址给浏览器,浏览器拿到URL地址之后,再去请求服务器,所以这个"/"是给浏览器使用的,此时"/"代表的就是webapps目录,"/JavaWeb_HttpServletResponse_Study_20140615/index.jsp"这个地址指的就是"webapps\JavaWeb_HttpServletResponse_Study_20140615\index.jsp"

  response.sendRedirect("/项目名称/文件夹目录/页面");这种写法是将项目名称写死在程序中的做法,不灵活,万一哪天项目名称变了,此时就得改程序,所以推荐使用下面的灵活写法:

1 response.sendRedirect("/JavaWeb_HttpServletResponse_Study_20140615/index.jsp");

  这种写法改成

1 response.sendRedirect(request.getContextPath()+"/index.jsp");

  request.getContextPath()获取到的内容就是"/JavaWeb_HttpServletResponse_Study_20140615",这样就比较灵活了,使用request.getContextPath()代替"/项目名称",推荐使用这种方式,灵活方便!

②.使用超链接跳转

1 <a href="/JavaWeb_HttpServletResponse_Study_20140615/index.jsp">跳转到首页</a>

  这是客户端浏览器使用的超链接跳转,这个"/"是给浏览器使用的,此时"/"代表的就是webapps目录。

  使用超链接访问web资源,绝对路径的写法推荐使用下面的写法改进:

1 <a href="${pageContext.request.contextPath}/index.jsp">跳转到首页</a>

  这样就可以避免在路径中出现项目的名称,使用${pageContext.request.contextPath}取代"/JavaWeb_HttpServletResponse_Study_20140615"

③.Form表单提交

1 <form action="/JavaWeb_HttpServletResponse_Study_20140615/servlet/CheckServlet" method="post">    
2         <input type="submit" value="提交">
3 </form>

  这是客户端浏览器将form表单提交到服务器,所以这个"/"是给浏览器使用的,此时"/"代表的就是webapps目录。

 对于form表单提交中action属性绝对路径的写法,也推荐使用如下的方式改进:

1 <form action="${pageContext.request.contextPath}/servlet/CheckServlet" method="post">
2          <input type="submit" value="提交">
3 </form>

  ${pageContext.request.contextPath}得到的就是"/JavaWeb_HttpServletResponse_Study_20140615"

  $ {pageContext.request.contextPath} effect equivalent to request.getContextPath (), both acquired are "/ item name"

References ④.js scripts and css style files

1  <%--使用绝对路径的方式引用js脚本--%>
2  <script type="text/javascript" src="${pageContext.request.contextPath}/js/index.js"></script>
3  <%--${pageContext.request.contextPath}与request.getContextPath()写法是得到的效果是一样的--%>
4  <script type="text/javascript" src="<%=request.getContextPath()%>/js/login.js"></script>
5  <%--使用绝对路径的方式引用css样式--%>
6  <link rel="stylesheet" href="${pageContext.request.contextPath}/css/index.css" type="text/css"/>

Comprehensive Example:

Copy the code
 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
 2 
 3 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 4 <html>
 5   <head>
 6     <title>"/"代表webapps目录的常见应用场景</title>
 7     <%--使用绝对路径的方式引用js脚本--%>
 8     <script type="text/javascript" src="${pageContext.request.contextPath}/js/index.js"></script>
 9     <%--${pageContext.request.contextPath}与request.getContextPath()写法是得到的效果是一样的--%>
10     <script type="text/javascript" src="<%=request.getContextPath()%>/js/login.js"></script>
11     <%--使用绝对路径的方式引用css样式--%>
12       <link rel="stylesheet" href="${pageContext.request.contextPath}/css/index.css" type="text/css"/>
13   </head>
14   
15   <body>
16       <%--form表单提交--%>
17        <form action="${pageContext.request.contextPath}/servlet/CheckServlet" method="post">
18            <input type="submit" value="提交">
19        </form>
20        <%--超链接跳转页面--%>
21        <a href="${pageContext.request.contextPath}/index.jsp">跳转到首页</a>
22   </body>
23 </html>
Copy the code

 Four, response details

  getOutputStream getWriter Methods for obtaining and outputting binary data , outputting the text data ServletOuputStream of, PrintWriter object.
  getOutputStream and getWriter these two methods are mutually exclusive , call any of these methods after, you can not call another method.  
  Servlet writes the data to the program or ServletOutputStream PrintWriter object to be retrieved in response Servlet engine from the inside, as a Servlet engine in response to the body of the message data, and then outputs the first row and the response status in response to the combination of the client. 
  After Serlvet of service method, Servlet engine will check whether getWriter or output stream object getOutputStream method returns the close method has been called, and if not, Servlet engine will call the close method to close the output stream object.

Reproduced in: https: //my.oschina.net/zhanghaiyang/blog/606317

Guess you like

Origin blog.csdn.net/weixin_33693070/article/details/92661519