[JavaWeb] Servlet Technology of response client

Posted by samsbox on Sat, 16 Oct 2021 08:53:59 +0200

reference material:
Basic course of Java Web Development -- edited by Li Jun (main)

1. Introduction to Servlet

Definition of Servlet: Servlet is a Java application running on the Web server. It is a technology provided by SUN company for developing dynamic Web resources.

The role of Servlet:

  • Collect user input from the web form < form >
  • Manipulate data by interacting with the database
  • Create web pages dynamically

The essence of Servlet: Java classes written in accordance with the specification have no main method, and the creation, use and destruction are managed by Servlet container

As shown in the figure above, the HTTP server that sends HTTP requests to the Servlet program for processing is usually called a Servlet container. Common containers include Tomcat, Jetty, WebLogic, JBoss, etc

2. Construction of development environment

2.1 installing and configuring Tomcat

  • Windows 10 operating system
  • JDK8 -- software environment for supporting Java language development
  • Tomcat9 -- a free and open source Web application server based on Java language, that is, Servlet container
  • IDEA 2021 Professional Edition - an integrated environment for Java language development, which can build Java Web projects (except Community Edition)

Here we mainly introduce the installation and configuration of Tomcat

Tomact official website https://tomcat.apache.org/

Take [Tomcat 9.0.52 Released] as an example

Select executable files for easy installation


Directory structure after installation


Configure the environment variable and create a new one in the system variable column to represent the directories of JDK and Tomcat

Add the bin folders of JDK and Tomcat to the PATH variable in the system variable

At this point, Tomcat configuration is completed, and the next step is the creation of the web project.

2.2 IDEA creating Web project

To create a Java enterprise project for the first time, you need to create a new Tomcat server


Locate the previously installed Tomcat directory

If JDK is not displayed below, click Add and select the corresponding JDK directory


After clicking next, just select Servlet

Current project structure

3. Hello Servlet

3.1 writing test classes

HelloServlet.java

package com.example.project;

import java.io.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;

@WebServlet(name = "helloServlet", value = "/hello")
public class HelloServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("Hello,Servlet!");
    }

}

3.2 write jump page

index.jsp

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <title>JSP - Hello World</title>
</head>
<body>
<h1><%= "Hello World!" %>
</h1>
<br/>
<a href="hello">Hello Servlet</a>
</body>
</html>


Visit localhost: 8080 / Project_ war_ Expanded page

Page after clicking the hyperlink

3.3 modifying Tomcat configuration

Through the test just now, it can be found that there is the project name project at the end of the accessed URL_ war_ Expanded, so how to omit this name to make the test URL look more concise? Next, you need to configure Tomcat

First, set up automatic update classes and resources, so that the server can refresh automatically when modifying JSP pages

Then click deploy and slide the scroll bar down

Select the first blank

After selection, click Apply and OK successively
After starting Tomcat again, the effect is as follows

4. Two methods of servlet identification

For the test of Part 3, do you wonder why the web server can execute the code of java class after clicking the hyperlink?
Before we get to know this, let's look at the key sentence of the front page: < a href = "hello" > Hello servlet</a>
When we click the hyperlink on the page, the address URL becomes localhost:8080/hello, and you can also access this address directly.

There is such a sentence in the helloServlet class: @ WebServlet(name = "helloServlet", value = "/hello")
In Java, the @ symbol is called annotation. Its function is to identify the current class as a Servlet class, such as Tomcat
The container can access the class.

Note: the Servlet ID cannot be repeated, otherwise an error will be reported when deploying the project

4.1 annotation method

There are two ways to use annotations to identify Servlet classes

  • @WebServlet(name = "ServletClassName", value = "url")
  • @WebServlet(name = "ServletClassName", urlPattern="url")

The url is the address to be accessed when calling the front-end web page, such as @ WebServlet(name = "helloServlet", value = "/ hello")

4.2 XML configuration file mode

