Servlet | Response object details


1. Write in front

To learn the Responseobject, you need to understand HTTPthe format of the response message of the protocol. If you have not understood this part of the knowledge, please click on these words to learn the HTTP protocol first

Click on these words to learn more about the Requestobject


2. Overview of Response

RespoinseThe function of is: setting response messages, which can be divided into the following three categories:

  • Set the response line:
    • format:HTTP/1.1 200 OK
    • Set status code:setStatus(int sc)
  • Set the response header:setHeader(String name,String value)
  • Steps to set the response body :
    • Get the output stream:
      • Character output stream:PrintWriter getWriter()
      • Byte output stream:ServletOutputStream getOutputStream()
    • Use the output stream to output data to the client browser

The following uses four case study Responseobjects


3. Redirect

Draw a picture to understand what redirection is:
Insert picture description here
Now the browser wants to access the A resource, but the A resource finds that the B resource is needed to complete the browser's requirements, so the A resource tells the browser: you need to access the B resource, so the browser just Go to visit B resource, redirection is successful.

A needs to tell the browser two pieces of information, the status code 302and the path of B. Let's demonstrate the redirection operation:

Requirements: ResponseServlet01Redirect to ResponseServlet02, Servletprint 1被访问了and2被访问了

In IDEA, create a new module, then create a new package, and create two more Servlet, namely ResponseServlet01and ResponseServlet02
Insert picture description here
In ResponseServlet01, print a sentence:

System.out.println("responseServlet01被访问了...");

Then set the status code as 302:

response.setStatus(302);

Finally set the response body location:

response.setHeader("location","/ResponseDemo/responseServlet02");

Similarly, ResponseServlet02print in:

System.out.println("responseServlet02被访问了...");

ResponseServlet01Code display:

package com.wzq.response;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/responseServlet01")
public class ResponseServlet01 extends HttpServlet {
    
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        //打印一句话
        System.out.println("responseServlet01被访问了...");

        //1. 设置状态码为302
        response.setStatus(302);
        //2. 设置响应头location
        response.setHeader("location","/ResponseDemo/responseServlet02");
    }

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

Run it: the
Insert picture description here
page redirection is successful!

But we found that the status code must be set for every redirection. Can we omit this step?

Answer: Yes, the Responseobject provides a redirection method:, sendRedirect(String path)just fill in a redirection path, so the two sentences above can be replaced with:

response.sendRedirect("/ResponseDemo/responseServlet02");

The following table shows 重定向and 请求转发the difference between :

Redirect Request forwarding
By the Responsecall By the Requestcall
The address bar changes The path of the forwarding address bar remains unchanged
Can access resources on other sites Can only access resources under the current server
Two requests, Requestshared data cannot be used One request, you can use Requestshared data

4. The server outputs character data to the browser

step:

  1. Set encoding
  2. Get character output stream
  3. Output Data

Create a new class, the code is as follows:

package com.wzq.response;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/responseServlet03")
public class ResponseServlet03 extends HttpServlet {
    
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        //1. 设置编码
        response.setContentType("text/html;charset=utf-8");
        //2. 获取字符输出流
        PrintWriter pw = response.getWriter();
        //3. 输出数据
        pw.write("<h1>你好,Response</h1>");
    }

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

Output result:
Insert picture description here


5. The server outputs byte data to the browser

Generally we use 字节流resources such as pictures to be output to the browser, but now we only demonstrate outputting some words

step:

  1. Get byte output stream
  2. Output Data

Create a new class, the code is as follows:

package com.wzq.response;

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.IOException;
import java.io.PrintWriter;

@WebServlet("/responseServlet04")
public class ResponseServlet04 extends HttpServlet {
    
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        //1. 获取字节输出流
        ServletOutputStream sos = response.getOutputStream();
        //2. 输出数据
        sos.write("你好".getBytes());
    }

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

Output result:
Insert picture description here

Guess you like

Origin blog.csdn.net/lesileqin/article/details/112534406