Location>code7788 >text

JavaWeb in the Tomcat, Servlet Details

Popularity:551 ℃/2024-08-06 21:55:51

JavaWeb

JavaWeb technology mainly includes server technology (back-end), such asTomcat,Servlet,JSPWaiting, and client-side technologies (front-end) such asHTML,CSS,JavaScriptwait a minute!

web server

Web servers are mainly responsible for processing HTTP requests from the client and respond accordingly

  • Web server.Computers with server software installed are used only for complex processing of requests, sending out the corresponding
  • Web server software:: Accepting client requests, processing requests and making responses
  • web serverYou can deploy a web project and let the browser act as a medium to access it.

Web server software

Server software is deployed in the server program, there are mainly the following kinds, we mainly learn the use of Tomcat

  1. weblogic: oracle, a large javaEE server, supports all JavaEE specifications, charges.
  2. websphere: IBM, a large javaEE server, support for all ovaTE specifications, charges.
  3. JBOSS: JBOSS company, a large javaEE server, support for all the JavaIL specification, the charge.
  4. Tomcat : Apache Foundation , small and medium-sized javaEE server , open source , free .

Tomcat

Tomcat is a free open source Java Servlet (Server Applet, service program) container , mainly for the deployment and operation of Java-based Web applications , was founded by the Apache Foundation , belongs to the lightweight server .

Tomcat main features

  • Servlet container:TomcatImplementing a Servlet Specification Container, can be used to deploy Servlet and JSP Web applications .JSP (JavaServer Pages) is a dynamic web content technology, which allows developers to embed Java code and features of JS into HTML pages
  • Lightweight.Tomcat is a lightweight server, compared to other commercial servers.Fast startup and low resource consumption
  • Easily configurable.Tomcat configuration file is simple and clear, easy to understand the modifications

Tomcat Architecture

  • Connector.Used to receive client HTTP requests and forward them to the correspondingServlet,also providesSockettogether withRequestcap (a poem)ResponseRelated transformations.
  • Container:ContainerbeTomcatdeal withServletThe core component of the system consists ofEngine, Host, Context, Wrapper.

TomcatThere is only oneServerOne.Servercan contain more than oneServiceOne.ServiceCan only contain oneContainer However, it is possible to include more than oneConnector Because a service can have multiple connections; the schematic is as follows.

multi- (faceted, ethnic etc)Connectorand aContainerIt is then possible to form aSevricewithServiceIt can be made available to the public, but it needs a runtime environment.Serverprovides a runtime environment whose relationships can be found in theTomcat(used form a nominal expression)confdirectory of theView in configuration file

Connector's relationship with Container

It is clear from the content of the appeal that a request sent to theTomcatWhen it does, it passes through theService,and then forwarded to ourConnector

  • Connectoris used to receive requests and encapsulate them intoRequestrespond in singingResponseto deal specifically with.Requestcap (a poem)ResponseAfter encapsulation, it will be handed over to theContainerProcessing.ContainerAfter the request is processed it is returned to theConnector, and finallyConnectorpass (a bill or inspection etc)SocketPutting the results of the processing back to the client

Servlet

A Java Servlet is a program that runs on a web server or application server.It is used as a Web browser or other HTTP client requests and HTTP servers on the database and the application of the middle layer , which is essentially written in the java language, an interface

Advantages of Servlets

  • Good performance
  • Servlets execute in the address space of the web server, theSo there is no need to create a separate process to handle each client's request
  • Servlets are platform independentBecause it is written in the Java development language.

Servlet Architecture

The following figure shows the location of the Servlet in the web application.

Servlet Tasks

  • Reading display data sent by the client (browser). HTML forms on included web pages, or can be forms from applets or custom HTTP clients.
  • Read the implicit HTTP request data sent by the client (browser), theIncludes cookies, media types and compression formats understood by the browser, etc.
  • Processing data and generating results, a process that may require access to a database, execute RMI or CORBA calls, invoke web services, or directly calculate the corresponding response.
  • Send explicit data (i.e. documents) to the client (browser). The format of the document can be various, including text files (HTML or XML), binary files (GIF images)
  • Send an implicit HTTP response to the client

