learning points
- Introduction to servlet concepts and related interfaces
- servet execution process
- servlet path mapping
- Default servlet --apply
- servlet life cycle (emphasis) -- understanding (emphasis)
- Servlet autoloading
- Servlet thread safety
- servletConfig object
- Detailed explanation of Servlet related interfaces
- ServletContext object -- knowledge points
How to develop servlets
Servlet development process
-
Write a common class that inherits the HttpServlet class
-
Override doxx method
-
Configure the servlet in web.xml
-
<servlet> <servlet-name>LoginServlet</servlet-name> servlt alias <servlet-class>dx.servlet.LoginServlet</servlet-class> servlet The fully qualified class name string of </servlet> <servlet-mapping> <servlet-name>LoginServlet</servlet-name> specify servlt alias <url-pattern>/hello</url-pattern> assign one url for users to call </servlet-mapping>
-
Servlet execution process
- The browser enters the URL and hits Enter, the browser first searches the host.txt file on the local machine, this file saves some default domain name and ip mapping.
- If the local machine does not have a specified mapping, it will send a request to the dns server provided by the telecom operator to obtain the mapping relationship and return the corresponding ip address
- The browser replaces the domain name in the URL entered by the user with the ip address, and then the resource is officially accessed.
- Send a request to the real resource, the request will be received by the web server
- The Web server will parse the request and get the resource path accessed
- The Web server will first look for dynamic resources (servlets) according to the address
- The Web server will look in the web.xml file for which servlet's url-pattern matches the address accessed by the user
- turn up
- Will find the corresponding servlet-name
- Find the corresponding servlet-class according to servlet-name
- Find the class according to the fully qualified class name inside, use reflection to create a servlet object
- Call the service method of the object, encapsulate the content of the request with HttpservletRequest, encapsulate the content of the response with HttpServletResponse as a parameter, and pass it into the service method
- The service method calls the corresponding doxxx method according to the request method
- can't find
- If there is no corresponding servlet to process the request, it will look for static resources according to the path
- If found, show the resource
- If not found, display 404
- turn up
- Search rules: find dynamic resources first, followed by static resources
Servlet mapping path
Configuration rules for mapping paths: 1. Exact matching 2. Fuzzy matching
exact match
- The relationship between url and servlet is one-to-one
- Note: A servlet can be configured with multiple url s
- It is written as follows:
- /app1
- /app1.action
- /app.do
- /app1.html: pseudo-static
- /user/app1
- No matter how it is written, it will be read as String type
fuzzy matching
- The relationship between url and servlet is many-to-one
- It is written as follows:
- /* Multiple url s match app1servlet
- *.do url s ending in .do match app1servlet
- /user/* URLs starting with /user/ match app1servlet
- The following spelling is not allowed, it must be written in the above format
- /h* ❌
- /h.* ❌
Think: Is the effect of / and /* the same?
- Works similarly, but with different priorities
- / belongs to exact match, /* belongs to fuzzy match
- / has higher priority
- (this answer is not authoritative)
servlet default path
-
Phenomenon: If you enter URL knowledge/, index.jsp will be opened by default
-
Function: By setting the default path, you can achieve the effect of entering the domain name to access the entry interface (home page)
-
Principle: View the web.xml file in the conf directory of tomcat, the code is as follows
-
<servlet> <servlet-name>default</servlet-name> <servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
-
The implementation of this function is performed by a servlet named DefaultServlet
-
The default servlet will look for the welcome page list in the configuration file by default, if found, it will be displayed, if not found, it will display 404
-
<welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> </welcome-file-list>
How to modify the home page?
-
method one
- You can directly modify the welcome-file-list code in the web.xml file under tomcat
- Not recommended, because tomcat's configuration file is for all projects.
-
Method Two
-
Just add this configuration information in the web.xml file of your own project, the modification is only for the current project
-
<welcome-file-list> <welcome-file>hello.html</welcome-file> </welcome-file-list>
-
-
Note: If the url of the servlet configured by yourself is also /, then the configuration of the default servlet will be overwritten
Servlet life cycle
object life cycle
- Create objects using reflection or new
- Use the set method or code block to initialize properties
- call member method
- Lost references are recycled and destroyed
Four life cycle methods of Servlet
- Constructor After the server is started, when the user accesses for the first time 1 time
- The init method is executed once after the object is created
- doxx method is executed N times when the user accesses
- destroy method 1 time when the server is closed
Notice:
- Servlet s are singleton multithreaded
- The creation of the Servlet object is delayed until the user first accesses it
Automatic loading of servlets
-
By default, the object of the servlet is created when the user accesses it for the first time. We hope that the object will be created with the startup of tomcat
-
Implement automatic loading:
<load-on-startup>1</load-on-startup>
-
Notice:
- In the code that configures the automatic loading information, you can specify a positive integer. The smaller the value, the higher the priority of startup.
- If you need to configure but don't know what value to configure, we specify 1
-
servlet is a singleton multi-threaded, reflecting the singleton pattern of the design pattern
Servlet multi-threaded concurrency problem
- If you define member variables in a servlet and write operations in doxx methods, there may be thread safety issues.
- Solution: lock the code that may have problems
ServletConfig object
- Role: The ServletConfig object encapsulates the configuration information of the servlet
- Create: Created by tomcat, created when the init method is executed.
- Get: After tomcat is created, the object is passed into the init method as a formal parameter, so it can be used directly in the init method
- Note: Each servlet will generate a servletConfig object, and servlets will not cross access to other Config objects
for example
-
Configure initialization parameters
-
<servlet> <servlet-name>app4</servlet-name> <servlet-class>com.bjpowernode.servlet.App4Servlet</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>app4</servlet-name> <url-pattern>/app4</url-pattern> </servlet-mapping>
-
Get initialization parameters
-
// 1. Get the servlet-name attribute String name = config.getServletName(); // 2. Get the initialization parameters of the servlet String debug = config.getInitParameter("debug"); String listings = config.getInitParameter("listings"); // 3. Get all initialization parameters Enumeration<String> names = config.getInitParameterNames(); while (names.hasMoreElements()){ String key = names.nextElement(); String value = config.getInitParameter(key); }
ServletContext object
-
ServletContext: the context object of the servlet, the running environment of the servlet
-
Create: tomcat is created when the web container starts, only one will be created
-
Obtain:
-
In the init method, get it through getServletContext() of the servletConfig object
-
In the doxx method, get it through getServletContext() of the Request object
ServletContext context = req.getServletContext();
-
The core API of the ServletContext object
-
Domain related methods:
- getAttribute(String key): Get the value according to the key
- setAttribute(String key,Object value): Add a key-value pair
- removeAttribute(String key): delete the key-value pair according to the key
-
Get initialization parameters related:
-
getInitParameter(String name): Get the value according to the initialization parameter name
<!-- web.xml Configure global initialization parameters in --> <context-param> <param-name>user</param-name> <param-value>root</param-value> </context-param>
// Get global initialization parameters String user = context.getInitParameter("user");
-
getInitParameterNames(): Gets a collection of all initialization parameter names
-
-
other
- getContextPath() gets the path of the web application
- getRealPath(String path) Get the real path of the resource
- getResourceAsStream(String path) Get the content according to the relative path of the resource, and get the content in the way of its own input stream
- getRequestDispatcher() uses forwarding to jump to the page
get real path
-
In web projects, absolute paths are required when using streams to read resources, and resources are often not found in relative paths.
// 1. Get the servletContext object ServletContext context = req.getServletContext(); // 2. Create an input stream to read the resource file //method one String path = context.getRealPath("/upload/db.properties");//The parameter here is a relative path FileInputStream fis = new FileInputStream(path); //Method 2 InputStream fis = context.getResourceAsStream("/upload/db.properties"); // 3. Create a Properties object to load the file content Properties properties = new Properties(); properties.load(fis); // 4. Get the file content String user = properties.getProperty("user"); String pass = properties.getProperty("pass");
-
Configuration files are generally stored in the resources directory, and will eventually be compiled under the classes directory, so the configuration files in the classes directory can generally use the following path: /WEB-INF/classes/db2.properties
-
If you read the files in the classes directory, you can use the class loader of the current class to read:
InputStream is = MyServlet.class.getClassLoader().getResourceAsStream("db2.properties");
domain object
- Role: Shared space provided for server programs to share data
- 4 domain objects (ordered from smallest to largest)
- pageContext
- request
- session
- servletContext
- The structure of domain object is Map type <string, object>
- Common method
- getAttribute(String key): Get the value according to the key
- setAttribute(String key,Object value): Add a key-value pair
- removeAttribute(String key): delete the key-value pair according to the key
- The scope of the servletContext domain object is the entire project, and each running project will generate a context object.
Forward
-
Two implementations of forwarding
context.getRequestDispatcher("/app11").forward(req,resp); req.getRequestDispatcher("/app1.html").forward(req,resp);
-
Example
// 1. Get the servletContext object ServletContext context = req.getServletContext(); // 2. Use forwarding to access app1.html context.getRequestDispatcher("/app1.html").forward(req,resp); // 3. Use forwarding to access the servlet context.getRequestDispatcher("/app11").forward(req,resp); // 4. Use forwarding to access baidu //java.lang.IllegalArgumentException: Path [https://www.baidu.com] does not start with '/' character // The forwarded resources can only be resources within the project context.getRequestDispatcher("https://www.baidu.com").forward(req,resp); // 5. Use requests to implement forwarding operations req.getRequestDispatcher("/app1.html").forward(req,resp);
-
The difference between forwarding and redirecting:
-
Forwarded resources can only be internal to the project (static and dynamic resources)
Redirected resources can be internal or external
-
-
Forwarding is only requested once, and forwarding to access new resources uses the original request and response, so it is only requested once
The redirection request is made twice, and the redirection to access the new resource uses a new request and response, so the request is made twice
-
Forwarding access to resources will not cause the url in the address bar to change
Redirecting access to a resource will cause the url in the address bar to change
-