Servlet basic understanding

1. Description:

  Servlet (Server Applet) is a Java Servlet short, called the small connector service programs or services, written in Java Server-side program, with a platform-independent and protocol features, the main function is to interactively browse and generate data, generate dynamic Web content. It refers to a narrow Servlet interface to the Java language, broadly refers to any Servlet class implements the Servlet interface, under normal circumstances, people will understand Servlet for the latter. Servlet running on Java-enabled application servers. In principle, Servlet can respond to any type of request, but in most cases only used to extend the Servlet Web server based on HTTP protocol.

 

2. Task:

  Servlet performs the following major tasks:

  • Read client (browser) of the transmitted data explicit. Form HTTP client program that includes HTML form on a web page, or may be derived from or customized applet.
  • Read client (browser) sends implicit HTTP request data. This includes cookies, media types and browsers can understand compression format, and so on.
  • Processing the data and generate a result. This process may need to access the database, the implementation of RMI or CORBA calls, call the Web service, or directly calculated corresponding response.
  • Transmitting the explicit data (i.e., document) to the client (browser). The format of the document can be varied, including text files (HTML or XML), binary files (GIF image), Excel and so on.
  • Sending an implicit HTTP response to the client (browser). This includes the type of document that tells the browser or other client is returned (eg HTML), setting Cookies and cache parameters, and other similar tasks.

 

3. Architecture:

    

 

 

 

 

 4. life cycle (execution):

  Servlet life cycle is the destruction of the whole process from servlet to appear. Divided into the following phases:

  Loading classes -> instantiated (assigned to the object space) -> initialized (object attribute assignment) -> Processing Request (Service Stage) -> Destruction

  

 

package com.tsvv;

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 TsvvServlet extends HttpServlet{
    //初始化servlet,调用init方法
    @Override
    public void init() throws ServletException {
        System.out.println("初始化时调用");
    }
    //开启服务
    @Override
    protected void Service (arg0 the HttpServletRequest, HttpServletResponse arg1) throws ServletException, IOException { 
        System.out.println ( "call the open service" ); 
    } 
    @Override 
    protected  void doGet (REQ the HttpServletRequest, HttpServletResponse RESP) throws ServletException, IOException { 

    } 
    // Destruction when calling Destory 
    @Override
     public  void the destroy () { 
        System.out.println ( "call when destruction" ); 
    } 
}

 

5. Servlet create three ways:

  1. Implement the Servlet interface

Package Penalty for com.tsvv;
 Import java.io.IOException; 

Import javax.servlet.Servlet;
 Import javax.servlet.ServletConfig;
 Import javax.servlet.ServletException;
 Import javax.servlet.ServletRequest;
 Import javax.servlet.ServletResponse; 

// Servlet life cycle: is created from Servlet to Servlet process of being destroyed
 // once created, the service everywhere
 // a Servlet only have one object, all service requests 
/ * 
 * 1. instantiated (using the constructor method to create the object) 
 * 2. initialize the init method 
 * 3. A method for service execution service 
 * 4. destruction destroy method executed 
 * / 
public  class ServletDemo1 the implements the Servlet { 

    //ServletDemo1 public () {} 

    // lifecycle methods: Servlet performing the method when the object is first created, the method is performed only once throughout the life cycle 
    public  void the init (the ServletConfig the arg0) throws ServletException { 
        System.out.println ( "======= ========= the init" ); 
    } 

    // lifecycle methods: a method in response to a client, the method may be performed multiple times, each time will request the servlet performing the method 
    public  void -Service (the ServletRequest the arg0, arg1 the ServletResponse)
             throws ServletException, IOException { 
        System.out.println ( "======= =========-Service" ); 

    } 

    // lifecycle methods: performing the method when the Servlet is destroyed 
    public  void the destroy () {
        System.out.println ("======= ========= the destroy" ); 
    } 
    // the servlet tomcat stop when it destroyed. 
    public the ServletConfig getServletConfig () { 

        return  null ; 
    } 

    public String the getServletInfo () { 

        return  null ; 
    } 
}

  2. GenericServlet inherited class that implements the Servlet interface in addition to the method of service, but we rarely used this method.

package com.tsvv;

import java.io.IOException;

import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class ServletDemo2 extends GenericServlet {

    @Override
    public void service(ServletRequest arg0, ServletResponse arg1)
            throws ServletException, IOException {
        System.out.println("=======service=========");

    }
}

  3. inherit HttpServlet (via create the Eclipse Servlet, default inherited HttpServlet )

