Servlet learning diary 7 -- forwarding and redirection of Servlet

Posted by bigfunkychief on Sun, 13 Feb 2022 03:57:08 +0100

catalogue

1, Supplement to the previous content

2, Several problems of servlet at present

3, Problems after separating two servlets

4, Forward

4.1 function

4.2 page Jump

4.3 operation and code

4.4 data transmission

4.5 forwarding features

5, Redirect

5.1 function

5.2 page Jump

5.3 code implementation

5.4 data transmission

5.5 codes

5.6 redirection features

5.7 forwarding and redirection summary

1, Supplement to the previous content

Write the Java code as follows, and use the get request to see the effect of the display

package com.ha.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;


public class RegisterServlet extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1. Obtain the data requested by the user
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        // [set response header]
        // setStatus: sets the status code in the status line
        // resp.setStatus(200);
        // setContentType: set the content type in the response header and set the data format of the response client
        resp.setContentType("text/html");  // Equivalent to: resp setHeader("Content-Type", "text/html");
        // setContentLength: set the data length of the response client. Generally, it is not necessary to set it. The client will read the data (this is generally used for verification)
        // resp.setContentLength(1024);  //  Equivalent to: resp setHeader("Content-Length", "1024");
        // setHeader: set some other information
        resp.setHeader("Connection", "keep-alive");
        
        // [set response body]
        // setCharacterEncoding: sets the data encoding format of the response client
        resp.setCharacterEncoding("utf-8");

        // Get the output stream through the resp object
        // Byte stream (if you want to respond to file data to the client, you need to use byte stream)
        // ServletOutputStream outputStream = resp.getOutputStream();
        // Character stream (use character stream if you want to respond to file data HTML document)
        PrintWriter printWriter = resp.getWriter();
        // The data written out through the stream will be transmitted to the client browser in the form of response text. If the browser can recognize the data, it will be displayed directly
        printWriter.println("<!DOCTYPE html>");
        printWriter.println("<html>");
        printWriter.println("<head>");
        printWriter.println("<meta chaeset='utf-8'>");
        printWriter.println("<title>Login user name and password</title>");
        printWriter.println("</head>");
        printWriter.println("<body>");
        printWriter.println("<label>user name:" + username + "<label>");
        printWriter.println("<label>password:" + password + "<label>");
        printWriter.println("</body>");
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

This is the response header:

2, Several problems of servlet at present

1. In the above Java program, business logic work such as judgment may be done, which is also used to print and display the effect.

2. When there is a better page to display later, the Java code will be modified again.

This is to call the business logic and display the result page in the same Servlet, which will cause design problems: (1) it does not conform to the principle of single function and perform their respective duties; (2) It is not conducive to subsequent maintenance

Business logic should be separated from displaying results

3, Problems after separating two servlets

Question: after the business logic is separated from the display result, how to jump to the Servlet that displays the result?

How can the data results obtained by the business logic be transferred to the Servlet that displays the results?

4, Forward

4.1 function

The role of forwarding is on the server side. It sends the request to other resources on the server to jointly complete the processing of a request.

4.2 page Jump

In the Servlet calling business logic, write the following code:

request.getRequestDispatcher("/ target URL pattern") forward(request, response);

4.3 operation and code

Create a new Java file

package com.ha.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;


public class AServlet extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/rs").forward(req, resp);
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

Add profile content

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
  version="3.1"
  metadata-complete="true">

  <servlet>
    <servlet-name>rs</servlet-name>
    <servlet-class>com.ha.servlet.RegisterServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>rs</servlet-name>
    <url-pattern>/rs</url-pattern>
  </servlet-mapping>


  <servlet>
    <servlet-name>a</servlet-name>
    <servlet-class>com.ha.servlet.AServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>a</servlet-name>
    <url-pattern>/a</url-pattern>
  </servlet-mapping>

</web-app>

Access / a

Completed the page from aservlet Java jump to registerservlet java

In the eyes of the client, a is always accessed. When using forward jump, you jump inside the server without changing the address bar. It belongs to the same request.

4.4 data transmission

1. forward indicates that a request is a jump within the server and can share data in the same - request scope

(1) Request scope: it has the space to store data. The scope is that a request is valid (a request can be forwarded multiple times)

The data can be stored in the request and obtained at any location in the process of a request

Any data can be passed (basic data type, object, array, collection, etc.)

(2) Save data: request setAttribute(key, value);

Stored in the request scope as a key value pair. Key is of String type and value is of 0bject type

(3) Get data: request gettribute(key);

Access the value of 0bject type through the key of String type

2. Complete process

package com.ha.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;


public class AServlet extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setAttribute("username", "Juan ");
        req.setAttribute("password", "123456");
        req.getRequestDispatcher("/rs").forward(req, resp);
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

package com.ha.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;


public class RegisterServlet extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = (String)req.getAttribute("username");
        String password = (String)req.getAttribute("password");

        resp.setContentType("text/html");
        resp.setHeader("Connection", "keep-alive");
        resp.setCharacterEncoding("utf-8");
        
        PrintWriter printWriter = resp.getWriter();
        printWriter.println("<!DOCTYPE html>");
        printWriter.println("<html>");
        printWriter.println("<head>");
        printWriter.println("<meta chaeset='utf-8'>");
        printWriter.println("<title>Login user name and password</title>");
        printWriter.println("</head>");
        printWriter.println("<body>");
        printWriter.println("<label>user name:" + username + "<label>");
        printWriter.println("<label>password:" + password + "<label>");
        printWriter.println("</body>");
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
  version="3.1"
  metadata-complete="true">

  <servlet>
    <servlet-name>rs</servlet-name>
    <servlet-class>com.ha.servlet.RegisterServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>rs</servlet-name>
    <url-pattern>/rs</url-pattern>
  </servlet-mapping>


  <servlet>
    <servlet-name>a</servlet-name>
    <servlet-class>com.ha.servlet.AServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>a</servlet-name>
    <url-pattern>/a</url-pattern>
  </servlet-mapping>

</web-app>

Operation results:

4.5 forwarding features

Forwarding is server behavior

Forwarding is that the browser only makes an access request once

Browser forwarding address unchanged

The information transmitted between two jumps will not be lost, so the data can be transmitted through request

Forwarding can only forward requests to components in the same Web application

5, Redirect

5.1 function

Redirection works on the client. After the client sends the request to the server, the server responds to the client with a new request address, and the client resends the new request.

5.2 page Jump

In the Servlet that calls the business logic, write the following code

response.sendRedirect("destination URL");

URL: uniform resource identifier, which is used to locate a resource in the server and the path of the resource in the web project (/ project/source)

5.3 code implementation

 

Access / a switch to / rs

5.4 data transmission

When sendRedirect jumps, the address bar changes, representing the request sent by the client again. Belong to two requests

The response has no scope, and the data in the two request requests cannot be shared

Transfer data: transfer data through the splicing of UR ("/ WebProject/b?usemame=tom");

Get data: request getParameter("usemame");  

5.5 codes

5.6 redirection features

Redirection is client behavior.

Redirection is when the browser makes at least two access requests.

Redirect browser address change.

Redirect the information transmitted between two jumps will be lost (request range).

Redirection can point to any resource, including other resources in the current application, resources in other applications on the same site, and resources in other sites.

5.7 forwarding and redirection summary

When two servlets need to transfer data, select forward forwarding. sendRedirect is not recommended for delivery

Topics: Java Operation & Maintenance Tomcat servlet server