Table of contents
What is a Servlet Container (Web Container)
There are many tutorials online
Several commonly used Tomcat commands
@WebServlet annotation (Servlet annotation)
Attributes of the @WebServlet annotation
load-on-startup element: Control Servlet startup priority
Servlet virtual path matching rules
Detailed explanation of ServletConfig interface
Obtain the ServletConfig object (generally there are two methods)
Methods provided by the ServletConfig interface
Configure Servlet initialization parameters (2 ways)
Get Servlet initialization parameters
Detailed explanation of ServletContext interface
Get the ServletContext object (4 methods)
Detailed explanation of HttpServletRequest interface
Detailed explanation of HttpServletResponse interface
FilterChain filter chain (Servlet)
FilterConfig interface (Servlet)
Why learn Servlet
What exactly is a Servlet
Servlet is a specification
Servlet interface
JSP
The correct order to learn Servlet is: Java --> Servlet.
The correct order of learning JSP is: Java --> Servlet --> JSP
Servlet version
Applet
Java Servlet is a "server-side applet" that runs on a server and is used to develop a dynamic website; Java Applet is a "client-side applet" that is generally embedded in an HTML page and runs in a browser that supports Java.
Both Applet and Servlet are Java-based technologies with very powerful functions. However, Applet development steps are complicated and can only be run on a computer with a Java Virtual Machine (JVM) installed. Now it has been fully replaced by JavaScript, and almost no one learns Applet anymore.
What is a Servlet Container (Web Container)
Generally choose Apache or Nginx to run PHP website; generally choose IIS to run ASP/ASP.NET website; generally choose built-in WSGI server module—wsgiref to run Python website.
A web server is a software that provides web services to the outside world. It can receive HTTP requests from browsers and return processing results to the browsers. When deploying Servlet websites, a similar software is also required, such as Tomcat, Jboss, Jetty, WebLogic, etc., but they are usually called "containers", not "servers"
web server
Commonly referred to as web servers, such as Apache, Nginx, IIS, etc., their functions are often relatively single, they can only provide http(s) services, allowing users to access static resources (HTML documents, pictures, CSS files, JavaScript files, etc.), they cannot execute any programming language, nor can they access databases, let alone allow users to register and log in. That is, if you only have a web server, you can only deploy static websites, not dynamic websites. To deploy a dynamic website, it is necessary to have the support of the programming language operating environment (runtime, Runtime) and the database management system.
Operating environment: The programming languages used to develop websites are generally scripting languages (such as PHP, ASP, Python). When deploying a website, the source code is directly thrown to the server. However, the source code itself cannot run and must have the support of an interpreter; when a user visits a dynamic page, the interpreter is responsible for analyzing, compiling and executing the source code, and then obtains the processing results.
Database: The web server does not have a database, and the programming language does not have a database. The database is an independent software; in order to realize functions such as user registration, publishing articles, and submitting comments, a database must be installed
Summary: Deploying dynamic websites generally requires at least three components, namely Web server, scripting language runtime and database
web container
The container in Servlet is used to hold classes and objects
The position of the Servlet container in the entire HTTP request process
After using the web container as a server
The web server is the "gate" of the entire dynamic website. The user's HTTP request first arrives at the web server, and the web server judges whether the request is a static resource or a dynamic resource: if it is a static resource, it will return it directly, which is equivalent to the user downloading a file on the server; if it is a dynamic resource, it cannot be processed, and the request must be forwarded to the Servlet container. After the Servlet container receives the request, it will find the corresponding Servlet class according to the configuration file (web.xml), load and instantiate it, and then call the method in it to process the user request; after the processing, the Servlet container will transfer the processing result to the Web server, which will encapsulate the processing result and send it to the final user in the form of an HTTP response.
Summarize
The Servlet container is the operating environment of the Servlet program, which mainly includes the following functions: Implement various interfaces and classes defined by the Servlet specification, and provide underlying support for the operation of the Servlet; Manage the Servlet classes written by users and the objects after instantiation; Provide HTTP services, which is equivalent to a simplified server.
Download and install Tomcat
There are many tutorials online
bin directory The bin directory is used to store Tomcat commands, which are mainly divided into two categories, one is Linux commands ending in .sh, and the other is Windows commands ending in .bat. Many environment variables are set here, such as JDK path, Tomcat path, etc.
conf directory The conf directory is mainly used to store Tomcat configuration files
Several commonly used files: server.xml is used to set the domain name, IP, port number, default loaded items, request encoding, etc.; context.xml is used to configure data sources, etc.; tomcat-users.xml is used to configure and manage Tomcat users and permissions; web.xml can set the file types supported by Tomcat;
lib directory The lib directory is mainly used to store jar packages that need to be loaded when Tomcat runs
The logs directory The logs directory is used to store the log files generated during the running of Tomcat. Clearing the files in this directory will not affect the running of Tomcat. In the Windows system, the output log of the console is in the catalina.xxxx-xx-xx.log file; in the Linux system, the output log of the console is in the catalina.out file.
temp directory The temp directory is used to store temporary files generated during the running of Tomcat, and clearing the files in this directory will not affect the running of Tomcat.
webapps directory The webapps directory is used to store applications (that is, commonly referred to as websites). When Tomcat starts, it will load the applications under the webapps directory, and the Servlet program we write can be placed here. Tomcat allows publishing applications in the form of folders, war packages, and jar packages
work directory The work directory is used to store compiled files (that is, class bytecode files) when Tomcat is running, such as compiled JSP files. Clear the work directory and restart Tomcat to clear the cache.
Several commonly used Tomcat commands
startup.sh/startup.bat: used to start Tomcat; shutdown.sh/shutdown.bat: used to shut down Tomcat; catalina.bat/ catalina.bat: used to set the memory of Tomcat.
Three ways to create Servlet
In Servlet, a dynamic web page corresponds to a Servlet class, and we can map the URL path to the Servlet class through the web.xml configuration file. The process of accessing a dynamic web page is actually the process of loading and instantiating the corresponding Servlet class and calling related methods; the content displayed on the web page is the HTML statement output to the browser through certain methods in the Servlet class.
The first step in creating a dynamic web page using Servlets is to create a Servlet class. The top level of the Servlet specification is an interface called javax.servlet.Servlet, and all Servlet classes must directly or indirectly implement this interface. It is inconvenient to directly implement the Servlet interface, so Servlet has two built-in implementation classes (abstract classes) of the Servlet interface, namely GenericServlet and HttpServlet. Therefore, there are three ways to create a Servlet class: Implement the javax.servlet.Servlet interface and rewrite all its methods. Inherit the javax.servlet.GenericServlet abstract class and rewrite the service() method. Inherit the javax.servlet.http.HttpServlet abstract class and rewrite the doGet() or doPost() method.
The relationship between Servlet, GenericServlet, and HttpServlet
GenericServlet is an abstract class that implements the Servlet interface. HttpServlet is a subclass of GenericServlet and has all the features of GenericServlet. The servlet program (MyServlet class) is a Java class that implements the Servlet interface.
Servlet interface
javax.servlet.Servlet is the core interface of the Servlet API, and all Servlet classes directly or indirectly implement this interface.
GenericServlet abstract class
javax.servlet.GenericServlet implements the Servlet interface and provides simple implementations of the other four methods except the service() method. To create a Servlet by inheriting the GenericServlet class, you only need to rewrite the service() method, which greatly reduces the workload of creating a Servlet.
HttpServlet abstract class
javax.servlet.http.HttpServlet inherits the GenericServlet abstract class and is used to develop Servlet programs based on HTTP protocol. Since Servlet is mainly used to handle HTTP requests and responses, usually, the written Servlet class inherits from HttpServlet. Seven request methods are defined in the HTTP/1.1 protocol, namely GET, POST, HEAD, PUT, DELETE, TRACE and OPTIONS. HttpServlet defines 7 methods for these 7 request methods, namely doGet(), doPost(), doHead(), doPut(), doDelete(), doTrace() and doOptions(). HttpServlet rewrites the service() method, which will first obtain the request method of the client, and then call the corresponding doXxx method according to the request method.
Summarize
Three ways to create Servlet 1) Servlet interface To create a Servlet class by implementing the Servlet interface, you need to rewrite all its methods, which is cumbersome and rarely used to create a Servlet. 2) GenericServlet class The GenericServlet abstract class implements the Servlet interface, and implements the other four methods in the Servlet interface except the service() method. To create a Servlet by inheriting from GenericServlet, you only need to rewrite the service() method, which greatly reduces the workload of creating a Servlet. Generic means "generic". As its name suggests, GenericServlet is a general Servlet class, and does not perform special processing for certain scenarios, especially the HTTP protocol. We must manually analyze and encapsulate the request information and response information of the HTTP protocol. 3) HttpServlet class HttpServlet is a subclass of GenericServlet, which handles the HTTP protocol specifically on the basis of GenericServlet. HttpServlet provides a corresponding method for each request method of the HTTP protocol, the name is doXxx(), for example: the method for processing GET requests is doGet(); the method for processing POST requests is doPost(). As its name suggests, HttpServlet is a Servlet class tailored for the HTTP protocol. On the Internet, people access dynamic web pages through the HTTP protocol, and the most frequently used methods are GET and POST. Therefore, we usually create Servlet classes based on HttpServlet, which saves the process of processing HTTP requests.
Servlet deployment and access
java web application
Consisting of a set of Servlet/JSP, HTML files, related Java classes, and other resources, it can run in Servlet containers provided by various vendors. According to the definition of JavaWeb application, Servlet is a component of JavaWeb application.
Each component has a fixed storage directory in the JavaWeb application.
The directory structure of webapps is shown in the figure below.
deploy
The quickest way is to directly copy all the files of the JavaWeb application to Tomcat's /webapps directory.
specific steps
1. Enter the Windows DOS command line window
2. Introduce the javax.servlet package
3. Compile Servlet
4. Create directory structure
5. Move the Servlet to the Tomcat directory
6. Configure web.xml
The meaning and usage of each element in web.xml are as follows: <web-app>: root element. <servlet>: Used to register Servlet, that is, to give Servlet a unique name. <servlet> contains two main sub-elements <servlet-name> and <servlet-class>, respectively used to specify the name of the Servlet and the fully qualified name of the Servlet (package name + class name). <servlet-mapping>: Used to define the mapping between Servlet and URL. <servlet-mapping> contains two sub-elements <servlet-name> and <url-pattern>, which are used to specify the name and virtual path of the Servlet respectively.
access
In the access path http://localhost:8080/servletDemo/MyServlet, the meanings of each part are as follows: http:// indicates the HTTP protocol; localhost: indicates the server IP; 8080 indicates the port number; /servletDemo indicates the context root path of the Web application; /MyServlet indicates the resource path, which is the value of the <url-pattern> element in web.xml
@WebServlet annotation (Servlet annotation)
Attributes of the @WebServlet annotation
@WebServlet is used to declare a class as a Servlet, which will be processed by the container during deployment, and the container will deploy the corresponding class as a Servlet according to its specific attribute configuration
some common attributes
Use of @WebServlet annotation
1. Enable annotation support There is an attribute in the top-level tag <web-app> of web.xml: metadata-complete, which is used to specify whether the current web.xml is complete. If this property is set to true, the container will only rely on web.xml during deployment, ignoring all annotations. If you do not configure this property, or set it to false, it means that annotation support is enabled. Since the default value of the metadata-complete attribute is false, that is, the Servlet annotation support is enabled by default, so by default, when using this annotation, it is not necessary to create a web.xml file.
2. Use @WebServlet annotation @WebServlet is a class-level annotation, which is marked on the class that inherits HttpServlet. A common way of writing is to directly write the relative request path (namely value) of the Servlet in the annotation, as shown below. @WebServlet("/MyServlet") If multiple attributes need to be set in @WebServlet, the attributes must be separated by commas. This method omits the urlPatterns attribute name, and its complete method is as follows. @WebServlet(urlPatterns = "/MyServlet").
Precautions:
Servlet classes created by implementing the Serlvet interface or inheriting GenericServlet cannot use the @WebServlet annotation. Use the @WebServlet annotation to configure the Servlet class, and do not configure the Servlet-related properties in the web.xml file again. If web.xml and @WebServlet are used to configure the same Servlet class at the same time, the value of <servlet-name> in web.xml cannot be the same as the value of name in the annotation, otherwise the container will ignore the configuration in the annotation.
Advantages and disadvantages of @WebServlet annotation and web.xml Servlet can be configured using either web.xml or @WebServlet annotation, both have advantages and disadvantages. @WebServlet annotation configuration Servlet Advantages: @WebServlet is directly used in the Servlet class, with less code and simple configuration. Each class only focuses on its own business logic and does not interfere with other Servlet classes, which is suitable for simultaneous development by multiple people. Disadvantage: When there are many Servlets, the configuration of each Servlet is distributed in its own class, which is not easy to find and modify. Web.xml configuration file configuration Servlet Advantages: Centralized management of Servlet configuration, easy to find and modify. Disadvantages: The code is cumbersome, not very readable, and not easy to understand.
Servlet life cycle
Servlet also has a life cycle, and the life cycle of Servlet is the process from creation to destruction of Servlet. The lifecycle of a Servlet is managed by the Servlet container,
It is mainly divided into the following three stages.
initialization phase
runtime phase
Destruction phase
Three methods are defined in the javax.servlet.Servlet interface: init(), service(), and destroy(), which are called by the Servlet container at different stages of the Servlet life cycle
initialization phase
Servlet initialization is the first phase of its life cycle and the basis for the other phases. Only after the initialization is completed can the Servlet process the request from the client.
The Servlet initialization phase is divided into 2 steps:
Load and instantiate the Servlet;
Call the init() method to initialize.
1. Load and instantiate the Servlet The Servlet container is responsible for loading and instantiating the Servlet. When the container starts or requests a Servlet for the first time, the container will read the configuration information in web.xml or @WebServlet, and load the specified Servlet. After loading successfully, the container will instantiate the Servlet through reflection. Because the Servlet container creates a Servlet instance through the Java reflection API, it needs to call the Servlet's default constructor (default constructor, that is, a constructor without parameters), so when writing a Servlet class, you cannot just provide a constructor with parameters.
2. Call the init() method for initialization. After loading and instantiation, the Servlet container calls the init() method to initialize the Servlet instance. The purpose of initialization: Let the Servlet instance complete some initialization work before processing the request, such as establishing a database connection, obtaining configuration information, and so on. The init() method can only be called once during the entire lifetime of the Servlet. During initialization, the Servlet instance can obtain the initialization parameters configured in web.xml or @WebServlet through the ServletConfig object.
runtime phase
The runtime phase is the most important phase in the Servlet life cycle. When the Servlet container receives a request from the client, the container will create a ServletRequst object and a ServletResponse object for the request, pass them into the service() method as parameters, and call this method to process the request.
It should be noted here that before executing the service() method, the init() method must have been successfully executed.
In the service() method, the Servlet obtains the relevant information and request information of the client through the ServletRequst object. After the request processing is completed, the response information is packaged through the ServletResponse object and returned to the client. When the Servlet container returns the response information to the client, the ServletRequst object and the ServletResponse object will be destroyed. During the entire life cycle of the Servlet, for each request of the Servlet, the Servlet container will call the service() method once, and create new ServletRequest and ServletResponse objects. That is, the service() method will be called multiple times during the entire life cycle of the Servlet.
Destruction phase
When the Servlet container closes, restarts or removes the Servlet instance, the container will call the destroy() method to release the resources used by the instance,
For example: close the database connection, close the input stream and output stream of the file, etc., and then the instance is recycled by Java's garbage collector. For each Servlet instance, the destroy() method can only be called once.
load-on-startup element: Control Servlet startup priority
load-on-startup is a node in web.xml, a sub-element of the servlet element, used to mark whether to initialize the current Servlet when the Servlet container starts, and the initialization sequence of the current Servlet.
The value rules of the load-on-startup element are as follows:
1. Its value must be an integer;
2. When the value is less than 0 or not specified, it means that the container will be loaded when the Servlet is requested for the first time;
3. When the value is greater than 0 or equal to 0, it means that the container loads and initializes the Servlet when it starts, and the smaller the value, the higher the priority;
4. When the values are the same, the container will choose the order to load. The loadOnStartup attribute of the @WebServlet annotation corresponds to the load-on-startup element in web.xml, and the rules and meanings of value selection are the same.
Servlet virtual path mapping
The client accesses the resources in the Web server through the URL address. If the Servlet program wants to be accessed by the outside world, it must be mapped to a URL address. Many times, the URL address is not consistent with the physical path (storage location on the hard disk) of the Servlet program, so it is called a virtual path. The corresponding relationship between Servlet and virtual path is called Servlet virtual path mapping.
Servlet virtual path mappings can be divided into 2 categories:
single mapping
multiple mapping
Servlet Single Mapping
There are two ways to implement Servlet single mapping:
* Use web.xml to achieve a single mapping;
* Use @WebServlet to implement a single mapping.
web.xml implements a single mapping
In the web.xml file, use the <servlet> and <servlet-mapping> elements to implement a single Servlet mapping
@WebServlet implements a single mapping
In the @WebServlet annotation, the value attribute is generally used to implement a single Servlet mapping = "@WebServlet("virtual path");
You can also use the urlPatterns attribute to implement a single Servlet mapping => @WebServlet("urlPatterns="virtual path")
Servlet Multiple Mapping
The multiple mapping of Servlet means that a Servlet can be mapped to multiple virtual paths. At this point, the client can access the same Servlet through multiple paths.
There are three ways to implement Servlet multi-mapping:
Configure multiple <servlet-mapping> elements.
Configure multiple <url-pattern> sub-elements.
Using an array of strings in the urlPatterns attribute of @WebServlet
Configure multiple <servlet-mapping> elements
Configuring Multiple <servlet-mapping> Elements Before the Servlet 2.5 specification, the <servlet-mapping> element was only allowed to contain one <url-pattern> sub-element. To realize the multiple mapping of Servet, it can only be realized by configuring multiple <servlet-mapping> elements.
Configure multiple <url-pattern> sub-elements
Starting from Servlet 2.5, the <servlet-mapping> element can contain multiple <url-pattern> sub-elements, and each <url-pattern> represents a mapping rule for a virtual path. Therefore, by configuring multiple <url-pattern> sub-elements in one <servlet-mapping> element, multiple mapping of Servlets can also be realized.
@WebServlet implements multiple mapping
Servlet 3.0 adds support for @WebServlet annotations. We can specify a set of mapping rules in the form of a string array in the urlPatterns attribute to implement multiple mappings for Servlets.
Servlet virtual path matching rules
There are four types of matching rules:
1. Full path matching
2. Directory matching
3. Extension matching
4. Default match (default match)
Matching priority The matching priority order of the Servlet virtual path is: full path matching (exact matching) > directory matching > extension matching > default matching (default matching).
The servlet container will start matching from the virtual path with high priority. After the matching is successful, it will immediately hand over the request to the corresponding Servlet for processing, and will not pay attention to whether other virtual paths are matched successfully.
Detailed explanation of ServletConfig interface
When the Servlet container initializes the Servlet, it will create a ServletConfig object for this Servlet, and pass the ServletConfig object to the Servlet as a parameter. The initialization parameter information of the current Servlet can be obtained through the ServletConfig object. There can be multiple ServletConfig objects in a Web application, and a Servlet can only correspond to one ServletConfig object, that is, the initialization parameters of a Servlet are only valid for the current Servlet.
Obtain the ServletConfig object (generally there are two methods)
1. Extract directly from the init() method with parameters
2. Call the getServletConfig() method provided by GenericServlet to obtain
Methods provided by the ServletConfig interface
Configure Servlet initialization parameters (2 ways)
1. Use web.xml to configure initialization parameters
In web.xml, one or more <init-param> elements can be used to configure initialization parameters for the Servlet
2. Use @WebServlet to configure initialization parameters
You can also set initialization parameters for Servlet through the initParams attribute of @WebServlet
Get Servlet initialization parameters
Detailed explanation of ServletContext interface
The life cycle of the ServletContext object starts when the Servlet container starts and ends when the container is shut down or the application is unloaded.
Get the ServletContext object (4 methods)
1. Through the getServletContext() method provided by GenericServlet
2. The getServletContext() method provided by ServletConfig
3. The getServletContext() method provided by HttpSession
4. The getServletContext() method provided by HttpServletRequest
Application of ServletContext
Get context initialization parameters
Divided into 2 steps:
1) Set context initialization parameters
2) Call the method in the interface to get the initialization parameters
Realize data communication between Servlets
In a Servlet, some attributes can be created by calling the setAttribute() method of the ServletContext interface, and these attributes are stored in the ServletContext object. All Servlets in the application can access and operate these attributes, through which data communication between different Servlets in the application can be realized
Read resource files under the web application
The ServletContext interface defines some methods for reading Web resources
Detailed explanation of HttpServletRequest interface
HttpServletRequest interface
The HttpServletRequest object is specially used to encapsulate the HTTP request message, referred to as the request object.
The HTTP request message is divided into three parts: request line, request header and request message body, so the HttpServletRequest interface defines related methods for obtaining the request line, request header and request message body.
Detailed explanation of HttpServletResponse interface
The HttpServletResponse object is specially used to encapsulate the HTTP response message, referred to as the response object.
The HttpServletResponse interface defines methods for sending response status code, response header, and response body to the client
Servlet request forwarding
Request forwarding is a server behavior. After the container receives the request, the Servlet will first do some preprocessing on the request, and then pass the request to other web resources to complete the follow-up work including generating the response
RequestDispatcher interface
Servlet can obtain RequestDispatcher object in two ways:
1. Call the getRequestDispatcher(String path) method of ServletContext, the parameter path specifies the path of the target resource, which must be an absolute path;
2. Call the getRequestDispatcher(String path) method of ServletRequest. The parameter path specifies the path of the target resource, which can be an absolute path or a relative path.
request domain object
request is one of the three major domain objects of Servlet. It needs to be used in conjunction with request forwarding to realize data transfer between dynamic resources.
Servlet redirection
Redirection is a client behavior. After receiving the client's request, the server will notify the client's browser to resend the request to another URL, which is called request redirection. It is essentially two HTTP requests, corresponding to two request objects and two response objects.
Use of Servlet Cookies
Session technology refers to the technology that helps the server record user status and data in a session.
There are two commonly used conversational techniques:
Cookies: client-side session technology
Session: server-side session technology
Use of Servlet Session
The default expiration time of Session is 30 minutes, and the expiration time can be set in two ways
1. Using the <session-config> element
In web.xml, use <session-config> and its sub-element <session-timeout> to configure the default expiration time of Session
2. 调用 session.setMaxInactiveInterval(int interval)
Set the expiration time in seconds by calling session.setMaxInactiveInterval(int interval), zero and negative numbers mean that the session will never expire
Session life cycle
Session object creation The Session object is created when the container calls the request.getSession() method for the first time. It is worth noting that when the web resources accessed by the client are static resources such as HTML, CSS, and pictures, the server will not create a Session object.
Destruction of the Session object The Session object will be destroyed in the following three situations:
1. Session expires;
2. Call the session.invalidate() method to manually destroy the Session;
3. The server is shut down or the application is uninstalled.
Servlet Filter
Check and modify the request object and response object passed to the Web resource by the Servlet container
Only the following filtering capabilities are available for web resources:
1. Before the web resource is accessed, check the request object, modify the request header and request body, or perform preprocessing operations on the request.
2. Pass the request to the next filter or target resource.
3. After the web resource is accessed, check the response object, modify the response header and response body
FilterChain filter chain (Servlet)
In a Web application, multiple Filters can be deployed. If these Filters all intercept the same target resource, they form a Filter chain (also called a filter chain). Each filter in the filter chain is responsible for a specific operation and task, and the client's request is passed between these filters until it is delivered to the target resource.
FilterConfig interface (Servlet)
A FilterCofig interface is provided in the Javax.Servet package, which is similar to the ServletConfig interface and is used to pass information to the filter during initialization. The FilterConfig interface is implemented by the container, and the container passes it as a parameter to the filter's init() method . The initialization parameters of Filter can be obtained through the filterConfig object.
Servlet Listener (listener)
Listener Listener can be divided into three categories according to the monitored events: 1. Listener for object creation and destruction 2. Listener for property change in object 3. Listener for object state change in HttpSession
There are two ways to register a Servlet listener, namely:
1. Register the listener in web.xml;
2. Register the listener with @WebListener.