Servlet Life Cycle

*Servletlife cycle can be understood as the process from creation to destruction*.

  • Called after Servlet initializationinit()methodologies
  • Servlet callsservice()method to handle client requests
  • Called before Servlet destructiondestroy()methodologies
  • Finally, servlets are garbage collected by the JVM's garbage collector.

Now we begin to explain in detail the Servlet's life cycle methods

init() method

init()method is designed to be called only once. It is called when the Servlet is first created, thewill not be called for each subsequent user request.Therefore it is used for one-time initial

  • Servletis created on the first user call corresponding to theServletWhen the URL of theHowever, it is also possible to specifyServletLoaded when the server is first started
  • When a user calls aServletWhen it does, it creates aServletinstance, a new thread is created for each user request.
  • init()method as long as its purpose is to simply create or load some data., these data are used by the user servlet throughout the cycle

The init() method is defined as follows.

public void init(ServletConfig servletConfig) throws ServletException {
      //Initialization Code
    }

service() method

The service() method is the main method for performing the actual task.

  • Each time the server receives a Servlet request, the server spawns a new thread and invokes the service.
  • The service() method checks the HTTP request type(GET,POST,PUT,DELETE) and, when appropriate, call theand other methods

Here is the code for its method

  public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {

    }

The service() method is called by the container, and the service method is called at the appropriate time. , so you don't have to do anything with the service() method, you just rewrite it for the different types of user requests.doGet()maybedoPost()Methods can be

doGet() method

  • A GET request comes from a normal request for a URL, or from an unspecifiedMETHOD(used form a nominal expression)HTMLform, which is processed by the doGet() method
public void doGet(HttpServletRequest request,
                  HttpServletResponse response)
    throws ServletException, IOException {
    // Servlet code
}

The doPost method

  • The POST request comes from a specially specifiedMETHDObecause ofPOST(used form a nominal expression)HTMLform, which consists ofdoPost()methodology
public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    // Servlet code
}

Destroy() method

  • destory()methodology andinit()method can only be called once.Called at the end of the Servlet lifecycle
  • The destroy() method allows your Servlet to close a database connection, stop a background thread, write a list of cookies or a hit counter to disk, and so on.
  • After calling thedestroy()After theservletThe object is then marked for garbage collection

The destory() method is defined as follows.

 public void destroy() {
    // Termination code...
  }

The architecture diagram is as follows

configure

  • <web-app> :The root element of the XML file, used to declare the version of the XML. encoding format and the location of the Web application's schema file (XSD).

  • <servlet>cap (a poem)<servlet-mapping>

    <servlet> Class information used to define a Servlet, including its name and implementation of the class

    • <servlet-name> :SettingServletName of the instance
    • <servlet-class> :: Configure the path to the class, make sure there is a corresponding class before you create it.

    <servlet-mapping> : Used to specify one or more URL patterns over the previously definedServletMapping between

    • <servlet-name>:: Used to bindservletLabel name needs to be the same as<servlet>tagged<servlet-name>concordance
    • <url-patter> : Configure the request path, the client request according to the path, can trigger the correspondingServletinstance of theservletmethodologies

    <load-on-startup> : Create a Servlet object on first access, set the value in the middle to a negative number.

    <load-on-startup> :: Created after server startup, set intermediate value to a number greater than 0

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns="/xml/ns/javaee"
             xmlns:xsi="http:///2001/XMLSchema-instance"
             xsi:schemaLocation="/xml/ns/javaee /xml/ns/javaee/web-app_4_0.xsd"
             version="4.0">
      <servlet>
          <servlet-name>servlet01</servlet-name>
          <servlet-class>.MyServlet01</servlet-class>
          <load-on-startup>0</load-on-startup>
      </servlet>
        <servlet-mapping>
            <servlet-name>servlet01</servlet-name>
            <url-pattern>/a</url-pattern>
        </servlet-mapping>
    </web-app>
    

