Basic principle and mapping of Servlet

3,Servlet

Servlet is an open source technology for developing dynamic Web launched by Sun company. The servlet runs in the server and is called by the server. It is a Java program running in the server. Its function is to receive the request of the client and respond to the data to the client. It is the middle layer between the request of the browser and the database on the server.

sun company provides a Servlet interface, and the program that implements this interface is Servlet.

Servlet, Filter and Listener are the three major components of Java Web.

  • The client sends a request to the server
  • The server starts and calls the Servlet, which generates the response content according to the client request and transmits it to the server
  • The server returns the response to the client

Servlet project naming specification:

1,Package name specification: com.***.servlet
2,Class name specification:****Servlet
3,web.xml In the file servlet-name The configuration and class name should be consistent
<!-- pom rely on-->
<dependency>
     <groupId>javax.servlet</groupId>
     <artifactId>javax.servlet-api</artifactId>
     <version>4.0.1</version>
</dependency>
<dependency>
    <groupId>javax.servlet.jsp</groupId>
    <artifactId>javax.servlet.jsp-api</artifactId>
    <version>2.3.3</version>
</dependency>
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>

3.1 implementation method

3.1.1 Servlet interface

Javax. Servlet The servlet interface contains a service method, which will be called by the Tomcat server

public class DemoServlet implements Servlet {
	//Initialization method of servlet
    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
        
    }

    @Override
    public ServletConfig getServletConfig() {
        return null;
    }
	//Tomcat will find the service method for operation, mainly for request and response
    @Override
    public void service(ServletRequest request,ServletResponse response) throws ServletException,IOException {
		//Set code
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        //Get requested data
        
        //Response data
        PrintWriter out = response.getWriter();		//Get the output stream
        out.print("");
    }

    @Override
    public String getServletInfo() {
        return null;
    }
	//Destruction method
    @Override
    public void destroy() {

    }
}

3.1.2 abstract classes

The GenericServlet abstract class implements the four methods of the Servlet interface, so after inheriting the GenericServlet, you only need to rewrite the service method. Other operations are similar to directly implementing the serlvet interface

package com.cy.demo.servlet

import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;

public class Demo2Servlet extends GenericServlet {
    //The other four method abstract classes GenericServlet have been implemented. You only need to rewrite the service
    @Override
    public void service(ServletRequest request,ServletResponse response) throws ServletException,IOException {

    }
}

3.1.3 HttpServlet

In normal use, the maximum number is inherited from javax Servlet Http. HttpServlet to implement the servlet program. In this way, the five methods of servlet are rewritten, and doGet and doPost methods are added. There are no abstract methods inside. HttpServlet internally analyzes the transmission protocol of Http and provides more usage methods.

Automatically create Servlet classes:

Inheritance relationship: created class inheritance → HttpServlet inheritance → GenericServlet implementation → Servlet interface

The access specification is defined by the Servlet interface. GenericServlet implements the Servlet interface, implements the method null, and makes some use methods for the ServletConfig class. HttpServlet inherits GenericServlet, implements the service method, distributes and processes requests, and adds post and get methods. We just need to re doGet and doPost with the requirements.

//Inherit HttpServlet class
public class Demo3Servlet extends HttpServlet {
    //Override doGet and doPost methods
   @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //Set code
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf=8");
        //Get the flow of the response
         PrintWriter out = response.getWriter();
         out.print("Hello Servlet");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);  //By calling doPost, you can use two methods without distinguishing between post and get
    }
}

3.2 mapping path

Java needs to configure the mapping path to find the corresponding Servlet. In Java, there are two configurations to obtain the mapping path, which are through XML files and annotations.

3.2.1 XML file

Java needs to configure the mapped path in the XML file to find the corresponding servlet and call it.

<?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">
    	<!-- Two servlet-name One must be found, each one servlet Class will generate a -->
   		<!-- servlet The corresponding will be found according to the configuration servlet class -->
		<servlet>
				<servlet-name>Consistent with class name</servlet-name>	<!--3,According to the same servlet-name Find here-->
				<servlet-class>com.****.Class name</servlet-class>	  <!--4,Find the corresponding class according to the path-->
		</servlet>
		<servlet-mapping>
				<servlet-name>Consistent with class name</servlet-name>	<!--2,according to url-pattern Find here-->
				<url-pattern>/Consistent with class name</url-pattern>	<!--1,According to the path entered by the browser, the server finds here-->
		</servlet-mapping>
   		 <!--Mapping paths, each servlet You can specify multiple mapping paths,
			/*Is a wildcard to indicate that all paths access this 
			*.yu: Custom suffix,*Represents any character and cannot be preceded by anything else
		-->
</web-app>

Mapping mapping priority: specified mapping path > Default wildcard

3.2.2 notes

You can find the corresponding Servlet by directly adding the annotation of @ WebServlet on the Servlet class

By searching urlPatterns through the request path, you can find the corresponding name, so as to find the servlet class that matches the name

@WebServlet(name = "Demo2Servlet",urlPatterns = "/Demo2Servlet")
public class Demo2Servlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf=8");
        //Get the corresponding flow
        PrintWriter out = response.getWriter();
        out.print("Hello Servlet2");
    }

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

3.3 principle

3.4 life cycle

When the browser accesses, the servlet is executed in the following order: 1 and 2 will be executed when the browser accesses for the first time, and subsequent accesses will not be executed. 3. It will be executed once every page access, and 4. Destroy the object when the server is closed.

1. Execute the construction method to create an object: it will be executed during the first access after the server is started, and will not be executed later

2. Execute init method for initialization: it is executed during the first access after the server is started, and will not be executed later

3. Execute the service method to operate the data: it will be executed every time

4. Call the destroy method to destroy the object: execute when the server is shut down

Tags: Java Web Development

Posted by tooNight on Sun, 17 Apr 2022 11:31:42 +0930