Servlet Part 2 [Servlet implementation thread safety and other details added]

1. Servlet is singleton

(1) The
browser makes multiple requests to the Servlet. Under normal circumstances, the server only creates a Servlet object , that is, once the Servlet object is created, it will reside in memory and serve subsequent requests until The server shuts down.

(2)
However, the request object and response object for each access are new. For each access request, the Servlet engine creates a new HttpServletRequest request object and a new HttpServletResponse response object, and then passes these two objects as parameters to the service () method of the Servlet it calls. Call the doXXX method separately.

Second, Servlet and thread safety

Because a type of Servlet has only one instance object, it is possible that a Servlet will process multiple requests at the same time. Is the Servlet thread-safe? Answer: "Not thread-safe." This shows that the work efficiency of Servlet is very high, but there are also thread safety problems!
So we should not create member variables in the Servlet, because there may be a thread to write to this member variable, another thread to read the member variable.

Usually, the thread safety problem will be solved by the following methods:

1. Don't create member variables in Servlet! Just create local variables!

If a variable needs to be shared by multiple users, you should add a synchronized mechanism when accessing the variable.

If a variable does not need to be shared, it is directly defined in doGet () or doPost (). There will be no thread safety issues

2. Can create stateless members! (There are no other member variables in this class, only some methods that do not involve state)

public class Servlet01 extends HttpServlet {
	private User user;
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		System.out.println("doGet()...");
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		System.out.println("doPost()...");
	}
}

class User{
	public void sayHello(){
		System.out.println("hello...");
	}
}

3. Stateful members can be created, but the state must be read-only! (Can only take values, cannot be changed)

public class Servlet02 extends HttpServlet {
	private User user;
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		System.out.println("doGet()...");
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		System.out.println("doPost()...");
	}
}

class User{
	private String name;
	private int age;
	
	public String getName() {
		return name;
	}

	public int getAge() {
		return age;
	}
}

Third, let the server create a Servlet when it starts

By default, the server will create a Servlet the first time it receives a request. But in fact, you can also configure the Servlet in web.xml so that the Servlet is created when the server starts.

在<servlet>中配置<load-on-startup>,其中给出一个非负整数!且该数越小,优先级越高!
<servlet>
    <servlet-name>Servlet03</servlet-name>
    <servlet-class>com.zuobiao.servlet.Servlet03</servlet-class>
    <load-on-startup>0</load-on-startup> 
</servlet>
    
<servlet-mapping>
    <servlet-name>Servlet03</servlet-name>
    <url-pattern>/Servlet03</url-pattern>
</servlet-mapping>

If the element is configured in the <load-on-startup>element, then when the server starts, it will load and create a Servlet instance object, and call the Servlet instance object init () method.

4. The same Servlet can be mapped to multiple URLs

(One)
<servlet>
    <servlet-name>Servlet04</servlet-name>
    <servlet-class>com.zuobiao.servlet.Servlet04</servlet-class>
    <load-on-startup>0</load-on-startup> 
</servlet>
  
<servlet-mapping>
    <servlet-name>Servlet4</servlet-name>
    <url-pattern>/AServlet</url-pattern>
    <url-pattern>/BServlet</url-pattern>
</servlet-mapping> 

No matter whether I visit http: // localhost: 8080 / AServlet or http: // localhost: 8080 / BServlet. I visited Servlet04.

Note:
<url-pattern>是<servlet-mapping>The sub-element is used to specify the access path of the Servlet, that is, the URL. It must start with "/"!

(2) URLs mapped by Servlets can use wildcards

1. The so-called wildcard is the asterisk "*". The asterisk can match any URL prefix or suffix. You can use a wildcard to name a Servlet to bind a set of URLs, for example:

路径匹配:
<url-pattern>/servlet/*<url-patter>:/servlet/a、/servlet/b,都匹配/servlet/*;
扩展名匹配:
<url-pattern>*.do</url-pattern>:/abc/def/ghi.do、/a.do,都匹配 *.do;
啥都匹配:
<url-pattern>/*<url-pattern>:匹配所有URL;

Please note that wildcards are either prefixes or suffixes, and cannot appear in the middle of the URL, nor can they be wildcards only. For example: /.do is wrong, because the asterisk appears in the middle of the URL. . * Is also wrong, because at most one wildcard can appear in a URL.

2. Wildcards are a way of fuzzy matching URL, if there is more specific <url-pattern>, then the access path will match the specific <url-pattern>.

1、看谁的匹配度高,谁就被选择
2、*.扩展名的优先级最低

E.g:

<servlet>
	<servlet-name>hello1</servlet-name>
	<servlet-class>com.zuobiao.servlet.Hello1Servlet</servlet-class>
</servlet>
<servlet-mapping>
	<servlet-name>hello1</servlet-name>
	<url-pattern>/servlet/hello1</url-pattern>
</servlet-mapping>
	
<servlet>
	<servlet-name>hello2</servlet-name>
	<servlet-class>com.zuobiao.servlet.Hello2Servlet</servlet-class>
</servlet>
<servlet-mapping>
	<servlet-name>hello2</servlet-name>
	<url-pattern>/servlet/*</url-pattern>
</servlet-mapping>

When the access path http://localhost:8080/hello/servlet/hello1, the path that is because access hello1 the match <url-pattern>, and the match hello2 <url-pattern>, but because of hello1 <url-pattern>no wildcard matching priority so that the set hello1.

(3) URLs mapped by Servlet can use wildcards and Servlet can be mapped to multiple URLs:

1. What programming language is used to hide the website [.php, .net, .asp actually access the same resource]

2. The specific suffix declares the copyright [company abbreviation]

Fifth, the inheritance of the web.xml file (just for better understanding and thus compared to inheritance)

1. Each complete JavaWeb application requires web.xml, but we do not know that all web.xml files have a common parent file, which is in the Tomcat conf / web.xml path.

2. The content in \ conf \ web.xml is equivalent to the web.xml written in each project, which is the parent file of all web.xml.

3. In \ conf \ web.xml, there is also a default Servlet and a Servlet with the suffix jsp. Some source codes are as follows:

 <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>
        <servlet-name>jsp</servlet-name>
        <servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
        <init-param>
            <param-name>fork</param-name>
            <param-value>false</param-value>
        </init-param>
        <init-param>
            <param-name>xpoweredBy</param-name>
            <param-value>false</param-value>
        </init-param>
        <load-on-startup>3</load-on-startup>
</servlet>

<servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>jsp</servlet-name>
        <url-pattern>*.jsp</url-pattern>
</servlet-mapping>

a. The default Servlet matches all URLs, that is, when the URL path accessed by the user does not match a page, the Servlet named default is executed, and if it can't handle it, it displays 404. In fact, we are also executing this Servlet when accessing index.html.

b. Any access with URL suffix jsp will execute a Servlet named jsp

Novice Java, if there are errors, please correct me!

Guess you like

Origin www.cnblogs.com/Java-biao/p/12724553.html