Servlet annotations

The use of annotations avoids the need for the file for explicit configuration, thus reducing the complexity of the configuration file and improving development efficiency.

@WebServlet

  • Role: tags are used to define their URL mapping and other configurations directly on the Servlet class
  • Attributes.
    • valuemaybeurlPatterns : Specify one or more URL patterns that can be used to match HTTP requests and distribute them to servlets.
    • name:forServletConfigure a name
    • loadOnStartup:DesignationServletWhether and in what order it is loaded at server startup
    • asyncSupported : Indicates if the Servlet supports asynchronous processing
    • initParams :: Initialize the parameter list
  • urlPatternsConfiguration method.

Configure multiple attributes with their attribute names

@WebServlet({"/demo1","/demo2",...}) // Configure multiple request paths to correspond to one servlet
@WebServlet("/user/demo1")//configure multiple paths
@WebServlet("/user/*")//match requests that begin with user
@WebServlet("/*")//match all requests
@WebServlet("/*.do")//match requests ending in do

HttpServlet

HttpServlet beServletis an implementation of an abstract class. It is an abstract class that is implemented in the sourceServlet interface adds some information about theHttpprotocol processing method, which is more powerful than theServlet is powerful, and in the actual development, theImplementing an interface service usually inherits from this class and avoids direct inheritance.Servletresemble

GET requests and POST requests

GET request

A GET request is aHTTPMethods,Used to request resources from the server.When a client (usually a browser) makes a request to a server, the client can use it to create an application.It is in requesting a specific resource

  • Parameters for GET requests
    • The parameters of a GET request are usually appended to the URL, using the?Separate URLs and parameters with the
    • The parameters are separated by using the&segregation
    • Example./resource?param1=value1&param2=value2
  • Security of GET requests
    • All parameters in a GET request are exposed in the URL, so it may be recorded in the browser's history or log files, less secure
    • Therefore, GET requests cannot be used to pass sensitive information, such as passwords, etc.
  • cache speed
    • Browsers and other intermediate components cache the results of GET requests, thus leading to faster GET requests and improved performance
  • Limitations of GET
    • Since the GET request is sent via a URL, and the URL itself has a length limitation.Therefore the length of GET is limited
  • General usage scenarios for GET
    • GET requests are usually used to retrieve information, thesuch as querying a database or fetching static resources

POST request

Consistent with the GET request the POST request is also aHTTPmethod, which is used to send data to the server. When a client (browser) sends a request to the server using the POST method, theIt is submitting the data to the server for processing

  • POST request body

    • POST requests are usually not placed in the URL, but in the body of the request.
    • This means that the data will not be displayed in the URL, which is more secure and implicit than GET requests.
  • safety

    • Since the data is not displayed in the URL, POST is more suitable for transmitting sensitive information.
    • The data in a POST request is usually organized using an encoded format
  • POST Restrictions

    • POST length is not limited, so large amounts of data can be transferred.
    • But servers still have their own maximum limits
  • POST General Usage Scenarios

    • POST requests are usually used to submit data, andsuch as login forms, registration forms

doGet() and doPost()

doGet()

doGet()The methodology isHttpServlet A method in the class

  • Type of request
    • doGet()method is specialized for handling HTTP GET requests

doPost()

doPost()The methodology isHttpServletA method in the class

  • Type of request
    • doPost()method is specialized in handling HTTP POST requests

:

@WebServlet("/login")
public class MyHttpServlet01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ("fulfillmentGETRequest business logic");
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ("fulfillmentPOSTRequest business logic");
    }
}

MyHttpServlet01class isHttpServlet class, overriding itsdoGet()respond in singingdoPost()method, we in Postman software can go to test its GET request and POST request respectively