Servlet Part II [Servlet Call Diagram, Servlet Details, ServletConfig, ServletContext]

Servlet call graph

We have learned the life cycle of servlets before. We draw the call diagram of servlets according to the life cycle of servlets to deepen our understanding

 

 

Servlet details

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>

No matter if I visit http://localhost:8080/Demo1 or http://localhost:8080/ouzicheng. All I visit are Demo1.

 

 

 

 

Servlet mapping URLs can use wildcards

Wildcards have two formats:

  1. *.extension name
  2. Start with a forward slash (/) and end with "/*".

match all

 

 

matches those with a .jsp extension

 

 

If the *. extension and the forward slash (/) start and end with "/*" both wildcards appear, which one is matched?

  1. Whoever has the highest match will be selected
  2. *.Extensions have the lowest priority

Servlet mapped URLs can use wildcards and servlets can be mapped to multiple URLs:

  1. What programming language is the hidden website written in [.php,.net,.asp actually access the same resource]
  2. Claim copyright with a specific suffix [company abbreviation]

		 <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>



Servlets are singletons

Why servlets are singletons

The browser makes multiple requests to the servlet . In general, the server only creates one servlet object , that is, once the servlet object is created , it will reside in memory and serve subsequent requests until the server is shut down .

The request object and the response object are new each time you visit

For each access request , the servlet engine will create a new HttpServletRequest request object and a new HttpServletResponse response object , and then pass these two objects as parameters to the service() method of the servlet it calls , and the service method will then be based on the request method. Call the doXXX methods respectively .

thread safety issues

When multiple users access the servlet, the server creates a thread for each user . Thread safety issues arise when multiple users access servlet shared resources concurrently .

in principle:

  1. If a variable needs to be shared by multiple users , the synchronization mechanism should be added when accessing the variable synchronized (object){}
  2. If a variable does not need to be shared , it is defined directly in doGet() or doPost() . This will not cause thread safety issues

load-on-startup

If an element is configured in the element, then when the WEB application starts , it will load and create the instance object of the servlet , and call the init() method of the servlet instance object .

 

 

 

 

effect:

  1. Write an InitServlet for the web application, this servlet is configured to load at startup, and creates the necessary database tables and data for the entire web application
  2. Complete some timed tasks [write logs regularly, backup data regularly]

Accessing any resource on the web is accessing a servlet

When you start Tomcat, you type http://localhost:8080 on the URL. Why does the page of the Tomcat kitten appear?

This is served by the default servlet for you !

  • Let's first look at the configuration in the web.xml file. The web.xml file is configured with 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>


  • What is the default servlet? If the URL of the matching element cannot be found in the web.xml file , their access requests will be handed over to the default servlet for processing , that is, the default servlet is used to process access requests that all other servlets do not handle.
  • Since I said that accessing any resource on the web is accessing the Servlet, then I am accessing the static resource [local image, local HTML file] and also accessing this default Servlet [DefaultServlet]
  • To confirm: when I do not manually configure the default servlet, accessing local images is accessible

 

 

  • Now I configure a default Servlet by myself, Demo1 is the default Servlet I manually configured, overwriting the default Servlet configured in 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>


  • Next, I will continue to visit the picture just now. At this time, the output is the content written by the Servlet Demo1.

 

 

  • Summary: **No matter what resource [including JSP] is accessed in the web, it is accessing Servlet. **When the default servlet is not manually configured, and you visit a static image or a static web page, the default servlet will look for the image or web page in your web site .

ServletConfig object

What is the use of the ServletConfig object?

Through this object, the initialization parameters configured in web.xml can be read.

Now the question is, why do we put the parameter information in the web.xml file ? We can define parameter information directly in the program. What is the benefit of getting it in the web.xml file ?

The advantage is: it can make your program more flexible [replace the requirements, just change the configuration file web.xml, the program code does not need to be changed]

Get the parameter information configured by the web.xml file

  • Configure a parameter for the Servlet Demo1, the parameter name is name and the value is 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>

  • Obtain the ServletConfig object in the Servlet, and obtain the parameters configured in the web.xml file through the ServletConfig object

ServletContext object

What is a ServletContext object?

When Tomcat starts, it creates a ServletContext object. it represents the current web site

What is the use of ServletContext?

  1. Since ServletContext represents the current web site, all servlets share a ServletContext object , so servlets can communicate through ServletContext .
  2. ServletConfig obtains the parameter information of a single servlet, and ServletContext can obtain the parameter information of the entire web site
  3. Use ServletContext to read resource files of web sites
  4. Realize Servlet forwarding [Not much forwarding with ServletContext, mainly with request forwarding]

Communication between servlets

ServletContext objects can be called domain objects

