Servlet(2)

1. Servlet life cycle
In Java, any object has a life cycle, and Servlet is no exception. The life cycle of a servlet is shown in Figure 1.
Insert picture description here

The life cycle of a servlet. According to different functions, the life cycle of a servlet can be roughly divided into four phases, namely the loading instantiation phase, the initialization phase, the operation phase [processing request] and the destruction phase.
1. Loading the instantiation stage
When the Servlet container is started, the web.xml configuration file of the project will be loaded, and the package name + class name configured in all the configured servlet-class will be parsed, and the package will be instantiated through the reflection mechanism Servlet class object corresponding to name + class name.
2. In the initialization phase,
when the client sends an HTTP request to the Servlet container to access the Servlet, the Servlet container will first parse the request and check whether the Servlet object is already in the memory. If so, use the Servlet object directly, if not, then Create a Servlet instance object, and then implement the initialization of the Servlet by calling the init() method. It should be noted that in the entire life cycle of a servlet, its init() method can only be called once.
3. Running phase [processing request]
This is the most important phase in the servlet life cycle. In this phase, the Servlet container creates a ServletRequest object representing the HTTP request and a ServletResponse object representing the HTTP response for this request, and then takes them as parameters Passed to the service() method of the servlet.
The service() method obtains the client request information from the ServletRequest object and processes the request, and generates the response result through the ServletResponse object.
In the entire life cycle of a Servlet, for each access request of a Servlet, the Servlet container will call the service() method of the Servlet once, and create new ServletRequest and ServletResponse objects, that is, the service() method is in the entire life of the Servlet It will be called multiple times during the cycle.
4. Destruction phase
When the server is shut down or the web application is removed from the container, the servlet is destroyed as the web application is closed. Before destroying the Servlet, the Servlet container will call the destroy() method of the Servlet to let the Servlet object release the resources it occupies. In the entire life cycle of a servlet, the destroy() method can only be called once.
It should be noted that once the Servlet object is created, it will reside in memory and wait for the client to access it. The Servlet object will not be destroyed until the server is shut down or the Web application is removed from the container.

package com.wangxing.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;

public class TestServlet2 extends HttpServlet{
	@Override
	public void init() throws ServletException {
		System.out.println("初始化阶段调用 init() 方法实现 Servlet 的初始化工作");
	}
	@Override
	public void service(ServletRequest req, ServletResponse resp) throws ServletException, IOException {
		System.out.println("运行阶段Servlet 容器都会调用一次 Servlet 的 service() 方法,完成请求处理");
	}
	@Override
	public void destroy() {
		System.out.println("Servlet 容器会调用 Servlet 的 destroy() 方法,以便让 Servlet 对象释放它所占用的资源");
	}
}

Insert picture description here

The relationship between the service method of Servlet and the doGet/doPost method 1. The
service method and the doGet/doPost method are both methods of the HttpServlet class
1.service(ServletRequest req, ServletResponse resp)-from the Servlet interface
2.service(HttpServletRequest req, HttpServletResponse resp)-self-defined-
3.doGet(HttpServletRequest req, HttpServletResponse resp)self-defined-
4.doPost(HttpServletRequest req, HttpServletResponse resp)self-defined
in When specifically processing the request, the Servlet container will call the .service (ServletRequest req, ServletResponse resp) method from the Servlet interface by default to make the request. The HttpServlet class will use the service (ServletRequest req, ServletResponse resp) method from the Servlet interface to call the service defined by HttpServlet itself (HttpServletRequest req, HttpServletResponse resp). This is the service defined by HttpServlet itself (HttpServletRequest) when processing the request. req, HttpServletResponse resp) is executed. At this time, the HttpServletRequest object is used in the service (HttpServletRequest req, HttpServletResponse resp) method defined by HttpServlet to obtain the hydrogen submission method, and the corresponding doGet/doPost method is called to process the request by judging the request submission method.

