Detailed Explanation of Request and Response of JavaWeb

HTTP protocol

Introduction

The HTTP protocol (HyperText Transfer Protocol) is the most widely used network transfer protocol on the Internet, and all WWW documents must comply with this standard.

HTTP is a communication protocol based on TCP/IP to transfer data (HTML files, image files, query results, etc.).

How HTTP works

The HTTP protocol works on a client-server architecture. The browser, as an HTTP client, sends all requests to the HTTP server, namely the WEB server, through the URL.

Web servers include: Apache server, IIS server (Internet Information Services), etc.

The web server sends response information to the client according to the received request.

The default HTTP port number is 80, but you can also change it to 8080 or other ports.

Three things to note about HTTP:

  • HTTP is connectionless: the meaning of connectionless is to limit each connection to only process one request. After the server has processed the client's request and received the client's response, it will disconnect. In this way, transmission time can be saved.
  • HTTP is media independent: This means that any type of data can be sent via HTTP as long as the client and server know how to process the data content. The client and server specify the appropriate MIME-type content type.
  • HTTP is stateless: The HTTP protocol is a stateless protocol. Statelessness means that the protocol has no memory capacity for transaction processing. The lack of state means that if the previous information is needed for subsequent processing, it must be retransmitted, which may result in an increase in the amount of data transmitted per connection. On the other hand, when the server does not need previous information, its response is faster.
  • The content displayed by the browser includes HTML, XML, GIF, Flash, etc. The browser distinguishes them by MIME Type and decides what content and format to display.

    Request message data format

The request message that the client sends an HTTP request to the server includes the following format: request line, request header, blank line, and request data. The following figure shows the general format of the request message. .

  1.  Request line

The "method" in the request line is actually a command, indicating the operation (or action) the client wants the server to perform on the resource specified by the URL, that is, what the server does; the URL locates the requested resource; the protocol version is used to notify the server to the client The HTTP version number used by the end.

There are two common request methods:          

         GET:

                     1. The  request parameters are in the request line, after the url.

                     2. The  requested URL length is limited

                     3.  Not very safe

        POST:

                    1. The  request parameters are in the request body

                    2.  There is no limit to the length of the requested url

                    3.  Relatively safe

2.  Request header

The header line of the HTTP message is used to carry additional information, and there can be zero, one or more lines. Each header line includes a header line field name, followed by a colon, then an optional space, followed by the corresponding value, and finally CRLF.

Different header lines carry different category information for different purposes.

Header information description
Accept This header information specifies the MIME types that the browser or other clients can handle. The values  image/png  or  image/jpeg  are the two most common possible values.
Accept-Charset This header information specifies the character set that the browser can use to display the information. For example, ISO-8859-1.
Accept-Encoding This header information specifies the type of encoding that the browser knows how to handle. The values  gzip  or  compress  are the two most common possible values.
Accept-Language This header information specifies the preferred language of the client. In this case, the servlet will produce results in multiple languages. For example, en, en-us, ru, etc.
Authorization This header information is used by the client to identify itself when accessing a password-protected web page.
Connection This header indicates whether the client can handle persistent HTTP connections. Persistent connections allow clients or other browsers to retrieve multiple files with a single request. The value  Keep-Alive  means that a persistent connection is used.
Content-Length This header information is only applicable to POST requests and gives the size of the POST data (in bytes).
Cookie This header information returns the cookies previously sent to the browser to the server.
Host This header information specifies the host and port in the original URL.
If-Modified-Since This header information represents the page that the client wants only if the page has changed after the specified date. If there are no new results available, the server will send a 304 code indicating the  Not Modified  header.
If-Unmodified-Since This header is the opposite of If-Modified-Since, it specifies that the operation will succeed only when the document is older than the specified date.
Referer This header information indicates the URL of the web page pointed to. For example, if you are on page 1 and click a link to page 2, when the browser requests page 2, the URL of page 1 will be included in the Referer header.
User-Agent This header information identifies the browser or other client that made the request, and can return different content to different types of browsers.

 3.  Request blank lines

            Blank line, used to separate request line and request data

4.  Request body (body)

             Encapsulate the request parameters of the POST request message

            The request body is the load of the request message, which can be text, pictures, videos, HTML documents, applications, emails, etc.