package com.tsvv;

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 ServletDemo3 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        System.out.println("=======Get=========");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        System.out.println("=======Post=========");
        doGet(req,resp);
    }

}

  Automatically configure the relevant information of the Servlet in the web.xml file when you create a Servlet by Eclipse

  (Note: If you copy the class files, configuration information is not configured, you need to manually configure!)

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    id="WebApp_ID" version="3.0">
    <display-name>TestSetvlet</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>
    <servlet>
        <servlet-name>TsvvServlet</servlet-name>
        <servlet-class>com.tsvv.TsvvServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>TsvvServlet</servlet-name>
        <url-pattern>/TsvvServlet</url-pattern>
    </servlet-mapping>
    <servlet>
        <servlet-name>ServletDemo1</servlet-name>
        <servlet-class>com.tsvv.ServletDemo1</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>ServletDemo1</servlet-name>
        <url-pattern>/ServletDemo1</url-pattern>
    </servlet-mapping>
    <servlet>
        <servlet-name>ServletDemo2</servlet-name>
        <servlet-class>com.tsvv.ServletDemo2</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>ServletDemo2</servlet-name>
        <url-pattern>/ServletDemo2</url-pattern>
    </servlet-mapping>
    <servlet>
        <servlet-name>ServletDemo3</servlet-name>
        <servlet-class>com.tsvv.ServletDemo3</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>ServletDemo3</servlet-name>
        <url-pattern>/ServletDemo3</url-pattern>
    </servlet-mapping>
</web-app>

  Configuration information about the above:

    A)  the Eclipse each create a Servlet, two labels will be added in web.xml: <servlet> and <servlet-mapping> tag (the two labels can be seen as a set of labels)

    B)  <the servlet> and <servlet-mapping> the tag will have a <servlet-name> tag, the tag can change the contents, but the contents of these two <servlet-name> tag must also be consistent with the changed requirements.

    C)  <the servlet-class> tag full path name Servlet class configuration (i.e., the package name + class name)

      Note: If you change the name of the Servlet class After you create a Servlet, this place should change together, otherwise there will be "ClassNotFoundException" That class can not find abnormalities

    D)  <URL-pattern> tag is used to configure the browser to access the Servlet what path (i.e. the path Servlet access the external current), the default path: / class name

      For example: The above configuration is HelloServlet <url-pattern> is  / ServletDemo1 , we access path in the browser was:

      http: // hostname / web project access path / ServletDemo1

6. inheritance of Servlet:

  

  It can be seen that the core part:
  • Two top-level interface
    • Servlet
    • ServletConfig
  • Interface implementation class
    • GenericServlet
  • Class-based implementation of the HTTP protocol
    • HttpServlet

  Servlet whole inheritance are as follows:

  

 

   

  • ServletConfig   configuration information the Servlet, used to transfer information during initialization Servlet
    • GetServletContext () Gets the object context Servlet operation, the corresponding information can be acquired (e.g. Servlet path), the access level variable capacity
    • getInitParameter (String name) Get initialization parameters (web.xml configured init-param)
 
  • GenericServlet   general Servlet, implements the Servlet and ServletConfig Interface
    • init (ServletConfig config) initialization method, call the method init ()
    • init () initialization method, the method body is empty, the main Servlet cover for customizing
    • service (ServletRequest request, ServletResponse response) method abstract service, required to achieve the class inheritance
    • destory () method to be performed before the destruction of Servlet
 
  • HttpServlet   based class that implements the HTTP protocol
    • service (ServletRequest request, ServletResponse response) implements the abstract method GenericServlet, call the service (HttpServletRequest, HttpServletResponse)
    • service (HttpServletRequest request, HttpServletResponse response) or doPost doGet call request according to different methods
    • doGet () request processing the GET
    • doPost () request processing a POST

 

 

 

   

 

   

  Simple summarize key points:
  • Servlet initialization only once, it is a single example, only one instance, access by multiple threads. That Servlet is multithreaded single instance of
  • Instantiation, the constructor first call, and then calls the init method, the initialization operation can be written to cover the init process
  • Different calls doGet () or doPost request method () method
  • Before calling its destroy Servlet destroy the actual situation () method

 

7. Servlet works:

  Servlet interface defines Servlet and Servlet containers contract between. This contract is: Servlet class Servlet container will be loaded into memory, and generates Servlet examples and call its specific method. However, to note that, in an application, each Servlet type only one instance .

  User requests resulting Servlet container calls the Servlet Service () method, passing in a ServletRequest object and a ServletResponse objects . ServletRequest object and the objects are ServletResponse by the Servlet container (e.g. TomCat) packaged , the programmer does not need to achieve, a programmer can directly use these two objects.

  ServletRequest encapsulates current Http request, and therefore, the developer does not have to parse and manipulate Http original data. ServletResponse Http response indicates that the current user's programmers to directly manipulate objects ServletResponse will be able to easily send a response back to the user .

  For each application, Servlet container also creates a ServletContext object. This object encapsulates details environmental context (application). Each application has only one ServletContext. Each object can also have a Servlet Servlet ServletConfig object configuration package.

 

8. Servlet three global:

  

 

 

9. JSP与Servlet:

 

  JSP is a special form of the Servlet, each page is a JSP page Servlet examples --JSP compiled into the system by the Servlet, Servlet then responds to user requests. JSP is a simplified Servlet fact of using JSP, Servlet but it is still used, because the Web application will Servlet Each JSP page generated by the Servlet corresponding to the container. For Tomcat, JSP pages generated Servlet placed in the path corresponding Web application work.

 

 

Guess you like

Origin www.cnblogs.com/tsvv-plus/p/11809610.html