The call diagram for the Servlet
Previously we have learned about the life cycle of servlets. Let’s draw the call diagram of servlets according to the life cycle of servlets to deepen our understanding
The details of the Servlet
A registered Servlet can be mapped multiple times
The same Servlet can be mapped to multiple urls.
<servlet>
<servlet-name>Demo1</servlet-name>
<servlet-class>zhongfucheng.web.Demo1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Demo1</servlet-name>
<url-pattern>/Demo1</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Demo1</servlet-name>
<url-pattern>/ouzicheng</url-pattern>
</servlet-mapping>
Copy the code
Whenever I visit http://localhost:8080/Demo1 or http://localhost:8080/ouzicheng. I visited Demo1.
Servlet mapped urls can use wildcards
Wildcards have two formats:
- *. Extensions
- It starts with a forward slash (/) and ends with a “/*”.
Match all
Matches the.jsp extension
If the *. Extension and the forward slash (/) and end with “/*” are both wildcards, which one matches?
- Whoever is the best match will be selected
*.
The extension has the lowest priority
Servlet mapped urls can use wildcards and servlets can be mapped to multiple urls:
- PHP,.net, and.asp actually access the same resource.
- 4. A company abbreviation to declare copyright with a specific suffix.
<servlet>
<servlet-name>Demo1</servlet-name>
<servlet-class>zhongfucheng.web.Demo1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Demo1</servlet-name>
<url-pattern>*.jsp</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Demo1</servlet-name>
<url-pattern>*.net</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Demo1</servlet-name>
<url-pattern>*.asp</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Demo1</servlet-name>
<url-pattern>*.php</url-pattern>
</servlet-mapping>
Copy the code
Servlets are singletons
Why are servlets singletons
When a browser requests a Servlet multiple times, the server typically creates only one Servlet object, meaning that once created, the Servlet object resides in memory to service subsequent requests until the server is shut down.
Each access request object and response object are new
For each access request, the Servlet engine creates a new HttpServletRequest request object and a new HttpServletResponse response object, and then passes both objects as parameters to the service() method of the Servlet it calls, The service method then calls the doXXX method, depending on the request.
Thread safety
When multiple users access the Servlet, the server creates a thread for each user. Thread-safety issues arise when multiple users concurrently access a Servlet shared resource.
Principle:
- If a variable needs to be shared by multiple users, use synchronized (object){} when accessing the variable.
- If a variable does not need to be shared, it is defined directly in doGet() or doPost(). There are no thread-safety issues
load-on-startup
If an element is configured in the element, the WEB application starts up by loading and creating the instance object of the Servlet and calling the init() method of the Servlet instance object.
Function:
- Write an InitServlet for your Web application that is configured to load at startup to create the necessary database tables and data for the entire Web application
- Complete some scheduled tasks [Regularly write logs, regularly back up data]
Accessing any resource on the Web is accessing a Servlet
When you start Tomcat, you type http://localhost:8080 into the url. Why does the Tomcat Kitten page appear?
This is served for you by the default Servlet!
- Let’s start by looking at the configuration in the web.xml file, which configures a default Servlet
<servlet>
<servlet-name>default</servlet-name>
<servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>0</param-value>
</init-param>
<init-param>
<param-name>listings</param-name>
<param-value>false</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
Copy the code
- What is the default Servlet? Any URL that does not have a matching element in the web.xml file will have access requests handled by the default Servlet, which is used to handle access requests that none of the other servlets handle
- Since I said that accessing any resource on the web is accessing a Servlet, I am accessing static resources (local images, local HTML files) and accessing the DefaultServlet (DefaultServlet).
- Confirm: access to local images is accessible when I don’t manually configure the default Servlet
- Now I configure a default Servlet myself, and Demo1 is the default Servlet I configured manually, overriding the default Servlet configured for web.xml
<servlet>
<servlet-name>Demo1</servlet-name>
<servlet-class>zhongfucheng.web.Demo1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Demo1</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
Copy the code
- Let’s go back to the image and see what the Demo1 Servlet says
- Summary: ** Whenever you access a resource on the Web (including JSP), you are accessing a Servlet. ** When you visit a static image or web page without manually configuring the default Servlet, the default Servlet will look for that image or web page in your web site and return it to the browser if it exists, or a 404 error if it does not exist
ServletConfig object
What is the ServletConfig object used for?
The initialization parameters configured in web.xml can be read from this object.
Now the question is, why do we put parameter information in a web.xml file? We can define parameter information directly in the program, so what good is it to have it in the web.xml file?
The benefit: It makes your application more flexible (just change the requirements, change the configuration file web.xml, and leave the code unchanged).
Gets the parameter information configured in the web. XML file
- Configure a parameter for the Demo1 Servlet with the name and the value zhongfucheng
<servlet>
<servlet-name>Demo1</servlet-name>
<servlet-class>zhongfucheng.web.Demo1</servlet-class>
<init-param>
<param-name>name</param-name>
<param-value>zhongfucheng</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>Demo1</servlet-name>
<url-pattern>/Demo1</url-pattern>
</servlet-mapping>
Copy the code
- The ServletConfig object is obtained in the Servlet, and the parameters configured in the web.xml file are obtained from the ServletConfig object
ServletContext object
What is a ServletContext object?
When Tomcat is started, a ServletContext object is created. It represents the current Web site
What does a ServletContext do?
- ServletContext Since ServletContext represents the current Web site, all servlets share a ServletContext object, so servlets can communicate with each other using a ServletContext.
- ServletConfig takes parameter information configured for a single Servlet, and ServletContext takes parameter information configured for the entire Web site
- Use the ServletContext to read the resource file for the Web site
- Implement Servlet forwarding [ServletContext forwarding is not much, mainly request forwarding]
Servlets communicate with each other
The ServletContext object can be called a domain object
One question that might arise at this point is, what is a domain object? A domain object can simply be thought of as a container.
To implement communication between servlets, use the setAttribute(String Name,Object obj) method of the ServletContext. The first parameter is the keyword and the second parameter is the Object you want to store
- This is the code for Demo2
// Get the ServletContext object
ServletContext servletContext = this.getServletContext();
String value = "zhongfucheng";
//MyName as the key, value as the value of the field object
servletContext.setAttribute("MyName", value);
Copy the code
- This is the code for Demo3
// Get the ServletContext object
ServletContext servletContext = this.getServletContext();
// Get the value of the object stored in the domain by keyword
String value = (String) servletContext.getAttribute("MyName");
System.out.println(value);
Copy the code
- By accessing Demo3, you can obtain the information stored by Demo2, which enables communication between multiple servlets
Gets web site configuration information
If I wanted all servlets to have access to the database, I couldn’t configure it in every Servlet in the web.xml file. That would be too much code! And it can be very verbose.
- The web. XML file allows you to configure parameter information for the entire site [all servlets can access this parameter information]
<context-param>
<param-name>name</param-name>
<param-value>zhongfucheng</param-value>
</context-param>
Copy the code
- Demo4 code
// Get the ServletContext object
ServletContext servletContext = this.getServletContext();
// Get the value by name
String value = servletContext.getInitParameter("name");
System.out.println(value);
Copy the code
- Let’s see if Demo3 gets the same code
// Get the ServletContext object
ServletContext servletContext = this.getServletContext();
// Get the value by name
String value = servletContext.getInitParameter("name");
System.out.println(value);
Copy the code
Reading resource files
The first way:
- Now I’m going to read the 1.png image from Servlet111
- The way we did it, the code would look like this.
FileInputStream fileInputStream = new FileInputStream("1.png");
System.out.println(fileInputStream);
Copy the code
- When we visited, something went wrong! Couldn’t find 1.png file
- Why is that? We used to read the file, if the program and the file in the same package name, can be directly obtained by the file name! The reason is simple: we used to write programs that ran through the JVM, but now we run them through Tomcat
- According to the Web directory specification, the class files compiled by servlets are stored in the WEB-INF\classes folder
- Now that we know we need to go into the classes directory to read the file, we change our code to the following
FileInputStream fileInputStream = new FileInputStream("D:\\zhongfucheng\\web\\WEB-INF\\classes\\zhongfucheng\\web\\1.png");
System.out.println(fileInputStream);
Copy the code
- When you read it again, you will find that you can get the file.
- But now the problem is that I have to write the absolute path when I read the file, which is too inflexible. Imagine if I moved this file-reading module to another Web site, and my code would have to change again [because the web site name is different].
- We can avoid modifying the code by reading the ServletContext because the ServletContext object is generated based on the current Web site
- The code looks like this:
// Get the ServletContext object
ServletContext servletContext = this.getServletContext();
// Call the ServletContext method to get the stream to read the file
InputStream inputStream = servletContext.getResourceAsStream("/WEB-INF/classes/zhongfucheng/web/1.png");
Copy the code
The second way:
- It would be much simpler if my files were in a Web directory! , can be obtained directly from the file name
- The code is shown below
// Get the ServletContext object
ServletContext servletContext = this.getServletContext();
// Call the ServletContext method to get the stream to read the file
InputStream inputStream = servletContext.getResourceAsStream("2.png");
Copy the code
The third way:
Read the resource file through the class loader.
- My files are in the SRC directory.
- The code is shown below
// Get the class loader
ClassLoader classLoader = Servlet111.class.getClassLoader();
// Get the read file stream from the class loader
InputStream inputStream = classLoader.getResourceAsStream("3.png");
Copy the code
- My files are in a package in the SRC directory
- Add package name path as follows.
// Get the class loader
ClassLoader classLoader = Servlet111.class.getClassLoader();
// Get the read file stream from the class loader
InputStream inputStream = classLoader.getResourceAsStream("/zhongfucheng/web/1.png");
Copy the code
Rule: If the file is too large, it cannot be read by the classloader, resulting in an overflow of memory
Open source project (5.8K STAR) :Github.com/ZhongFuChen…
If you want to follow my updated articles and shared dry goods in real time, you can search Java3y on wechat.
The content of the PDF document is typed by hand. If you don’t understand anything, you can ask me directly (the official account has my contact information).