The core HttpServletRequest and HttpServletResponse of Java web

Preface

It has only been more than 20 years since Java was born, and I was fortunate enough to solidify this language in the initial stage of its development. Because I believe that as the Java ecosystem becomes more and more active, and Java's design ideas are more and more recognized by the times, and there are more and more Java developers, it will continue to grow like a company and continue to draw fresh blood. And continuous innovation and development until 30, 50, or even 100 years.
Java was born to make applications on different hardware devices, such as TVs, refrigerators, washing machines, etc. Therefore, JVM was designed to shield different underlying systems. However, it did not develop as expected, but was used by mistake. Misunderstandings have formed a deep relationship with the Internet, and therefore the title of Java web, because Java was not written for the web in the early days, Java is a school, and the web is only a disciple of its development, but it is this web disciple. , Pushing the java martial art to the prosperous age.
The growth of Java appeared between 2000 and 2010. With the continuous development of Internet technology in the world, the birth of Servlet is the product of Java catering to the development of the Internet, and it is also an epoch-making change that promotes Java to Internet development technology.
So, what is a servlet?

The internet

Before understanding Servlet, you need to understand the network. As mentioned above, Servlet is a product that caters to the birth of the Internet. Therefore, there is Internet first, and then Servlet.
The concept of network was born in the last century. With the continuous growth of the world's industry, the various components of computers have been continuously upgraded, such as CPU, memory, etc., resulting in more powerful computer functions and higher computing efficiency and speed. People have put forward the idea of ​​connecting computers, so how do you connect?
The communication from one computer to another, people divide them from top to bottom into the ISO seven-layer model, which led to the later development of the TCP/IP network model. But this model is just a network communication skeleton, only the skeleton has no flesh and blood and cannot be called a complete body.
As a result, many agreements were born between each layer, that is, agreements. What format is used to convey the file, what format is used to convey the mail, etc. Among them is the now-famous HTTP protocol, which is used for web page interaction.

HTTP

Http is a hypertext transfer protocol, because it can not only transfer text, but also transfer pictures, videos and other media. There are specific concepts on Baidu, so I won’t repeat them here.
What I want to discuss here is the connection between HTTP and Servlet.
Let's first look at how computers communicate with computers based on HTTP.
Insert picture description here
The dense English in the picture above is very familiar. The message pops up when you open the webpage and press F12, which is the HTTP message, which contains the request header, request body, response body, and so on.
And Serlet?
Java is a programming language, Servlet is naturally a tool for writing information, and HttpServlet is naturally a tool for writing Http information.
This is what I mentioned above, why Servlet is a product that caters to the Internet.

The core of this article is HttpServletRequest and HttpServletResponse.
As a Java programmer, if you want to play Java Web, you must understand the core Servlet of the web. And HttpServlet is the core of Servlet, therefore,

HttpServlet is the core of the core of the development and growth of Java in the current Internet era.

As mentioned above, HttpServlet is a tool for writing Http information. As long as you know the components of Http, you will naturally understand the design principles of HttpServlet.

Http composition

Http is a stateless, connectionless request-response protocol, so it can be divided into two parts: request and response
request. The
request contains the request header and the request body. The
request header contains the request line, the request attribute, and the end line. The
request line It also contains the request method, URL and protocol version
response. The
response contains the response header and response body. The
response header contains the response line, response attributes and end line. The
response line contains the response status code, protocol version, etc.

The specific relationship structure diagram is as follows:
Insert picture description here

Look at the first part:

(1) HTTP request

(1) Request method The
request header contains the request line, and the request line contains the request method.
Common request methods are GET/POST/PUT/DELETE and so on. The most commonly used methods are GET and POST.
For the GET method, there is no request body, because the request parameters are spliced ​​on the URL, so the length will be limited and the exposure will be more obvious.
For the POST method, there must be a request body, because its parameters are stored in the request body, so the length is not limited, and the exposure is relatively safe.
(2) Request attributes
Common request attributes are:

Connection: keep-alive                                  # 维护客户端和服务端的连接关系 
Content-Length: 68                                      # 描述HTTP消息实体的传输长度
Accept: application/json, text/javascript, */*; q=0.01          #发送端(客户端)希望接受的数据类型、q 是权重系数,范围 0 =< q <= 1,q 值越大,请求越倾向于获得其“;”之前的类型表示的内容
Origin: http://apptest.zhidianlife.com:8007            # 浏览器在referrer字段中只显示源网站的源地址(即协议、域名、端口),而不包括完整的路径  
Authorization: c81e7286507f4aa4b6179f4c381b4c64          # 请求所需的认证信息
User-Agent: Mozilla/5.0 (Windows NT 6.3; Win64; x64)      AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36          # 客户端版本号的名字
Content-Type: application/json                     # 请求实体,文档类型
Referer: http://apptest.zhidianlife.com:8007/procurement/order?_t=756512&_winid=w9290         #  从来于哪里
Accept-Encoding: gzip, deflate                        # 客户端接收编码类型,一些网络压缩格式: gzip, deflate
Accept-Language: zh-CN,zh;q=0.9                      # 客户端接收的语言类型 、中文

(3) End Marker In the
above figure, the most easily overlooked is the CRLF at the end—the end mark. Generally, when simulating the Http protocol with Java, the \r\n identifier must be added at the end, which means the end of this unit information.

(Two), HTTP response

(1) Response status code The
response header contains the HTTP protocol version, response status code and so on.
There are five categories of response status codes, with status codes starting with 1, starting with 2, starting with 3, starting with 4, and starting with 5.
1XX...
2XX...
3XX...
4XX...
5XX...
(2) Response body The
response body is the source code of the webpage, and the client browser will parse and render the source code of the webpage into a dynamic operation page.
(3) End marker The
end marker conforms to the end identifier above.

HttpServlet

HttpServlet is developed for Http. After understanding the composition of Http, you can roughly understand its mechanism. The specific situation is discussed in depth in the source code to see what HttpServlet does.

public abstract class HttpServlet extends GenericServlet {
# 这一部分定义了各种请求方法的标识符
private static final long serialVersionUID = 1L;
private static final String METHOD_DELETE = "DELETE";
private static final String METHOD_HEAD = "HEAD";
private static final String METHOD_GET = "GET";
...

# 这一部分定义了各种请求方法的具体实现 	
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	....省略
}
protected void doHead(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	....省略
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	....省略
}
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	....省略
}
...

#最重要的service方法
 protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String method = req.getMethod();
    long lastModified;
    
    # 如果是get请求,则转到get方法中..下同
    if (method.equals("GET")) {
        lastModified = this.getLastModified(req);
        if (lastModified == -1L) {
            this.doGet(req, resp);
        } else {
            long ifModifiedSince;
            try {
                ifModifiedSince = req.getDateHeader("If-Modified-Since");
            } catch (IllegalArgumentException var9) {
                ifModifiedSince = -1L;
            }

            if (ifModifiedSince < lastModified / 1000L * 1000L) {
                this.maybeSetLastModified(resp, lastModified);
                this.doGet(req, resp);
            } else {
                resp.setStatus(304);
            }
        }
    } else if (method.equals("HEAD")) {
        lastModified = this.getLastModified(req);
        this.maybeSetLastModified(resp, lastModified);
        this.doHead(req, resp);
    } else if (method.equals("POST")) {
        this.doPost(req, resp);
    } 
    ....
}
}

The beginning of java web is to implement the service method by customizing Servlet and inheriting HttpServlet. The service method of the custom Servlet passed in will be called when it is called from the upper layer.
There are two questions here:
(1) Whether a custom servlet must inherit HttpServlet before its Service method can be called successfully.
(2) Whether the custom Servlet can directly implement the Servlet interface to achieve the purpose of requesting access.
Guess: The
upper layer calls the service method of HttpServlet. As long as you pass in HttpServlet or its subclasses, you can successfully call the service method of the passed object.

上层调用方法猜想:
?   ?   ?method(HttpServlet  httpServlet){
	httpServlet.service(httpServletRequest , httpServletResponse);
}

Through experiments and verification, it is found that
as long as the customized MyServlet implements Servlet, the service method of the customized MyServlet can be successfully invoked.
This shows that the upper layer calls the service method of the interface Servlet instead of the service method of the HttpServlet.
What is the difference between Servlet and HttpServlet?
Insert picture description here
HttpServlet is a subclass of Servlet. In addition to Servlet, it also implements more functions and customizes various request methods and processing methods of the HTTP protocol. It inherits Servlet functions and expands HTTP related processing methods. class. It is an abstract class but has no abstract methods, which shows that it is not mandatory for subclasses to implement any of its methods.
As you can see in the service source code of the above HttpServlet, the service does a routing and forwarding, which is forwarded to different specific implementation methods according to different request methods. The upper layer injects two objects into the service method when it is called:
HttpServletRequest and HttpServletResponse.
(1) What are they, and where do they come from?
(2) What are their internal methods and what they can do.

Where is the upper level?

Servlet is controlled by the upper layer, and the service method is also called by the upper layer. So where is the upper level and what is it?
Here to introduce a web container, what is a web container? Literally, it is a container that holds a web program, and a web program can be clearly understood as a Servlet. So the web container can also be understood as a container for Serlvet.
Insert picture description here
Web container is a general term for applications, which specifically includes middleware such as Tomcat and JBoss.

HttpServletRequest

What is the relationship between the web container and this object?
HttpServletRequest is a request object. The web container is responsible for parsing the received HTTP information to generate an HttpServletRequest object, so this object is actually an encapsulation of HTTP protocol request information.
Contains various parameters of the request header, request body parameters, protocol version, request address, timestamp, cookie, session, etc.
Specifically, the call chain can be traced. The HttpServletRequest object information comes from the top-level interface ServletRequest, and the information that can be called by this interface is the encapsulated information:

public interface ServletRequest {

Object getAttribute(String var1);  // 某个属性

Enumeration<String> getAttributeNames(); // 属性集合

String getCharacterEncoding(); // 编码方式

void setCharacterEncoding(String var1) throws UnsupportedEncodingException;

int getContentLength();  // 请求体长度

long getContentLengthLong();

String getContentType(); // 请求体内容形式

ServletInputStream getInputStream() throws IOException;

String getParameter(String var1);  // 请求体参数

Enumeration<String> getParameterNames(); // 请求体参数集合

String[] getParameterValues(String var1); // 请求体中的value值

Map<String, String[]> getParameterMap();  // 请求体中的value值集合

String getProtocol(); // 协议

String getScheme();

String getServerName(); 

int getServerPort(); // 端口

BufferedReader getReader() throws IOException;

String getRemoteAddr(); 

String getRemoteHost(); // 请求主机

void setAttribute(String var1, Object var2);

void removeAttribute(String var1);

Locale getLocale();

Enumeration<Locale> getLocales();

boolean isSecure();

RequestDispatcher getRequestDispatcher(String var1);

/** @deprecated */
@Deprecated
String getRealPath(String var1);

