Learn more about Java basics


What is the Servlet

A Servlet is a special Java class that is a small Java program (that is, a server-side applet) that runs in a Web server. Servlets typically receive and respond to requests from Web clients over HTTP (Hypertext Transfer Protocol). This Java class must inherit HttpServlet. Each Servlet can respond to client requests, and servlets provide different methods for responding to client requests, such as doGet, doPost, doPut, etc

Relationship between Tomcat and servlets

Tomcat is a Web application server and is a Servlet/JSP container. Tomcat, as a Servlet container, is responsible for processing customer requests, passing them to servlets, and passing the Servlet’s responses back to the customer. Servlets are components that run on servers that support the Java language.

The most common use of servlets is to extend Java Web server functionality and provide a very secure, portable, and easy-to-use alternative to CGI. From the request and response in THE HTTP protocol, we know that the request sent by the browser is a request text, and the response received by the browser should also be a response text.

  1. Tomcat receives and parses the HTTP request text, and then encapsulates it into a Request object of HttpServletRequest type. All HTTP header data reads can be queried by calling the corresponding method of the Request object.
  2. Tomcat also requires the response information to be encapsulated as a response object of type HttpServletResponse. By setting the response property, you can control the output to the browser, and then hand the response to Tomcat. Tomcat sends it as response text to the browser.

The Java Servlet API is an interface between the Servlet container (Tomcat) and servlets. It defines serlvet methods and object classes that the Servlet container passes to servlets. The most important of these are ServletRequest and ServletResponse. So when we write a servlet, we need to implement the servlet interface and operate according to its specifications.

Servlet execution process

In the browser’s address bar: http://ip:port/appNames/servlet

1) Connect to the server through the browser and IP: port. 2) The browser generates a request packet (path appNames/servlet) to send the request to the server. 3) The server receives the request packet, analyzes the resource path of the request for precise positioning, searches the appName under the Webapps file for matching by the appName of the request, and obtains the servlet(mapping) in web.xml. 4) The server creates two objects: the first object: the request object, which implements the HttpServletRequest interface. The server will parse the data in the request packet and store it in this object. The advantage of this is that it is not necessary to understand the HTTP protocol, just to read the request. The second object, the response object, implements the HttpServletResponse interface. The function is to store the results of the servlet processing to this object, and then the server generates a response packet based on the data of this object. 5) When servlet executes servlet() method, it can obtain request data through Request or store the processing result in Response. The server then works directly with the response object to generate a response packet to the browser. 6) The browser parses the response packet returned by the server and generates the response result.

  

Servlet access process: XML Http request — – > web. — — — — — — — — > url – the pattern — — — — — > servlet – name — — — — — > servlet – class — — — — — > QuickStratServlet (the corresponding class file)

The life cycle of a Servlet

The Servlet life cycle can be divided into five steps

  1. Load the Servlet. When Tomcat first accesses a Servlet, Tomcat is responsible for creating instances of the Servlet
  2. Initialization. When the Servlet is instantiated, Tomcat calls the init() method to initialize the object
  3. Processing services. When the browser accesses the Servlet, the Servlet calls the service() method to handle the request
  4. Destroyed. The destroy() method is automatically called when Tomcat is shut down or when a Servlet is detected to be removed from Tomcat, causing the instance to release its resources. A Servlet that has not been used for a long time will also be automatically destroyed by Tomcat
  5. Unloading. After the Servlet calls destroy(), it waits for garbage collection. If the Servlet needs to be used again, the init() method is called again for initialization.

To summarize: Service () is called whenever the Servlet is accessed. Init () is only called the first time the Servlet is accessed. Destroy () is only called when Tomcat is turned off.

The Servlet configuration

Using configuration files
  1. Write a Servlet class
public class MyServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doPost(req, resp); } @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.service(req, resp); }}Copy the code
  1. Configure the Servlet in web.xml

    Use springboot # # # # # #

  2. Write a servlet class
  3. Start the class configuration in SpringBoot
@SpringBootApplication
public class ServletApp {

    @Bean
    public ServletRegistrationBean MyServlet() {return new ServletRegistrationBean(new MyServlet(),"/myserv/*"); } public static void main(String[] args){ SpringApplication.run(ServletApp.class, args); }}Copy the code