There may be a question here, what is the domain object? In fact, the domain object can be simply understood as a container [similar to the Map collection]

To achieve communication between servlets, you need to use the setAttribute(String name, Object obj) method of ServletContext. The first parameter is the keyword, and the second parameter is the object you want to store.

  • Here is the code for Demo2

        //获取到ServletContext对象
        ServletContext servletContext = this.getServletContext();

        String value = "zhongfucheng";

        //MyName作为关键字,value作为值存进   域对象【类型于Map集合】
        servletContext.setAttribute("MyName", value);


  • This is the code for Demo3

        //获取ServletContext对象
        ServletContext servletContext = this.getServletContext();

        //通过关键字获取存储在域对象的值
        String value = (String) servletContext.getAttribute("MyName");

        System.out.println(value);

  • Accessing Demo3 can obtain the information stored in Demo2, so as to realize the communication between multiple servlets

 

 

Get information about web site configuration

If I want all servlets to be able to obtain information about connecting to the database, it is impossible to configure each servlet in the web.xml file, so the amount of code is too large! And it will appear very verbose and redundant.

  • The web.xml file supports configuration parameter information for the entire site [ all servlets can get this parameter information ]

    <context-param>
        <param-name>name</param-name>
        <param-value>zhongfucheng</param-value>
    </context-param>

  • Demo4 code

        //获取到ServletContext对象
        ServletContext servletContext = this.getServletContext();

        //通过名称获取值
        String value = servletContext.getInitParameter("name");
        System.out.println(value);


 

 

  • Try to see if Demo3 can get it, the same code

        //获取到ServletContext对象
        ServletContext servletContext = this.getServletContext();

        //通过名称获取值
        String value = servletContext.getInitParameter("name");
        System.out.println(value);

 

 

read resource file

The first way:

  • Now I want to read 1.png image through Servlet111

 

 

  • As we used to, the code should look like this.

        FileInputStream fileInputStream = new FileInputStream("1.png");
        System.out.println(fileInputStream);

  • When we visited, something went wrong! Says 1.png file not found

 

 

  • Why is this? When we read the file before, if the program and the file are in the same package name, we can get it directly from the file name ! , the reason is very simple, the programs we wrote in the past were all run through the JVM, and now we run through Tomcat
  • According to the web directory specification, the compiled class files of Servlet are stored in the WEB-INF\classes folder

 

 

  • Seeing this, we know that we need to enter the classes directory to read the file , so we change the code to the following way


        FileInputStream fileInputStream = new FileInputStream("D:\\zhongfucheng\\web\\WEB-INF\\classes\\zhongfucheng\\web\\1.png");
        System.out.println(fileInputStream);


  • When you read it again, you will find that you can get the file.
  • But now the problem comes again. When I read the file, I have to write the absolute path, which is too inflexible . Just imagine, if I move the module that reads the file to another web site , my code will have to be modified again [because the name of the web site is different] .
  • We can avoid modifying the code by reading through the ServletContext , because the ServletContext object is generated according to the current web site
  • The code looks like this:

        //获取到ServletContext对象
        ServletContext servletContext = this.getServletContext();

        //调用ServletContext方法获取到读取文件的流
        InputStream inputStream = servletContext.getResourceAsStream("/WEB-INF/classes/zhongfucheng/web/1.png");

 

 

The second way:

  • If my files were placed in the web directory , it would be much simpler! , you can get it directly by the file name

 

 

  • The code looks like this


        //获取到ServletContext对象
        ServletContext servletContext = this.getServletContext();

        //调用ServletContext方法获取到读取文件的流
        InputStream inputStream = servletContext.getResourceAsStream("2.png");

 

 

The third way:

Read resource files via class loader .

  • My files are placed in the src directory [also called the class directory]

 

 

  • The code looks like this

        //获取到类装载器,2018年2月5日15:11:58 根据@兰兰美如画评论,发现Thread.currentThread().getContextClassLoader()这种方式会更好。
        //ClassLoader classLoader = Servlet111.class.getClassLoader();

        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
         

        //通过类装载器获取到读取文件流
        InputStream inputStream = classLoader.getResourceAsStream("3.png");



 

 

  • My files are placed under the package in the src directory

 

 

  • The code is as follows, just add the package name path.

        //获取到类装载器
        ClassLoader classLoader = Servlet111.class.getClassLoader();

        //通过类装载器获取到读取文件流
        InputStream inputStream = classLoader.getResourceAsStream("/zhongfucheng/web/1.png");



Principle: If the file is too large, it cannot be read by the class loader, which will cause memory overflow

If there are any mistakes in the article, please correct me, and we can communicate with each other. Students who are used to reading technical articles on WeChat can pay attention to the WeChat public account: Java3y


 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325138984&siteId=291194637