There is usually a web.xml configuration file in a web project

The annotation began to appear after JDK1.5 and Servlet 3.0. Before that, the Servlet declaration in the Java Web project is usually through configuring the file, such as the hello class before declaration. The specific code is as follows:

<?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_4_0.xsd"
         version="4.0">
    <servlet>
        <servlet-name>hello</servlet-name>
        <servlet-class>com.example.project.HelloServlet</servlet-class>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>
</web-app>

XML configuration Servlet description

  • < Servlet > is used to register servlets, and the Servlet name and full class name need to be specified
  • < Servlet mapping > is used to map the virtual path accessed by the Servlet
  • < servlet name > must exist in a < Serlvet >
  • < URL parrtern > is used to specify the virtual path to access the Servlet. Starting with "/" indicates the root directory of the Web application

5. Servlet life cycle

Like any other object in Java, Servlet has a life cycle, that is, the process from object creation to destruction.

5.1 initialization phase

You can rewrite the init() method in the Servlet class to write the initialization code of the Servlet class

When the Servlet container (Tomcat) receives an HTTP request from the client to access a Servlet, first check whether the Servlet object already exists in memory. If so, use it directly. Otherwise, create a Servlet instance object.

Call the init() method to initialize the Servlet, which is only executed once in the whole life cycle.

There are two rewriting methods in code implementation:

  • public void init(ServletConfig config) this method uses the config object of the Servlet to read some configurations about the Servlet, including XML configuration and annotation configuration, which will be described in detail later
  • public void init() only does initialization. The specific work is written by the developer
package com.example.project;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import javax.servlet.annotation.*;

@WebServlet(name = "helloServlet", value = "/hello")
public class HelloServlet extends HttpServlet {
    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
    }

    @Override
    public void init() throws ServletException {
        super.init();
    }
}

5.2 operation phase

The Servlet container (Tomcat) encapsulates the HTTP request and response into Java objects and passes them as parameters to the service() method. The method will determine the doGet() or doPost() method to be called according to the type of HTTP request to process the business logic.

The Servlet container will call the service() method once for each access request. However, in actual development, it generally only focuses on the implementation of specific services in doGet() and doPost() methods.

5.3 destruction stage

When the server is shut down or the Web application is removed from the Servlet container, the Servlet object is destroyed.

Before destruction, the container calls the destroy() method so that the Servlet object releases the occupied resources.

6. Common objects of Servlet

Servlet is implemented by inheriting HttpServlet class. As a Java class, it contains some common objects:

Object namedescribe
ServletConfigInitialize Servlet
ServletContextShare information of multiple servlets
HttpServletRequestHTTP request information
HttpServletResponseHTTP response information

6.1 ServletConfig object

6.1.1 method description

This object is mainly used to store some configuration information about servlets. Common methods include:

Method nameeffect
String getInitParameter(String name)Return the corresponding parameter according to the initialization parameter name
Enumeration getInitParameterNames()Returns all initialization parameter names
ServletContext getServletContext()Returns a ServletContext object representing the current Web application
String getServletNames()Returns the name of the Servlet

6.1.2 testing

  • Annotation method
package com.example.project;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import javax.servlet.annotation.*;

@WebServlet(name = "helloServlet",
        value = "/hello",
        initParams = {
        @WebInitParam(name = "Encoding", value = "UTF-8"),
                @WebInitParam(name = "myName", value = "lazycat")
        })
public class HelloServlet extends HttpServlet {
    @Override
    public void init(ServletConfig config) throws ServletException {
        System.out.println(config.getInitParameter("Encoding"));
        System.out.println("Hello " + config.getInitParameter("myName"));
    }
}

design sketch:

  • XML mode

web.xml

