English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

How to Implement Request and Response in javaweb

 Let's take a look at a flowchart first:

 The process of the server handling requests:

  (1The server will open a new thread for each request it receives.
  (2The server will encapsulate the client's request data into the request object, and the request is the carrier of the request data!
  (3The server will also create a response object, which is connected to the client and can be used to send responses to the client.
 

 The flowchart shows that in the request and response of JavaWeb, the two most important parameters are request and response, which are in the Servlet's service() method.

1、Response concept:

         The response is a parameter of the Servlet.service method, of type javax.servlet.http.HttpServletResponse. For each request sent by the client, the server will create a response object and pass it to the Servlet.service() method. The response object is used to respond to the client, which means that the response object can be used to complete the response work to the client in the service() method.

The functions of the response object are divided into the following four types:

(1)Set response header information

(2)Send status code

(3)Set response body

(4)Redirect 

2、Response body

The response object is used to output the response body (response body) to the client, and the response object provides two response stream objects in total:

(1)PrintWriter out = response.getWriter():Get character stream;

(2)ServletOutputStream out = response.getOutputStream():Get byte stream; 

Of course, if the response body content is a character, then use response.getWriter(), and if the response content is a byte, such as during a download, then you can use response.getOutputStream().

NoteYou cannot use both streams at the same time in a single request! That is to say, either you use repsonse.getWriter() or response.getOutputStream(), but not both. Otherwise, an illegalStateException exception will be thrown.

3、Set response header information

You can use the setHeader() method of the response object to set response headers! The response headers set by this method will eventually be sent to the client browser!

(1)response.setHeader("content-type”, "text/html;charset=utf-8"): Set content-type response header, which is used to inform the browser that the response content is of html type, encoded in utf-8。And at the same time, it will set the character stream encoding of response to utf-8,i.e., response.setCharaceterEncoding("utf-8");

(2)response.setHeader("Refresh","5; URL=http://www.baidu.com":5Automatically jump to Baidu homepage after 1 second.

4Set status code and other methods

(1) response.setContentType("text}}/html;charset=utf-8"): Equivalent to calling response.setHeader(“content-type”, "text/html;charset=utf-8");

(2) response.setCharacterEncoding("utf-8) Set character encoding of the character response stream to utf-8;

(3) response.setStatus(200): Set status code;

(4) response.sendError(404, "The resource you are looking for does not exist"): When sending an error status code, Tomcat will jump to a fixed error page, but it can display error information.

5, redirection (*****重点*****)

5.1 What is redirection (two requests)?

When you access http://www.sun.com, you will find that the URL in the browser address bar will change to http://www.oracle.com/us/sun/index.htm, which is a redirection. Redirection is when the server notifies the browser to access another address, i.e., to make another request.

 5.2 How to complete redirection?

Answer: The status code of redirection is302Firstly, we use the response object to send302status code, and then set a Location, which is to provide a usable URL, and let the browser access the new URL to achieve redirection.

For example:

public class AServlet extends HttpServlet { 
  public void doGet(HttpServletRequest request, HttpServletResponse response) 
      throws ServletException, IOException { 
    response.setStatus(302);  
    response.setHeader("Location", "http://www.baidu.com);  
  } 
} 

The purpose of the above code is: after accessing AServlet, it notifies the browser to redirect to Baidu's homepage. The client browser parses the response code as302After that, it knows that the server wants to redirect, so it will immediately retrieve the response header Location and send the second request.

There is also a quick redirection method,even using the response.sendRedirect() method. For example, the two statements in the above example can be replaced with response.sendRedirect("http://www.baidu.com)) instead.

request—wraps all the client request data 

1Overview of request

) Request is a parameter of Servlet.service() method, the type is javax.servlet.http.HttpServletRequest. When the client sends each request, the server will create a request object, encapsulate the request data into the request, and then pass it to the service() method when calling Servlet.service() method, which means that the request object can be used to obtain the request data in the service() method.

As shown in the figure:


) The functions of request can be divided into the following types:

(1) Encapsulates the request header data;

(2) Encapsulates the request body data, if it is a GET request, then there is no body;

(3) Request is a domain object, which can be treated as a Map to add and retrieve data;

(4) Request provides request forwarding and request inclusion features.

2Domain methods of request

Request is a domain object! In JavaWeb, there are a total of four domain objects, among which ServletContext is a domain object, which only creates one ServletContext object in the entire application. Request is one of them, and request can share data in a request.

A request creates a request object, if multiple Servlets are experienced in a request, then multiple Servlets can use request to share data. We still do not know how many Servlets are experienced in a request.

The following are the domain methods of request:

(1)void setAttribute(String name, Object value):Used to store an object, which can also be called storing a domain attribute, for example: servletContext.setAttribute(“xxx”, “XXX”);, a domain attribute is stored in the request, the name of the domain attribute is xxx, and the value of the domain attribute is XXX. Please note that if this method is called multiple times and the same name is used, the previous value will be overwritten, which is the same as the characteristic of Map;

(2)Object getAttribute(String name):Used to obtain data from the request, before obtaining it, you need to store it first, for example: String value = (String)request.getAttribute(“xxx”);, to obtain the domain attribute named xxx;

(3)void removeAttribute(String name):Used to remove the domain attribute from the request, if the domain attribute specified by the parameter name does not exist, this method does nothing;

(4)Enumeration getAttributeNames():获取所有域属性的名称;

3、request传递参数

最为常见的客户端传递参数方式有两种:

(1)浏览器地址栏直接输入:一定是GET请求;

(2)超链接:一定是GET请求;

(3)表单:可以是GET,也可以是POST,这取决与

的method属性值;

GET请求和POST请求的区别:

(1)GET请求:

请求参数会在浏览器的地址栏中显示,所以不安全;

请求参数长度限制长度在1K之内;

GET请求没有请求体,无法通过request.setCharacterEncoding()来设置参数的编码;

(2)POST请求:

请求参数不会显示浏览器的地址栏,相对安全;

请求参数长度没有限制;

4、请求转发和请求包含(*****重点*****)

无论是请求转发还是请求包含,都表示由多个Servlet共同来处理一个请求。例如Servlet1来处理请求,然后Servlet1又转发给Servlet2来继续处理这个请求。

请求转发和请求包含
RequestDispatcher rd = request.getRequestDispatcher("/MyServlet");  使用request获取RequestDispatcher对象,方法的参数是被转发或包含的Servlet的Servlet路径

请求转发:rd.forward(request,response);
请求包含:rd.include(request,response);

有时一个请求需要多个Servlet协作才能完成,所以需要在一个Servlet跳到另一个Servlet!
    > 一个请求跨多个Servlet,需要使用转发和包含。
 > 请求转发:由下一个Servlet完成响应体!当前Servlet可以设置响应头!(留头不留体)            即当前Servlet设置的相应头有效,相应体无效。
    > 请求包含:由两个Servlet共同未完成响应体!(都留)                                                                     都有效。     
    Whether it is request forwarding or request inclusion, it is within the scope of a single request! Use the same request and response!  

Comparison between Request Forwarding and Request Inclusion:

(1) If request forwarding is used from AServlet to BServlet, then it is not allowed to output the response body in AServlet, that is, it can no longer use response.getWriter() and response.getOutputStream() to output to the client, this task should be completed by BServlet; if request inclusion is used, there is no such restriction;

(2) Although request forwarding cannot output the response body, it can still set the response headers, for example: response.setContentType(”text/html;charset=utf-8";

(3) Request inclusion is mostly used in JSP pages to complete the merging of multiple pages;

(4) Request forwarding is mostly used in Servlets, and the forwarding target is mostly JSP pages;

As shown in the figure:


Comparison of Request Forwarding and Redirection

(1) Request forwarding is one request, while redirection is two requests;

(2) After request forwarding, there will be no change in the browser address bar, while redirection will change, because redirection is two requests;

(3) The target of request forwarding can only be resources within this application, while the target of redirection can be other applications;

(4) The request forwarding method for AServlet and BServlet is the same, either both are GET or both are POST, because request forwarding is a request;

(5The second request of the redirection must be GET;

 That's all for this article, I hope it will be helpful to everyone's learning, and I also hope everyone will support the Yelling Tutorial more.

Statement: The content of this article is from the Internet, the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#w3Please report via email to codebox.com (replace # with @ when sending an email) and provide relevant evidence. Once verified, this site will immediately delete the infringing content.

You May Also Like