public abstract class HttpServlet extends GenericServlet {
    private static final String METHOD_GET = "GET";
    private static final String METHOD_POST = "POST";
    @Override
	public void service(ServletRequest req, ServletResponse resp) throws ServletException, IOException {
		HttpServletRequest arg0=(HttpServletRequest)req;
		HttpServletResponse arg1=(HttpServletResponse)resp;
		service(arg0,  arg1); 
	}
    protected void service(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
		String method=arg0.getMethod();
		if(method.equals("get")){
			doGet(arg0, arg1);
		}
		if(method.equals("post")){
			doPost(arg0, arg1);
		}
	}
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		super.doGet(req, resp);
	}
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		super.doPost(req, resp);
	}
   ..........
}

Servlet configuration virtual path mapping
Servlet multiple mapping means that the same servlet can be mapped into multiple virtual paths. In other words, the client can access the same Servlet through multiple paths. There are two ways to implement Servlet multiple mapping.
1) Configure multiple elements

<servlet>
  	<servlet-name>testservlet</servlet-name>
  	<servlet-class>com.wangxing.servlet.TestServlet3</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>testservlet</servlet-name>
  	<url-pattern>/test3</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
  	<servlet-name>testservlet</servlet-name>
  	<url-pattern>/test33</url-pattern>
  </servlet-mapping>

http://localhost:8080/TestServlet3/test3
http://localhost:8080/TestServlet3/test33
These two different paths above can access the same Servlet program.
2) Configure multiple sub-elements Configure multiple sub-elements
in the element

 <servlet>
  	<servlet-name>testservlet</servlet-name>
  	<servlet-class>com.wangxing.servlet.TestServlet3</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>testservlet</servlet-name>
  	<url-pattern>/test3</url-pattern>
  	<url-pattern>/test33</url-pattern>
  </servlet-mapping>

http://localhost:8080/TestServlet3/test3
http://localhost:8080/TestServlet3/test33
These two different paths above can access the same Servlet program.
Using wildcards
in servlet mapping paths In the actual development process, developers sometimes hope that all paths in a certain directory can access the same servlet. At this time, wildcards " "

can be used in the servlet mapping path . There are two formats of wildcard characters, as follows. 1. The format is " . Extension", for example *.do matches all URL addresses ending with .do.
Match all URL addresses ending with .hello.

<servlet>
  	<servlet-name>testservlet</servlet-name>
  	<servlet-class>com.wangxing.servlet.TestServlet3</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>testservlet</servlet-name>
  	<url-pattern>*.hello</url-pattern>
  </servlet-mapping>

http://localhost:8080/TestServlet3/abc.hello
http://localhost:8080/TestServlet3/hello.hello

2. The format is / , for example, /abc/ matches all URL addresses starting with /abc.
Match all URL addresses