<?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_4_0.xsd"
         version="4.0">
        <servlet>
            <servlet-name>hello</servlet-name>
            <servlet-class>com.example.project.HelloServlet</servlet-class>
            <init-param>
                <param-name>Encoding</param-name>
                <param-value>UTF-8</param-value>
            </init-param>
            
            <init-param>
                <param-name>myName</param-name>
                <param-value>lazycat</param-value>
            </init-param>
        </servlet>
    
        <servlet-mapping>
            <servlet-name>hello</servlet-name>
            <url-pattern>/hello</url-pattern>
        </servlet-mapping>
</web-app>

In this way, the Servlet class is simplified to:
HelloServlet.java

package com.example.project;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.*;

public class HelloServlet extends HttpServlet {
    @Override
    public void init(ServletConfig config) throws ServletException {
        System.out.println(config.getInitParameter("Encoding"));
        System.out.println("Hello " + config.getInitParameter("myName"));
    }
}

Through comparison, it is found that the annotation looks concise.

6.2 ServletContext object

When the Servlet container (Tomcat) is started, a unique ServletContext object will be created for each Web application to represent the current Web application.

This object not only encapsulates all the information of the current Web application, but also realizes the data sharing among multiple servlets.

Its main functions are: obtaining Web initialization parameters and realizing data sharing of multiple servlets

Common methods include:

Method nameeffect
Enumeration getAtrributeNames()Returns an iteratable object for all domain attribute names of all ServletContext
Object getAttribute(String name)Return the corresponding attribute value according to the parameter attribute name
void removeAttribute(String name)Delete the corresponding domain attribute according to the parameter attribute name
void setAttribute(String name, Object obj)Set domain parameters, where name is the attribute name and obj is the attribute value

6.2.1 get initialization parameters of Web application

In the web.xml file, in addition to configuring the initialization information of the Servlet, you can also configure the initialization information of the whole Web application

    <context-param>
        <param-name>appName</param-name>
        <param-value>javaweb</param-value>
    </context-param>
    
    <context-param>
        <param-name>appAddress</param-name>
        <param-value>myapp</param-value>
    </context-param>

< context param > is located in < web app >

Get the values of all initialization parameters in the Servlet class. Take the doGet method as an example:

ServletContext context = this.getServletContext();
Enumeration<String> names = context.getInitParameterNames();
while(names.hasMoreElements(){
	String name = names.nextElement();
	String value = context.getInitParameter(name);
	System.out.println(name + "," + value);
}

6.2.2 realize data sharing of multiple servlets

The following two Servlet classes take the doGet method as an example
servlet1.java

this.getServletContext().setAttribute("data", "test");

servlet2.java

ServletContext sc = this.getServletContext();
System.out.println(sc.getAttribute("data"));

6.3 HttpServletRequest object

This object is the first parameter of the doGet and doPost methods.

HTTP request message is divided into request message header and request message body.

6.3.1 get request message header

Relevant methods:

Method nameeffect
String getMethod()GET HTTP request method (such as GET, POST, etc.)
String getRequestURI()Get the resource name part of the URL request, that is, the part before the parameter after the host and port number of the URL
String getContextPath()Get the parameter part of the URL request, that is, all the contents after the middle number (?) of the URL
String getServletPath()Gets the path of the Web application in the URL, starting with "/"
Enumeration getHeaderNames()Gets the names of all request headers
String getHeader(String name)Gets the value of a header field with a specified name
String getCharcterEncoding()Gets the character set encoding of the body part of the request message

6.3.2 get request message body

Relevant methods:

Method nameeffect
String getParameter(String name)Gets the parameter value of a specified name. If it does not exist, it returns null
String[] getParameterValues(String name)The Http request message can have parameters with the same name (such as the check box of the form) and return all corresponding parameter values

6.3.3 resolve garbled code & request forwarding Servlet delivery

Solve garbled Code:

  • doPost method request.setCharacterEncoding("utf-8");
  • doGet method
    String data = req.getParameter("data")
    data = new String(data.getBytes("iso-8859-1"), "utf-8");

Request forwarding:
In a Servlet, after a Web resource receives a client request, if you want the Servlet to process the request or forward the requested data to the page for display, you can use the forward() method of the requestdispatcher object.

The ServletRequest interface defines the getRequestDispatcher(String path) method

Function: returns the RequestDispatcher object that encapsulates the resources specified by a path, where the path must start with "/", indicating the root directory of the current Web application

Note: the contents of the WEB-INF directory are visible to the requestdispatcher object

Method nameeffect
forward(ServletRequest request, ServletResponse responsePass from one Servlet to another Web resource. This method must be called before the response is submitted to the client

Example: servlet1 request is passed to servlet2 (take doGet method as an example)
servlet1.java

request.setAttribute("name", "lazycat");
request.getRequestDispathcer("/servlet2").forward(request, response);

servlet2.java

String name = (String)request.getAttribute("name");

6.3.4 five characteristics of request forwarding

  • There is no change in the browser address bar. Request forwarding belongs to the internal behavior of the server, and the client cannot know the process
  • No matter how many times the server-side request is forwarded, it belongs to one request for the client.
  • The data of the request domain object is shared between the forwarded servlets
  • It can be forwarded to the page file under the WEB-INF directory
  • You cannot access resources outside the project. This process can only occur between different Web resources of the same project

6.4 HttpServletResponse object

The HTTP response message is divided into three parts: status line, response header and message body

6.4.1 common methods for setting response header fields

Method nameeffect
void setHeader(String name, String value)Set the HTTP response header field
void setContentLength(int len)Set the size of the entity content of the response message, in bytes (B)
void setContextType(String type)Set the MIME type of Servlet output content. For example, if the content sent to the client is PDF document data, it is set to "application/pdf"; if it is text, it is "text/html;charset=UTF-8"
void setCharacterEncoding(String charset)Sets the character encoding used for the output content

6.4.2 method of response object output stream

Method nameeffect
getOutputStream()Get byte output stream object, which can directly output binary data in byte array
getWriter()Gets the byte output stream object of type PrintWriter, which can directly output character text content

6.4.3 File Download & text output

File download can be realized through this object. Take the doGet method to download PDF files as an example (PDF is in the same level directory of index.jsp):

response.setContextType("application/pdf");
response.setHeader("Context-Disposition", "attachment;fileName="+"save.pdf");
String path = this.getServletContext().getRealPath("/");
File file = new File(path + "test.pdf");
ServletOutputStream out;
try{
	FileInputStream inputStream = new FileInputStream(file);
	out = response.getOutputStream();
	int b = 0;
	byte[] buffer = new byte[512];
	while((b = inputStream.read(buffer)) != -1){
		out.wirte(buffer, 0, b);
	}
	inputStream.close();
	out.close();
	out.flush();	// Force flush buffer
} catch(IOException e){
	e.printStackTrace();
}

Text output

String data = "test print";
PrintWriter out = response.getWriter();
out.write(data);

6.4.4 resolving garbled code & request redirection

Solve garbled Code:
Mode 1:
response.setCharacterEncoding("UTF-8");
response.setHeader("Context-type", "text/html;charset = utf-8");

Mode 2:
response.setContextType("text/html;charset="utf-8")

Request redirection: after receiving the request from the client, the Web server may not be able to access the Wweb resource pointed to by the URL of the current request for some reasons, or the server reassigns a new resource path according to business requirements to make the client resend the request

However, sendRedirect(String location) throws IOException is used to redirect requests

location is used to specify the URL address (relative or absolute address) of the resend request

The schematic diagram is as follows:

6.4.5 five features of request redirection

  • The browser address bar will change, the request redirection will tell the client the URL address of the browser relocation, and the browser will resend the request according to the address
  • The client sent two requests. After the client requests resources for the first time, it resends the second request according to the URL path returned by sendRedirect() method
  • Data in the request domain object is not shared. The data requested twice cannot be shared
  • Unable to access resources under WEB-INF
  • You can access resources other than the current project

Topics: Java Tomcat http