1. Servlet overview
1. Dynamic web resource development technology provided by sun company. The essence is the previous Java applet, which requires that this applet must implement the Servlet interface so that the server can call it.
2. Two steps to develop a servlet
*Experiment: Quick Start of Servlet
(1) Step 1: Write a Java program to implement the Servlet interface (here directly inherits the default implementation class GenericServlet)
package cn.itheima;import java.io.*;import javax.servlet.*;public class FirstServlet extends GenericServlet{public void service(ServletRequest req, ServletResponse res) throws ServletException, java.io.IOException{res.getOutputStream().write("My FirstServlet!".getBytes());}}(2) In addition to putting the compiled .class with packages under WEB-INF/classes, you must also configure the web.xml registration Servlet of the web application.
<servlet> <servlet-name>FirstServlet</servlet-name> <servlet-class>cn.itheima.FirstServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>FirstServlet</servlet-name> <url-pattern>/FirstServlet</url-pattern> </servlet-mapping>
3. Develop Servlets with MyEclipse
2. Detailed description of Servlet
1. Life cycle: When a thing is born and dies, what it will inevitably do during its existence. Putting it together is the declaration cycle of the thing.
2. Servlet life cycle: Generally, when the servlet is accessed for the first time, an object is created in memory, and the init() method is called immediately after creation to initialize. For each request, the service(req,resp) method is used to process the request. At this time, the request information will be encapsulated with the Request object, and the Response object (originally empty) represents the response message, which is passed into the service method for use. When the service method is processed, the return server server organizes a response message to be returned to the browser based on the information in the Response. The servlet is not destroyed after the response is completed and stays in memory and waits for the next request. Until the server is closed or the web application is removed from the virtual host, the servlet object is destroyed and the destroy() method is called before it is destroyed to do something afterwards.
3. Inheritance structure of Servlet interface
Servlet interface: defines the method that a servlet should have, and all servlets should implement this interface directly or indirectly.
|
|----GenericServlet: The default implementation of the Servlet interface, a general Servlet, this is an abstract class, most of the methods are implemented by default, only the service method is an abstract method that needs to be implemented by the inheritor himself.
|
|-----HttpServlet: A Servlet optimized for the HTTP protocol is inherited from the GenericServlet class, and the service abstract method is implemented. The default implementation determines the request method of the request, and calls different doXXX() methods according to the different request methods. Usually we can directly inherit HttpServlet
4. Things to note when registering Servlets in web.xml
4.1 Register a Servlet using the <servlet><servlet-mapping> tag
<servlet> <servlet-name>FirstServlet</servlet-name> <servlet-class>cn.itheima.FirstServlet</servlet-class>
Note: What you want here is the full class name of a servlet, not the file path that contains .java or .class extensions
</servlet> <servlet-mapping> <servlet-name>FirstServlet</servlet-name> <url-pattern>/FirstServlet</url-pattern> </servlet-mapping>
4.2 One <servlet> can correspond to multiple <servlet-mapping>
4.3 You can use the * match character to configure <serlvet-mapping>, but be careful that it must be a path starting with *.do or / that ends with /*.
~ Due to the introduction of match characters, it is possible that a virtual path will correspond to multiple servlet-mappings. At this time, which one is most similar to which servlet is looking for, and the *.do level is the lowest.
4.4 You can configure the <load-on-startup> sub-label for <servlet>, specifying that the servlet is loaded with the server startup, and the configured values specify the order of startup
servlet><servlet-name>invoker</servlet-name><servlet-class>org.apache.catalina.servlets.InvokerServlet</servlet-class><load-on-startup>2</load-on-startup></servlet>
4.5 Default servlet: If the external access path of a servlet is set to /, the servlet is a default servlet, and other servlets do not process requests.
~The default servlet is configured in conf/web.xml, and the access to static resources and the output of error pages are handled by this default servlet. If we write a default servlet ourselves to overwrite the default servlet in Dad's web.xml, it will cause the static web resources to be inaccessible. Therefore, configuration is not recommended.
4.6 thread safety issues of servlet
4.6.1 Because usually, a servlet has only one instance in memory to process the request, when multiple requests are sent, multiple threads will operate the servlet object, which may lead to thread safety problems.
(1) There may be thread safety issues with servlvet member variables
*Experiment: Define a member variable inti=0; perform i++ operation in doXXX() method and output i value to the client. At this time, thread safety issues may be caused due to delay.
(2) When servet operates resource files, multiple threads operate the same file and cause thread safety issues
*Experiment: The request comes with a parameter, the servlet writes the request parameter to a file, then reads the file, and prints the read value to the client. There may be thread safety issues
4.6.2 Solution
(1) Use synchronous code blocks to solve the problem. The disadvantage is that the synchronous code block can only process one request at the same time, which is very inefficient, so the synchronous code block only needs to contain core code that causes thread safety issues.
(2) Implement the SingleThreadModel interface for this servlet. This is a tag interface. The marked servlet will save a servlet pool in memory. If a thread comes and there is no servlet object processing in the pool, a new one will be created. If there are free servlets in the pool, use them directly. This doesn't really solve thread safety issues. This interface has been abandoned.
(3) Both solutions are not perfect, so try not to appear member variables in the servlet.
3. ServletConfig
1. Objects representing the configuration of servlets, which can be configured in <servlet> in web.xml
<servlet> <servlet-name>Demo5Servlet</servlet-name> <servlet-class>cn.itheima.Demo5Servlet</servlet-class> <init-param> <param-name>data1</param-name> <param-value>value1</param-value> </init-param> </servlet>
Then use this.getServletConfig() in the servlet to get the ServletConfig object. This object provides getInitParameter() and getInitParameterNames() methods, which can traverse the configuration items in the configuration.
If you don't want to write dead content in the servlet, you can configure it here.
4. ServletContext
1. The object representing the current web application.
2. Used as a domain object, transfer data between different servlets, and its scope is the entire web application.
Lifecycle: Create a ServletContext object representing the entire web application when the web application is loaded into the container. When the server is closed or the web application is removed from the container, the ServletContext object is destroyed.
~Domain: A domain is understood as a box, where data can be placed. Since a domain is called a domain, it has a visible range. The data in this domain can be operated within this range. Such an object is called a domain object.
3. In web.xml, you can configure the initialization parameters of the entire web application and use ServletContext to obtain
<context-param><param-name>param1</param-name><param-value>pvalue1</param-value></context-param>this.getServletContext().getInitParameter("param1")this.getServletContext().getInitParameterNames()4. Forwarding between different servlets
this.getServletContext().getRequestDispatcher("/servlet/Demo10Servlet").forward(request, response);After the method execution is completed, the service will return to the server, and the server will call the target servlet, where the request will be recreated and the data of the previous request will be copied into it.
5. Read resource files
5.1 Since the relative path is the directory started by the Java virtual machine by default, we will directly write the relative path relative to the tomcat/bin directory, so we cannot get the resources. If written as an absolute path, the absolute path is wrong when the project is published to another environment.
5.2 In order to solve this problem, ServletContext provides this.getServletContext().getRealPath("/1.properties"), which gives a virtual path to the resource and will return the real path of the resource in the current environment. this.getServletContext().getResourceAsStream("/1.properties"), which returns the virtual path of a resource to the stream of the real path of the resource.
5.3 When obtaining resource files under non-servlets, there is no ServletContext object used, and only class loaders can be used at this time.
classLoader.getResourceAsStream("../../1.properties"), this method uses the class loader to load resources directly into memory, which has problems with update delays, and if the file is too large, it takes up too much memory.
classLoader.getResource("../1.properties").getPath() directly returns the real path of the resource, without the problem of update delay.
Summarize
The above is all the content of this article about briefly discussing the technical foundation of Servlet development, and I hope it will be helpful to everyone. Interested friends can continue to refer to this site:
Basic analysis of Servlet session technology
As well as other related topics on this website, if there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!