int getRemotePort();

String getLocalName();

String getLocalAddr();

int getLocalPort();

ServletContext getServletContext();

AsyncContext startAsync() throws IllegalStateException;

AsyncContext startAsync(ServletRequest var1, ServletResponse var2) throws IllegalStateException;

boolean isAsyncStarted();

boolean isAsyncSupported();

AsyncContext getAsyncContext();

DispatcherType getDispatcherType();
}

HttpServletResponse

This object is the same, it is an encapsulation of HTTP response information.
Specifically, it can be traced to the ServletResponse object:

public interface ServletResponse {
String getCharacterEncoding();

String getContentType();

ServletOutputStream getOutputStream() throws IOException;

PrintWriter getWriter() throws IOException;

void setCharacterEncoding(String var1);  // 设置编码方式

void setContentLength(int var1);

void setContentLengthLong(long var1);

void setContentType(String var1);

void setBufferSize(int var1);

int getBufferSize();

void flushBuffer() throws IOException;

void resetBuffer();

boolean isCommitted();

void reset();

void setLocale(Locale var1);

Locale getLocale();
}

The entire interactive process

As can be seen from the above, a web page request to response process.
Insert picture description here

The client generally uses a browser to access. When the user uses the browser to send a message to the server,

  1. The browser will send the client's request to the server in the form of HTTP protocol
  2. The web container encapsulates the HTTP protocol into the HttpServletRequest and HttpServletResponse objects, the web finds the corresponding Servlet service, and passes the two objects HttpServletRequest and HttpServletResponse into it.
  3. After the service program performs processing calculations and database interaction on these two objects, it returns these two objects to the Web container.
  4. The web container parses the two object data and sends it to the client browser in the form of Http protocol.

Finally, after the browser receives the information, the entire process of parsing in accordance with the HTTP protocol is completed.

What can programmers do

For this set of processes, programmers usually write Servlet services, such as writing Java web to process HttpServletRequest and HttpServletResponse objects. Java web has evolved from the early servlet + JSP and today's SSM, from the monolithic architecture to the microservices, such as Springboot + Spring cloud. A complex system may also include messaging middleware (such as RabbitMQ), caching middleware (such as Redis), load balancing middleware (such as Nginx), and so on.
This whole system belongs to Servlet service, and the objects that the system needs to process are HttpServletRequest and HttpServletResponse. These two objects are messaging objects. What the program needs to solve is the correct processing of messages, high concurrency when processing requests, and high availability under system exceptions.

The above is only a personal understanding. If there is something inappropriate, please help from the passing gods.

Guess you like

Origin blog.csdn.net/weixin_43901067/article/details/106295855