Hello, today I share Servlet with you, take out your little book and write it down!
Servlet Programming Basics
Servlet is a protocol connecting Web server and server-side Java program, and it is a communication specification. The specification is in the form of a set of interfaces.
The Servlet specification contains a set of interfaces. The Servlet interface is just one of them.
Microscopically, a Servlet is an instance object of a Servlet interface implementation class. It is a small Java program running on a Server, namely a Server Applet, which is the origin of the word Servlet. The main function of Servlet is to invoke server-side Java code according to the request submitted by the client to complete the processing and operation of the request.
1.1. Servlet Life Cycle
The Servlt lifecycle refers to the entire process of creating a Servlet object, initializing a Servlet object, executing a Servlet object service, and eventually destroying a Servlet object.
The Web server is responsible for managing the execution of the entire Servlet lifecycle process. That is, the Web server is responsible for the invocation of methods in the whole process of Servlet creation, service and destruction, and the programmer cannot control its execution process.
But programmers can capture these life cycle points of servlets and specify that servlets do specific business related things.
1.1.1 Life cycle method execution process
The Servlet lifecycle method execution flow:
- When the request is sent to the Web container, the Web container parses the request URL and separates the corresponding URI from the Servlet.
- Based on the isolated URI, the Servlet to execute is found by mapping the URI configured in web.xml to the Servlet, that is, the Servlet to handle the request.
- If the Servlet does not exist, the Servlet’s no-argument constructor, init() method, is invoked to instantiate the Servlet. The service() method is then executed.
- If the Servlet has already been created, the service() method is called directly.
- When the Web container is closed or the application is closed, the destroy() method is called to destroy the Servlet instance.
public class HelloServlet implements Servlet{
Public HelloServlet(){system.out.println (" instantiate "); } public void init(ServletConfig config){system.out.println (" init "); } public void service(ServletRequest Request,ServletResponse Response){system.out.println (" ServletRequest Request "); } public void deStory (){system.out.println (" destroy "); }Copy the code
}
1.1.2. Features of Servlets
Servlets are singleton multithreaded.
A Servlet instance executes the no-argument constructor and init() method only once, and on the first access.
Each time a user submits a request to the current Servlet, the service() method is executed.
A Servlet instance executes the destroy() method only once, when the application is stopped.
Because servlets are singleton multithreaded, it is generally not necessary to define modifiable member variables for Servlet classes in order to keep them thread-safe. Because each thread can modify this member variable, thread-safety issues arise.
By default, servlets are not instantiated when the Web container starts.
1.1.3. Create a Servlet instance when the Web container starts
By default, servlets are not instantiated when the Web container starts
Modifying a configuration file:
<servlet-name>hello-servlet</servlet-name>
<servlet-class>com.jiang.HelloServlet</servlet-class>
<load-on-startup>1</load-on-startup>
Copy the code
<servlet-name>hello-servlet</servlet-name>
<url-pattern>/hello</url-pattern>
Copy the code
Adding load-on-startup to a servlet flags whether the servlet instance is created and initialized when the Web server (Tomcat in this case) starts. That is, whether the no-argument constructor method and init() method that executes the Servlet are called when the Web server starts, rather than when it is actually accessed.
- Its value must be an integer.
- When the value is greater than or equal to 0, it means that the container loads and initializes the Servlet at startup. The smaller the value, the higher the priority of the Servlet and the earlier it is created.
- A value less than 0 or not specified indicates that the Servlet will not be created until it is actually used.
- When the values are the same, the container selects its own creation order.
1.1.4. GetServletInfo () method
The getServletInfo() method in the Servlet interface is the basic information about the current Servlet that is not defined by the program itself and is not a method in the Servlet life cycle.
1.2, SerlvetConfig
1.2.1. What is ServletConfig
There is a single parameter, ServletConfig, in the init() method of the Servlet interface.
ServletConfig is an interface that, as the name implies, is Servlet configuration, and ** is the configuration information for the current Servlet class in web.xml. ** The Servlet specification encapsulates all configuration information for servlets in ServletConfig interface objects.
When the Web container calls the init() method, the Web container first encapsulates the configuration information of the current Servlet class in Web.xml as an object. The type of this object implements the ServletConfig interface, and the Web container passes this object to the ServletConfig parameter in the init() method.
1.2.2 get ServletConfig
Because the ServletConfig object is passed to the current Servlet class by the Web container through the init() method, the init() method is called only once when the Servlet object is initialized. Therefore, you need to pass the ServletConfig object to the ServletConfig member variable of the Servlet in the init() method so that the Service () method can use the ServletConfig object. That is, we need to declare a ServletConfig member variable in the Servlet.
Is there a thread-safety issue after you declare a member variable?
The assignment of the ServletConfig variable is done in the init() method, and the SerlvetConfig object is readable by all threads, but cannot be modified.
1.2.3 methods in ServletConfig
In the Java help documentation, you can see the four methods of the interface:
<servlet-name>hello-servlet</servlet-name> <servlet-class>com.jiang.helloServlet</servlet-class> <! < <init-param> <param-name>myName</param-name> <param-name> <param-value>JiangZW</param-value> </init-param> <init-param> <param-name>myAge</param-name> <param-value>2</param-value> </init-param>Copy the code
- GetInitParameter () : Gets the initialization parameter value of the specified name.
getInitParameter(“myName”)
- GetInitParameterNames () : Gets all the initialization parameter names of the current Servlet. The return value is Enumeration of the Enumeration type.
getInitParameterNames()
- GetServletName () : Gets the Servlet name specified in servlet-name of the current Servlet. In the figure above, the ServletName is “hello-servlet”.
getServletName()
- GetServletContext () : Gets the current Servlet’s context object, ServletContext. This is a very important object.
getServletContext()
1.2.4 features of ServletConfig
Tomcat creates different ServletConfig for different servlets to encapsulate their configuration information. That is, a Servlet will have a ServletConfig object corresponding to it.
1.3, the ServletContext
1.3.1. What is ServletContext
A ServletContext, or ServletContext, is an interface that is the runtime environment for all servlets in a Web application in a Web container.
This runtime environment is created when the Web application is started and destroyed when the Web application is shut down. That is, a Web application has a Servlet runtime environment, a ServletContext object.
What are the details of the ServletContext runtime?
Configuration information in the web.xml file
Data that can be shared between servlets
A ServeltContext can represent the entire Web application, so to speak. So, ServletConetxt has another name: Application.
1.3.2 methods in ServletContext
See the Java documentation, you can see javax.mail. Servlet. The ServletContext interface contains a lot of ways.
Here are a few important ways to do this.
Context parameters can be configured using context-param in web. XML.
The context parameter context-param is different from the initialization parameter init-param:
Context parameters are shared by all servlets in the current Web application and are available to each Servlet.
The Servlet initialization parameters are only available to the current Servlet.
Methods:
- String getInitParameter ()
The context-param of the web. XML document is used to retrieve the upper and lower text parameter values of the specified name.
- Enumeration getInitParameterNames()
Gets all the context parameter names in context-param of the web.xml file.
- void setAttribute(String name, Object object)
setAttribute(“User”,new User());
In the public data space of the ServletContext, also known as the domain property space, you put the data. This data is global to the Web application and is the same as the entire application life cycle.
- Object getAttribute(String name)
User user = (User)getAttribute(“User”);
Gets the data of the specified name from the domain property space of the ServletContext.
- void removeAttribute(String name)
removeAttribute(“User”)
Deletes the data with the specified name from the domain property space of the ServletContext.
- String getRealPath(String path)
Obtain the path of the specified file or directory in the current Web application in the local file system. The path is based on the drive letter. Absolute path.
- String getContextPath()
Gets the name of the current application in the Web container.
1.4. Set the welcome page
1.4.1 Welcome page Settings
Welcome page refers to the page displayed by default, that is, the default access path, which can be a page such as.html,.jsp, or the access path of Servlet, when the project name is directly accessed in the browser address bar.
<welcome-file>index.jsp</welcome-file>
Copy the code
There is a welcome-file-list tag in web.xml that specifies the welcome page for the current application.
1.4.2 Specify multiple welcome pages
<welcome-file>index1.jsp</welcome-file>
<welcome-file>index2.jsp</welcome-file>
<welcome-file>index3.jsp</welcome-file>
Copy the code
You can specify multiple welcome pages for your application, but only one will be active. The system loads these welcome pages in the same order as they were registered, looking them up from top to bottom. Once it is found, it is displayed immediately and will not look down again
1.5 setting and matching of URL-pattern
The URL-pattern tag is used to filter matches for requests, filtering for the type of request to be processed by the currently registered Servlet.
There are different ways to write paths in urL-pattern, representing different meanings.
1.5.1 Exact path mode
The request path must have exactly the same value as urL-pattern to be processed by the current Servlet.
<servlet-name>someServlet</servlet-name>
<url-pattern>/some</url-pattern>
<url-pattern>/s1/s2</url-pattern>
Copy the code
1.5.2 Wildcard path mode
The path in this mode consists of two parts: the exact path part and the wildcard part.
Only the portion of the request path that carries the exact path specified in the URL-pattern value can be processed by the current Servlet.
<servlet-name>someServlet</servlet-name>
<url-pattern>/some/*</url-pattern>
Copy the code
1.5.3. Full path Mode
All submitted requests can be handled by the current Servlet. The value can be specified as /* or /.
/* and/indicate that all requests will be processed by the current Servlet. The difference between the two paths is:
- Using /* indicates that the current Servlet will block user requests for static resources (.css,.js,.html,.jpg,.png…). Requests for dynamic resources (.jsp). Instead of getting the resource files directly, the user hands the request to the current Servlet.
- Using/indicates that the current Servlet intercepts user requests for static resources (.css,.js,.html,.jpg,.png…). However, requests for dynamic resources are not intercepted. That is, the static resource file requested by the user is not directly available.
1.5.4 Suffix Mode
The resource name at the end of the request path must carry the suffix specified in urL-pattern before the request can be processed by the current Servlet.
<servlet-name>someServlet</servlet-name>
<url-pattern>*.do</url-pattern>
Copy the code
Well, that’s all for today’s article, hoping to help those of you who are confused in front of the screen