Response message data format

The response information is sent by the Web server to the browser, and the HTTP response is also composed of four parts: status line, message header, blank line, and response body.

  1.  Response line:

              1.  Composition: protocol/version response status code status code description

              2.  Response status code: The server tells the client browser the status of this request and response. Different states have different meanings

                    1. The  status codes are all 3 digits 

                    2.  Classification:

classification Classification description
1** Information, the server receives the request and requires the requester to continue to perform the operation
2** Success, the operation was successfully received and processed. Representative: 200
3** Redirection requires further action to complete the request. Representative: 302 (redirect), 304 (access buffer)
4** Client error, the request contains a syntax error or the request could not be completed. Representative: 404 (the request path does not have a corresponding resource), 405 (the request method does not have a corresponding doXxx method)
5** Server error. The server encountered an error while processing the request. Represents: 500 (an exception occurred inside the server)

 2.  Response header:

Header information description
Allow This header information specifies the request method (GET, POST, etc.) supported by the server.
Cache-Control This header information specifies under what circumstances the response document can be safely cached. The possible values ​​are: public, private,  or  no-cache,  etc. Public means that the document is cacheable, Private means that the document is a private document for a single user and can only be stored in a private (non-shared) cache, and no-cache means that the document should not be cached.
Connection This header indicates whether the browser uses persistent HTTP connections. The value  close  indicates that the browser does not use persistent HTTP connections, and the value  keep-alive  means that persistent connections are used.
Content-Disposition This header information allows you to request the browser to ask the user to save the response to disk in a file with the given name.
Content-Encoding During transmission, this header information specifies the encoding method of the page.
Content-Language This header information indicates the language in which the document was written. For example, en, en-us, ru, etc.
Content-Length This header information indicates the number of bytes in the response. This information is only needed when the browser uses a keep-alive HTTP connection.
Content-Type This header information provides the MIME (Multipurpose Internet Mail Extension) type of the response document.
Expires This header information specifies the time when the content expires, after which the content is no longer cached.
Last-Modified This header information indicates the last modification time of the document. The client can then cache the file and  provide a date in the If-Modified-Since request header in future requests  .
Location 这个头信息应被包含在所有的带有状态码的响应中。在 300s 内,这会通知浏览器文档的地址。浏览器会自动重新连接到这个位置,并获取新的文档。
Refresh 这个头信息指定浏览器应该如何尽快请求更新的页面。您可以指定页面刷新的秒数。
Retry-After 这个头信息可以与 503(Service Unavailable 服务不可用)响应配合使用,这会告诉客户端多久就可以重复它的请求。
Set-Cookie 这个头信息指定一个与页面关联的 cookie。

 3. 响应空行

 4. 响应体:传输的数据

响应空行与相应体的作用与请求报文相同。


请求:request

下面的方法可用在Servlet程序中读取HTTP头。这些方法通过HttpServletRequest对象可用。