# Servlet details

  • Url matching order of servlets

When a request is sent to the servlet container, the container will first requested url minus the path of the current application context as the servlet mapping urls, I visit http://localhost/hiway/user/aaa.html, for example, my application context is hiway, The container removes http://localhost/hiway and uses the rest of /user/aaa.html for servlet mapping matches. The mapping process is sequential, and when one servlet matches successfully, the rest of the servlets are ignored. The matching rules and order are as follows:

  1. Exact path matching. Example: For example, if the url-pattern of a servletA is /test and the url-pattern of a servletB is /*, if the URL I visited is http://localhost/test, the container will match the exact path first. If /test is exactly matched by servletA, the servletA is called and the other servlets are ignored.
  2. Longest path matching. Example: The url-pattern of a servletA is /test/The url-pattern of the servletB is /test/a/When accessing http://localhost/test/a, the container will select the servlet with the longest path to match, which is servletB in this case.
  3. Extend matching. If the last section of the URL contains an extension, the container will select the appropriate servlet based on the extension. Example: url-pattern for servletA: *.action
  4. Finally, if none of the previous three rules finds a servlet, the container selects the requested resource based on the URL. If the application defines a default servlet, the container throws the request to the default servlet
  • Are servlets singletons

In the Servlet specification, Servlet singletons and multiinstances are defined as follows:

The Deployment Descriptor “, controls how the servlet container provides instances of the servlet.For a servlet not hosted in a distributed environment (the default), the servlet container must use only one instance per servlet declaration. However, for a servlet implementing the SingleThreadModel interface, the servlet container may instantiate multiple instances to handle a heavy request load and serialize requests to a particular instance.

As mentioned in the specification above, if a Servlet is not deployed in a distributed environment, typically each Servlet declared in web.xml corresponds to only one instance. If a Servlet implements the SingleThreadModel interface, multiple instances will be initialized. The default 20

So I understand that the Servlet is not a singleton, but that the container allows it to be instantiated only once, which is a singleton effect

  • ##### How do I develop thread-safe servlets
  1. Implement the SingleThreadModel interface
  2. The operation of shared data using synchronized
  3. Avoid using instance variables

Testing the above three approaches shows that it is possible to design thread-safe Servlet programs using all of them. However, if a Servlet implements the SingleThreadModel interface, the Servlet engine will create a separate Servlet instance for each new request, which incurs significant system overhead. SingleThreadModel is no longer advocated in Servlet2.4; Also, using synchronization in your program to protect the shared data that you want to use can significantly degrade system performance. This is because a block of synchronized code can only be executed by one thread at a time, making it less capable of processing customer requests simultaneously, and many customers are blocked. In addition, to ensure the consistency of the main memory and the data in the thread’s working memory, the cache must be refreshed frequently, which will greatly affect the performance of the system. So avoid or minimize synchronous code in servlets in real development; ** Avoiding instance variables in serlets is your best bet for Servlet thread safety. ** As you can also see from the Java memory model, temporary variables in methods are allocated space on the stack, and each thread has its own private stack space, so they do not affect thread safety

Learning materials: lixh1986.iteye.com/blog/235569…

  • Servlet < load – on – startup >

In the servlet configuration,

<load-on-startup>1</load-on-startup>
Copy the code

Flags whether the container loads the servlet at startup. A value of 0 or greater means that the container loads the servlet when the application starts. When it is a negative number or not specified, it indicates that the container is loaded when the servlet is selected. The smaller the positive value, the higher the priority for starting the servlet. When load-on-startup is configured, servlets are loaded immediately after startup, but only by calling the init() method of the servlet to initialize the resources associated with the servlet. After successful initialization, the servlet can respond to Web requests. If load-on-startup is not configured, the container checks whether the servlet is initialized when responding to a Web request for the first time. If the servlet is not initialized, init() is invoked to initialize the servlet first. After the initialization succeeds, the container responds to the request.

  • By default the default Servlet

The url-pattern can be configured with a slash to indicate that the servlet is the default servlet. What is the default servlet? When you access a resource address and all servlets do not match, the default servlet assignment is handled. In fact, servlets are responsible for the response of all resources in a Web application, including static resources (HTML pages). (There are configured default servlets that cannot access static resources.)

Learning materials: www.cnblogs.com/zhangyinhua…