<servlet>
  	<servlet-name>testservlet</servlet-name>
  	<servlet-class>com.wangxing.servlet.TestServlet3</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>testservlet</servlet-name>
  	<url-pattern>/*</url-pattern>
  </servlet-mapping>

http://localhost:8080/TestServlet3/test3
http://localhost:8080/TestServlet3/test33
http://localhost:8080/TestServlet3/abc
http://localhost:8080/TestServlet3/hello

Matches all URL addresses starting with /test.

<servlet>
  	<servlet-name>testservlet</servlet-name>
  	<servlet-class>com.wangxing.servlet.TestServlet3</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>testservlet</servlet-name>
  	<url-pattern>/test/*</url-pattern>
  </servlet-mapping>

http://localhost:8080/TestServlet3/test
http://localhost:8080/TestServlet3/test/abc It

should be noted that the two wildcard formats cannot be mixed. For example, /abc/*.do is illegal The mapping path.
In addition, when the client accesses a servlet, if the requested URL address can match multiple virtual paths, then Tomcat will adopt the most specific matching principle to find the virtual mapping path closest to the requested URL.
For example, for some mapping relationships as shown below:
Insert picture description here

When the request URL is /abc/a.html----/abc/* and /* can match this URL, Tomcat will call Servlet1.
When the request URL is /abc----/ , /abc/ and /abc Both can match this URL, and Tomcat will call Servlet3.
When the request URL is /abc/a.do-----/ , .do and /abc/ can all match this URL, Tomcat will call Servlet1.
When the request URL is /a.do--------/
and .do can match this URL, Tomcat will call Servlet2.
When the request URL is /xxx/yyy/a.do---- Both
.do and /* can match this URL, and Tomcat will call Servlet2.
Default Servlet
If the mapping path of a certain servlet is only a forward slash (/), then this servlet is the default servlet of the current Web application. When the servlet server receives an access request, if the URL of the matching element is not found in the web.xml file, it will hand over the access request to the default servlet for processing, that is, the default servlet is used to process other servlets that will not be processed Access request.
It should be noted that a default Servlet is also configured in the web.xml file in the conf folder under the Tomcat installation directory. The configuration information is as follows:

<servlet>
    <servlet-name>default</servlet-name>
    <serlet-class>org.apache.catalina.servlets.DefaultServlet</serlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

In the above configuration information, org.apache.catalina.servlets.DefaultServlet is set as the default Servlet, which works on all Web applications on the Tomcat server.
When a certain Web application in the Tomcat server does not have a default Servlet, the DefaultServlet will be used as the default Servlet. When the client accesses a static HTML file in the Tomcat server, the DefaultServlet will determine whether the HTML exists. If it exists, it will send the data back to the client in the form of a stream, otherwise it will report a 404 error.
Insert picture description here

The complete process of servlet processing user requests For
each servlet request, the Web server will create HttpServletRequest and HttpServletResponse objects before calling the service() method. Among them, the HttpServletRequest object is used to encapsulate the HTTP request message, referred to as the request object. The HttpServletResponse object is used to encapsulate the HTTP response message, referred to as the response object. The interactive process of the browser accessing the Servlet is shown in Figure 1.
Insert picture description here

In the figure, the browser first sends an HTTP request to the Web server. According to the received request, the Web server first creates an HttpServletRequest and HttpServletResponse object, and then calls the corresponding Servlet program. When the Servlet program is running, it first reads the data information from the HttpServletRequest object, then processes the request message through the service() method, and writes the processed response data to the HttpServletResponse object. Finally, the Web server reads the response data from the HttpServletResponse object and sends it to the browser.
It should be noted that during the running phase of the Web server, each Servlet will only create one instance object. For each HTTP request, the Web server will call the service (HttpServletRequest request, HttpServletResponse response) method of the requested Servlet instance and recreate it. A request object and a response object.
2. Commonly used interfaces, classes and methods
in Servlet Sun company provides a series of interfaces and classes for the development of Servlet technology. The most important interface is javax.servlet.Servlet.
1.Servlet interface

public abstract interface Servlet 

Insert picture description here

For the Servlet interface, Sun provides two default interface implementation classes: GenericServlet and HttpServlet. Among them, GenericServlet is an abstract class, which provides a partial implementation for the Servlet interface, but it does not implement HTTP request processing.

public abstract class GenericServlet implements javax.servlet.Servlet, javax.servlet.ServletConfig, java.io.Serializable {

HttpServlet is a subclass of GenericServlet. It inherits all methods of GenericServlet and provides specific operation methods for GET and POST in HTTP requests. Under normal circumstances, the written Servlet class inherits from HttpServlet, and the HttpServlet object is also used in development.
public abstract class HttpServlet extends GenericServlet { HttpServlet class contains two common methods

Insert picture description here

2.
ServletConfig interface public abstract interface ServletConfig
may need some auxiliary information when running a Servlet program, such as the encoding used by the file, the shared information using the Servlet program, etc. This information can use one or more elements in the web.xml file Configure it. When Tomcat initializes a Servlet, it will encapsulate the configuration information of the Servlet into the ServletConfig object. At this time, the ServletConfig object can be passed to the Servlet by calling the init (ServletConfig config) method.
ServletConfig is an interface that encapsulates auxiliary information when Servlet is running.
A series of methods for obtaining configuration information are defined in the ServletConfig interface.
Insert picture description here

For example: get the initialization parameter value configured in the web.xml file and the configured servlet-name value through the ServletConfig interface object.

<servlet>
    <servlet-name>testservlet4</servlet-name>
    <servlet-class>com.wangxing.servlet.TestServlet4</servlet-class>
    <!-- 配置初始化参数 -->
    <init-param>
    	<param-name>myname</param-name>
    	<param-value>zhangsan</param-value>
    </init-param>
    <init-param>
    	<param-name>mypassword</param-name>
    	<param-value>123456</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
  	 <servlet-name>testservlet4</servlet-name>
  	 <url-pattern>/test4</url-pattern>
  </servlet-mapping>

@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//得到ServletConfig接口对象
		ServletConfig config=this.getServletConfig();
		//通过ServletConfig接口对象得到web.xml文件中配置的初始化参数值
		//String getInitParameter(String name)	根据初始化参数名返回对应的初始化参数值
		String myname=config.getInitParameter("myname");
		String mypassword=config.getInitParameter("mypassword");
	System.out.println("初始化参数值myname=="+myname+",mypassword=="+mypassword);
//得到web.xml 中 <servlet-name>元素的值
	    //String getServletName()	返回 Servlet 的名字,即 web.xml 中 <servlet-name>元素的值
	    String servletName=config.getServletName();
	    System.out.println(" web.xml 中 <servlet-name>元素的值==="+servletName);
	}

Insert picture description here

3. ServletContext interface
When Tomcat is started, Tomcat will create a unique ServletContext object for each Web application to represent the current Web application, which encapsulates all the information of the current Web application. You can use this object to obtain the Servlet version of the Web application, initialize information, read resource files, and so on.
Insert picture description here

Insert picture description here

Configure web.xml

 <!-- 配置初始化信息 -->
  <context-param>
     <param-name>myname</param-name>
     <param-value>lisi</param-value>
  </context-param>
  <context-param>
  	<param-name>myage</param-name>
  	<param-value>24</param-value>
  </context-param>
  <servlet>
    <servlet-name>testservlet5</servlet-name>
    <servlet-class>com.wangxing.servlet.TestServlet5</servlet-class>
  </servlet>
  <servlet-mapping>
  	 <servlet-name>testservlet5</servlet-name>
  	 <url-pattern>/test5</url-pattern>
  </servlet-mapping>

@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//得到ServletContext接口对象
		ServletContext context=this.getServletContext();
		//得到Servlet版本号
		int majorVersion=context.getMajorVersion();
		int minorVersion=context.getMinorVersion();
		System.out.println("Servlet版本号=="+majorVersion+"."+minorVersion);
		//得到初始化信息
		//String  getInitParameter(String)	得到指定的初始化信息<context-param>
		String name=context.getInitParameter("myname");
		String age=context.getInitParameter("myage");
		System.out.println("初始化信息myname=="+name+",age=="+age);
		// 得到包含所有初始化信息名的Enumeration对象
        Enumeration<String> paramNames = context.getInitParameterNames();
        // 遍历所有的初始化参数名,得到相应的参数值并打印
        while (paramNames.hasMoreElements()) {
          String paramname = paramNames.nextElement();
          String value = context.getInitParameter(paramname);
          System.out.println("初始化信息=="+paramname+"="+value);
        }
	}

Insert picture description here

Reading resource files
in a web application In actual development, sometimes it is necessary to read some resource files in a web application, such as configuration files and log files. For this reason, some methods for reading Web resources are defined in the ServletContext interface, and these methods are implemented by the Servlet container. The Servlet container returns the I/O flow of the associated resource file or the absolute path of the resource file in the system according to the path of the resource file relative to the Web application.
Relevant methods used to obtain the resource path in the ServletContext interface.
Insert picture description here

1. Create a file named xxxxx.properties in the src directory of the project

testname=zhangsan
testage=23
testaddress=\u897F\u5B89

2. Write a servlet processing class that reads the xxxxx.properties file.

package com.wangxing.servlet;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class TestServlet6 extends HttpServlet{
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//得到ServletContext接口对象
		ServletContext context=this.getServletContext();
		//读取资源文件
		//InputStream getResourceAsStream(String path)	返回映射到某个资源文件的 InputStream 输入流对象。
		InputStream in=context.getResourceAsStream("/WEB-INF/classes/mytest.properties");
		Properties pros = new Properties();
	    pros.load(in);
	    String name=pros.getProperty("testname");
	    String age=pros.getProperty("testage");
	    String address=pros.getProperty("testaddress");
	    System.out.println("mytest.properties---testname===="+name);
	    System.out.println("mytest.properties---testage===="+age);
	    System.out.println("mytest.properties---testaddress===="+address);
	}
}

3. Configure web.xml
4. Test

Insert picture description here

Guess you like

Origin blog.csdn.net/guoguo0717/article/details/109080519