序号 方法 & 描述
1 Cookie[] getCookies()
返回一个数组,包含客户端发送该请求的所有的 Cookie 对象。
2 Enumeration getAttributeNames()
返回一个枚举,包含提供给该请求可用的属性名称。
3 Enumeration getHeaderNames()
返回一个枚举,包含在该请求中包含的所有的头名。
4 Enumeration getParameterNames()
返回一个 String 对象的枚举,包含在该请求中包含的参数的名称。
5 HttpSession getSession()
返回与该请求关联的当前 session 会话,或者如果请求没有 session 会话,则创建一个。
6 HttpSession getSession(boolean create)
返回与该请求关联的当前 HttpSession,或者如果没有当前会话,且创建是真的,则返回一个新的 session 会话。
7 Locale getLocale()
基于 Accept-Language 头,返回客户端接受内容的首选的区域设置。
8 Object getAttribute(String name)
以对象形式返回已命名属性的值,如果没有给定名称的属性存在,则返回 null。
9 ServletInputStream getInputStream()
使用 ServletInputStream,以二进制数据形式检索请求的主体。
10 String getAuthType()
返回用于保护 Servlet 的身份验证方案的名称,例如,"BASIC" 或 "SSL",如果JSP没有受到保护则返回 null。
11 String getCharacterEncoding()
返回请求主体中使用的字符编码的名称。
12 String getContentType()
返回请求主体的 MIME 类型,如果不知道类型则返回 null。
13 String getContextPath()
返回指示请求上下文的请求 URI 部分。
14 String getHeader(String name)
以字符串形式返回指定的请求头的值。
15 String getMethod()
返回请求的 HTTP 方法的名称,例如,GET、POST 或 PUT。
16 String getParameter(String name)
以字符串形式返回请求参数的值,或者如果参数不存在则返回 null。
17 String getPathInfo()
当请求发出时,返回与客户端发送的 URL 相关的任何额外的路径信息。
18 String getProtocol()
返回请求协议的名称和版本。
19 String getQueryString()
返回包含在路径后的请求 URL 中的查询字符串。
20 String getRemoteAddr()
返回发送请求的客户端的互联网协议(IP)地址。
21 String getRemoteHost()
返回发送请求的客户端的完全限定名称。
22 String getRemoteUser()
如果用户已通过身份验证,则返回发出请求的登录用户,或者如果用户未通过身份验证,则返回 null。
23 String getRequestURI()
从协议名称直到 HTTP 请求的第一行的查询字符串中,返回该请求的 URL 的一部分。
24 String getRequestedSessionId()
返回由客户端指定的 session 会话 ID。
25 String getServletPath()
返回调用 JSP 的请求的 URL 的一部分。
26 String[] getParameterValues(String name)
返回一个字符串对象的数组,包含所有给定的请求参数的值,如果参数不存在则返回 null。
27 boolean isSecure()
返回一个布尔值,指示请求是否使用安全通道,如 HTTPS。
28 int getContentLength()
以字节为单位返回请求主体的长度,并提供输入流,或者如果长度未知则返回 -1。
29 int getIntHeader(String name)
返回指定的请求头的值为一个 int 值。
30 int getServerPort()
返回接收到这个请求的端口号。
31 int getParameterMap()
将参数封装成 Map 类型。

  请求转发:一种在服务器内部的资源跳转方式

     1. 通过request对象获取请求转发器对象:

                  RequestDispatcher getRequestDispatcher(String path)

     2. 使用RequestDispatcher对象来进行转发:

                 forward(ServletRequest request, ServletResponse response) 

转发到另个类,需要request.getAttribute("转发的内容的名字");

共享数据

  域对象:一个有作用范围的对象,可以在范围内共享数据

        request域:代表一次请求的范围,一般用于请求转发的多个资源中共享数据

           方法:

                    1. void setAttribute(String name,Object obj):存储数据

                    2. Object getAttitude(String name):通过键获取值

                    3. void removeAttribute(String name):通过键移除键值对


响应:response对象

下面的方法可用于在 Servlet 程序中设置 HTTP 响应报头。这些方法通过 HttpServletResponse 对象可用。

序号 方法 & 描述
1 String encodeRedirectURL(String url)
为 sendRedirect 方法中使用的指定的 URL 进行编码,或者如果编码不是必需的,则返回 URL 未改变。
2 String encodeURL(String url)
对包含 session 会话 ID 的指定 URL 进行编码,或者如果编码不是必需的,则返回 URL 未改变。
3 boolean containsHeader(String name)
返回一个布尔值,指示是否已经设置已命名的响应报头。
4 boolean isCommitted()
返回一个布尔值,指示响应是否已经提交。
5 void addCookie(Cookie cookie)
把指定的 cookie 添加到响应。
6 void addDateHeader(String name, long date)
添加一个带有给定的名称和日期值的响应报头。
7 void addHeader(String name, String value)
添加一个带有给定的名称和值的响应报头。
8 void addIntHeader(String name, int value)
添加一个带有给定的名称和整数值的响应报头。
9 void flushBuffer()
强制任何在缓冲区中的内容被写入到客户端。
10 void reset()
清除缓冲区中存在的任何数据,包括状态码和头。
11 void resetBuffer()
清除响应中基础缓冲区的内容,不清除状态码和头。
12 void sendError(int sc)
使用指定的状态码发送错误响应到客户端,并清除缓冲区。
13 void sendError(int sc, String msg)
使用指定的状态发送错误响应到客户端。
14 void sendRedirect(String location)
使用指定的重定向位置 URL 发送临时重定向响应到客户端。
15 void setBufferSize(int size)
为响应主体设置首选的缓冲区大小。
16 void setCharacterEncoding(String charset)
设置被发送到客户端的响应的字符编码(MIME 字符集)例如,UTF-8。
17 void setContentLength(int len)
设置在 HTTP Servlet 响应中的内容主体的长度,该方法设置 HTTP Content-Length 头。
18 void setContentType(String type)
如果响应还未被提交,设置被发送到客户端的响应的内容类型。
19 void setDateHeader(String name, long date)
设置一个带有给定的名称和日期值的响应报头。
20 void setHeader(String name, String value)
设置一个带有给定的名称和值的响应报头。
21 void setIntHeader(String name, int value)
设置一个带有给定的名称和整数值的响应报头。
22 void setLocale(Locale loc)
如果响应还未被提交,设置响应的区域。
23 void setStatus(int sc)
为该响应设置状态码。

