(turn) Javaweb learning servlet (ii)----servlet life cycle, inheritance structure, modifying servlet templates

Source: Internet
Author: User
Tags tomcat server

Statement

Welcome reprint, but please keep the original source of the article →_→

Article Source: http://www.cnblogs.com/smyhvae/p/4140466.html

First, HTTP protocol review:

In the previous article: Javaweb learning Servlet (a)----myeclipse and Tomcat configuration, we can see the servlet resources written in myeclipse by entering the URL in the browser, with the following effects:

, the whole process is this: when the URL is entered in the browser, it resolves to the IP address through the Hosts file/dns server, and then finds the server that corresponds to the IP address.

During this time, the browser makes the request through the HTTP protocol. After the server receives the request, it does the following:

(1) Analyze which virtual machine is currently requested:

    • View the host request header to analyze which virtual host is being accessed
    • If there is no host request header (enter the IP address directly in the browser address bar instead of the URL), access the default virtual host

(2) analyze which web App the current virtual host is currently requesting access to:

    • Analyze from the requested Resources section of the request line

(3) to analyze which resource of this web app is being accessed by the current request:

    • Analyze which resource is accessed from the resource section of the request line

(4) Find the Web. xml file to see if there is a corresponding virtual path, and if so, respond with the resource corresponding to the virtual path.

(5) The server obtains the previously written data from the response object (which is the Java code written in the servlet) and organizes it into an HTTP response message to the browser .

Note: The sentence of paragraph (5) is the focus of this study.

Second, the operating process and life cycle of Servet

The servlet program is called by the Web server, and the Web server receives the client's Servletweb server first to check if the servlet's instance object has been loaded and created. If yes, proceed directly to step (4), otherwise, step (2).

After the access request:

(1) Mount and create an instance object of the servlet.

(2) Call the Init () method of the Servlet instance object.

(3) Create a HttpServletRequest object to encapsulate the HTTP request message and a HttpServletResponse object that represents the HTTP response message, and then call the servlet's service () Method and passes the request and response objects in as parameters.

(4) Before the Web application is stopped or restarted, the servlet engine uninstalls the servlet and calls the servlet's Destroy () method before uninstalling.

The life cycle of Servet:

The life cycle of a servlet defines how a servlet is loaded, initialized, and how it receives requests, responds to requests, and provides services.

The life cycle is as follows:

    • (1) Typically, the server creates an instance object (Servlet birth) of the Servlet class when the servlet is first called, and calls the Init () method to initialize the object immediately after it is created;
    • (2) Once created, the servlet instance resides in memory for subsequent requests to the servlet, and each access to the servlet will result in the service method execution in the servlet;
    • (3) When the Web app is removed or the server is shut down, the servlet will be destroyed as the Web App is destroyed (Servlet death). Before destroying the server calls the servlet's destroy method to do some cleanup work.

There are 3 ways to represent the life cycle of a servlet:

    • Init method, which is responsible for initializing the Servlet object.
    • Service method, which is responsible for responding to a customer's request (calling Doget or Dopost, etc.).
    • The Destroy method is responsible for releasing the resources that are consumed when the Servlet object exits the lifecycle.

Note: During the entire lifetime of the servlet, the servlet's Init method is called only once when the servlet is created, and each access to the servlet causes the service method in the servlet to execute.

For example: The browser now accesses the servlet 10 times in a row, with only one Sevlet object in memory. servlet objects created by the server (created once), request and response created by the servlet container (created 10 times)

Take a look at the code:

 1 package com.vae.servlet; 2 Import java.io.IOException; 3 Import Java.io.PrintWriter; 4 Import javax.servlet.ServletException; 5 Import Javax.servlet.http.HttpServlet; 6 Import Javax.servlet.http.HttpServletRequest; 7 Import Javax.servlet.http.HttpServletResponse; 8//General implementation of a servlet, as long as the inheritance of the HttpServlet class can be 9 public class Myservlet extends HttpServlet {Ten//servlet Initialize the method called one by one @Overri     De12 public void Init () throws Servletexception {Super.init (); System.out.println ("Init ...."); 15 }16//servlet is destroyed when the method is called @Override19 public void Destroy () {Super.destroy (); Ystem.out.println ("Destroy ...");}23//-------Doget/dopost core Business processing method (called by service method)------------@Overr Ide25 protected void doget (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, IO Exception {//super.doget (req, resp); DoPost (req, resp); System.out.println ("Do service ...") ;}31 @Override33 protected void DoPost (HttpServletRequest req, HttpServletResponse resp) 34 Throws Servletexception, IOException {//super.dopost (req, resp); 36}37}

Run the program, enter the URL, at this point, a press ENTER, the log will be played in the background immediately:

Then refresh the Page three times consecutively, the log is as follows:

As you can see, Servelet is initialized only once, and then we visit the same Sevlet object multiple times. At this point, the servlet is not destroyed even if the Web page is turned off, and the servlet is destroyed only if the Tomcat server is turned off.

It is important to note that the foreground may have get and post two requests, but the processing done in the background is the same . For example: The front-end input user name password, in the background verification is not distinguish which request method. So, if the code content is written in the Doget () method, we can add a sentence in the Dopost () method: "Doget (REQ,RESP);" can be reused (after all, the same logic is executed).

Third, the inheritance structure of the servlet:

    • servlet Interface: defines the basic methods that a servlet should have
    • Genericservlet: An abstract class that implements a servlet interface. Generic basic servlet implementation, for the less commonly used methods in this implementation class in the basic implementation, the service design for the abstract method, requires subclasses to implement
    • HttpServlet: abstract class, inheriting the Genericservlet class. Based on the common Servlet, the HTTP protocol is further enhanced: the service method in Genericservlet is replicated, and thecode in the service method body automatically determines how the user requests it, such as a GET request, Call HttpServlet's Doget method, such as a POST request, to invoke the Dopost method. As a result, developers typically only need to inherit httpservlet when writing a servlet, and then overwrite the Doget or Dopost method rather than overwrite the service method.

Iv. Modifying the servlet template:

When using MyEclipse to create a servlet, the servlet code generated from the default servlet template is as follows:

View Code

In the actual development, these generated code and comments are generally not available to us, each time we have to manually delete these comments and code, it is cumbersome, so you can adapt to the actual development of the servlet template code, to meet the actual development requirements of the template code.

MyEclipse 10 The steps to modify the servlet template are as follows:

Close the MyEclipse and locate the \common\plugins folder in the MyEclipse installation directory, such as:D:\MyEclipse10\Common\plugins, Then find Com.genuitec.eclipse.wizards_9.0.0.me201108091322.jar this jar file, as shown in:

With the compression tool open, Note that it is open instead of unpacking the jar package , as shown in:

, open the servlet.java file in the Templates folder in the jar package to see the template code inside:

View Code

Code template, remove the code from the comments and methods above Doget and Dopost, and add a row doget (request,response) in the Dopost method; The effect is as follows:

After you have modified, save, restart MyEclipse, you can use the new template code:

Package Com.vae.servlet;import Java.io.ioexception;import Javax.servlet.servletexception;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;public class Servlet2 extends HttpServlet {public    void doget ( HttpServletRequest request, HttpServletResponse response)            throws Servletexception, IOException {    }    public void DoPost (HttpServletRequest request, httpservletresponse response)            throws Servletexception, IOException {        doget (request, response);}    }

(turn) Javaweb learning servlet (ii)----servlet life cycle, inheritance structure, modifying servlet templates

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.