重定向 

       1. 设置状态码为302

                response.setStatus(302);

       2.设置响应头location

                response.setHeader("location","/day15/responseDemo2");

        简单的重定向方法

                response.sendRedirect("/day15/responseDemo2");

        乱码问题:

                  response.setContentType("text/html;charset=utf-8");


ServletContext对象:

  1. 概念:

          代表整个web应用,可以和程序的容器(服务器)来通信

  2. 获取:

        1. 通过request对象获取

              request.getServletContext();

        2. 通过HttpServlet获取

              this.getServletContext();

    3. 功能:

        1. 获取MIME类型:

              MIME类型:在互联网通信过程中定义的一种文件数据类型

                  格式: 大类型/小类型   text/html        image/jpeg

                获取:String getMimeType(String file)  

        2. 域对象:共享数据

            1. setAttribute(String name,Object value)

            2. getAttribute(String name)

            3. removeAttribute(String name)

                  ServletContext对象范围:所有用户所有请求的数据

        3. 获取文件的真实(服务器)路径

            1. 方法:String getRealPath(String path)  

                String b = context.getRealPath("/b.txt");//web目录下资源访问

                String c = context.getRealPath("/WEB-INF/c.txt");//WEB-INF目录下的资源访

                String a = context.getRealPath("/WEB-INF/classes/a.txt");//src目录下的资源访问

文件下载小例子

前端代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <!-- 加上虚拟目录-->
    <a href="/JavaEE_Web_02_01code_war_exploded/img/女.jpg">展示图片</a>
    <a href="/JavaEE_Web_02_01code_war_exploded/DownloadServlet?filename=img/女.jpg ">下载图片</a>
    <a href="/JavaEE_Web_02_01code_war_exploded/img/女.png">展示图片</a>
    <a href="/JavaEE_Web_02_01code_war_exploded/DownloadServlet?filename=img/女.png">下载图片</a>
</body>
</html>

后端代码

package com.example.JavaEE_Web_02_01code.ServletContext;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ResourceBundle;

/**
 * @Author: Promsing
 * @Date: 2021/2/2 - 19:41
 * @Description: 文件下载
 * @version: 1.0
 */
@WebServlet("/DownloadServlet")
public class DownloadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取请求参数,文件名称
        String filename = request.getParameter("filename");
        //2.使用字节输入流加载文件到内存
        ServletContext servletContext = this.getServletContext();
        String realPath = servletContext.getRealPath(filename);
        FileInputStream fis=new FileInputStream(realPath);
        //注意:设置response的响应头
        String mimeType = servletContext.getMimeType(filename);
        response.setHeader("content-type",mimeType);
        response.setHeader("content-disposition","attachment;filename"+filename);

        //3.将输入流的数据写道输出流中
        ServletOutputStream sos = response.getOutputStream();
        byte[] bytes=new byte[1024*8];
        int len=0;
        while ((len=fis.read(bytes))!=-1){
            sos.write(bytes,0,len);
        }
        //管理流
        fis.close();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

创作不易,如果本篇博客对您有一定的帮助,大家记得留言+点赞哦。 

 

Guess you like

Origin blog.csdn.net/promsing/article/details/113618924