Novice web development simple summary (two)-what is web.xml

table of Contents

One what is web.xml

Two web.xml configuration items

1.web-app

 2.context-param and listener

(1)context-param

(2)listener

(3) context-param and listener application scenarios

3.filter and filter-mapping

4.servlet和servlet-mapping

5. Other configuration items

(1)session-config

(2) mime-mapping

(3)welcome-file-list

(4)error-page

Three summary


One what is web.xml

In the previous article, a novice web development brief summary (1)-What is Tomcat mentioned when introducing Context, there is a webapp directory under each web application project, in this directory, it will usually follow The module is divided into different folders to store JSP files and resource files, and each folder is a Context.

In the webapp directory, there must be a WEB-INF directory, in which there is a web.xml file. This web.xml file is the configuration file of the web application, which is used to configure the welcome page, servlet, filter, listener, etc. of the web application.

Of course, this web.xml file is not necessary. If the configuration content is not used in the project, you can not configure web.xml. Finally, when the web application is packaged on the server for user access, the directory of WEB-INF cannot be accessed by users.

When a web application is started, the web container (such as JBoss, Tomcat, etc.) will read the configuration items in web.xml and complete the instantiation of the configuration items. Only if there is no error in this step, the project can start normally. The following mainly analyzes the various configuration items of web.xml

Two web.xml configuration items

1.web-app

The root element. It must indicate which file is used by web.xml.

<web-app version="3.1"
	xmlns="http://java.sun.com/xml/ns/j2ee"   
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">    
.......
</web-app>

I think this should be the same as the namespace in Android, with the xsi in the front instead of the link in the back. Finally, this marked the location of the xml schema.

xmlns:android="http://schemas.android.com/apk/res/android"

 2.context-param and listener

When starting a web application, the web container (such as Tomcat) will first read the <context-param> and <listener> of web.xml , and accomplish two things:

(1)context-param

  • 1) Convert <context-param> to key-value and store it in ServletContext;

<context-param> mainly stores the initialization parameters of ServletContext and the initialization parameters read by JSP application built-in objects.

ServletContext is again called Servlet Context. A web container (such as Tomcat) creates a ServletContext object for each application. This object is globally unique, and all Servlets share this object. This object contains the resource information shared by all servlets, which can be used by servlets through a set of methods, and data can be transferred between different servlets, such as obtaining the MIME type of a file, distributing requests, and recording logs. If the web application is deployed in a distributed manner, then each web application instance deployed on the server has a Servlet instance. The ServletContext instance can be obtained through getServletContext(). Of course, multiple web applications can be deployed on a web server, and the web server will also create a globally unique ServletContext for each web application.

Then getServletContext() is finally saved in ServletContext for use by different Servlets, so the content in <context-param> can be called by all Servlets through ServletContext, and does not belong to any Servlet. In the project, the corresponding value can be obtained through getServletContext().getInitParameter("param-name") (where name is the <param-name> configured by <context-param>). 

The application of this JSP is actually ServletContext, but it is called application in JSP and ServletContext in Servlet. The main thing is to share data in JSP and Servlet respectively through these two classes. Therefore, the content configured in <context-param> can be read on both sides, and the value modified by setAttribute() on either side can be read on both sides.

In a web server, four Map-like structures are provided: application, session, request, page, and running JSP and Servlet to modify these four structure values, but the scope of these four classes is different:

application: It is useful for the entire web application, all JSPs and Servlets under the application can access the values ​​inside;

session: only valid for one session, only for the JSP and Servlet in this session can access the value inside;

request: Only valid for this request, and can only be accessed by the requested JSP and Servlet;

page: Only valid for the current page, and can only be accessed for the JSP and Servlet of the current page.

<context-param> is not required to be configured in the project.

Give an example to illustrate the use of <context-param>: In a project with a non-Spring MVC architecture, applicationcontext.xml (mainly placed some beans related to business logic) is usually used to load the Application Context, then it needs to be configured contextConfigLocation.

If the contextConfigLocation is not configured in web.xml, then when the web container is started, it will search for the /WEB-INF/applicationcontext.xml file by default. But if you customize the file name of the configuration file, you need to configure the file through contextConfigLocation, as follows

<context-param>
	<param-name>contextConfigLocation</param-name>
	<param-value>classpath:config/application-context-*.xml</param-value>
</context-param>

Among them, classpath: only find files in this path; classpath*: not only contains the class path, but also contains the jar (class path) for searching.

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

Usually when configuring <servlet>, contextConfigLocation is also configured through <init-param>. The difference between these two will be introduced to <servlet> later, and will be summarized in detail.

When contextConfigLocation is configured in <context-param>, <listener> is usually added to web.xml. This is when the web container starts, after completing the first step to read the content of <context-param>, then instantiate the corresponding class instance in <listener>.

(2)listener

  • 2) The class instance configured in <listener> is instantiated and monitored for related events according to the configured path.

These class instances can be custom monitor classes, but the system interface must be implemented based on specific event monitoring. Now take ServletContextListener as an example. There are two methods in this interface:


public interface ServletContextListener extends EventListener {
    void contextInitialized(ServletContextEvent var1);

    void contextDestroyed(ServletContextEvent var1);
}

Obviously, it can be seen that when the web container creates the class instance corresponding to <listener>, it will first call contextInitialized(ServletContextEvent var1) to initialize and complete the initialization work. Of course, in this method, you can pass var1.getServletContext().getInitParameter(" name") (where name is the <param-name> configured by <context-param>) to get the value of <context-param> configuration. Before the web project starts, some initialization work is completed; of course, when the web application is closed At that time, the contextDestroyed(ServletContextEvent var1) method of the monitor class is also called to complete the work of releasing some resources.

Give an example to illustrate the use of this <listener>: When configuring a Spring project, you must configure <listener>. It is usually necessary to add the ContextLoaderListener listener to the project to automatically load the information of the ApplicationContext configuration. It is generally used with <context-param> (Configuring ApplicationContext through contextConfigLocation), but <context-param> is not necessary.

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

The role of the ContextLoaderListener is to read the xml file configured in the contextConfigLocation (that is, the initialization parameter configured through <context-param>) when starting the web container, automatically assemble the configuration information of the ApplicationContext, and generate a WebApplicationContext object, and at the same time ServletContext is bound to WebApplicationContext, and WebApplicationContext is also bound to ServletContext. In this way, you can use the WebApplicationContext object to access container-managed beans (here is a question that I need to learn later: How do I know which beans to load in a project? These beans should be some beans related to business logic) .

ApplicationContext is the ApplicationContext created for the entire application by loading the applicationcontext.xml file, loading the beans in the configuration file, and collecting all the beans.

WebApplicationContext inherits from the ApplicationContext interface and adds the characteristics of Web applications. It can view resolution, theme resolution, mapping, and associate with ServletContext through ServletContext, and bind WebApplicationContext to ServletContext in ContextLoaderListener (servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context) );)

Common web monitoring event interfaces are as follows: 

 ServletContextListener: used to monitor the startup and shutdown of web applications (including Initialized/Destroyed events)

ServletContextAttributeListener: used to monitor the changes of attributes within the scope of ServletContext (including Add/Remove/Replace events)

ServletRequestListener: used to monitor user requests (including Initialized/Destroyed events)

ServletRequestAttributeListener: used to monitor the changes of attributes within the scope of ServletRequest (including Add/Remove/Replace events)

HttpSessionListener: used to monitor the creation and termination of user sessions (including Created/Destroyed events)

HttpSessionAttributeListener: used to monitor the changes of attributes within the scope of the user session (including Add/Remove/Replace events)

(3) context-param and listener application scenarios

An example of a scenario where these two configuration items can be applied: before the web project starts, the database needs to be opened

Then there are two steps for this realization:

(1) Configure some basic information of the database through <context-param>, such as url, user, password, etc.

(2) Customize the listener class to implement the ServletContextListener interface: read the content of the <context-param> configuration in contextInitialized (ServletContextEvent var1) to open the database; release resources in contextDestroyed (ServletContextEvent var1), close the database, etc.

So far, the web application has not been started yet.

3.filter and filter-mapping

Before the web application is started, after reading the <context-param> and <listener>, the content of <filter> is read, and the filter is instantiated according to the specified classpath.

The work of filter is mainly used to pre-process user requests and post-process responses. When the client sends a request, the filter will first preprocess the request, and then encapsulate the request as a SerlvetRequest and forward it to the Servlet for processing and response. After the Servlet response is completed, the ServletResponse is given to the filter for post-processing. Back to the client.

According to different applications, there are filters with different functions: authentication filter, log and audit filter, image conversion filter, data compression filter, password filter, token filter, filter that triggers resource access events, performance monitoring filter, media type chain Filter, etc. (Of course, the processing of some public functions will be placed in the Filter).

All custom Filters need to implement the javax.sevlet.Filter interface. The core method doFilter (ServletRequest request, ServletResponse response, FilteChain chain), which implements the filtering function in this interface, is used to add filtering functions to requests and responses.

Define filter in web.xml through .<filter>. It is usually used in conjunction with <filter-mapping>. <filter-mapping> is used to tell which requests or responses are passed to the filter for processing, and the two <filter-name> must be the same.

For example, a more commonly used filter for character set conversion:

    <filter>
		<filter-name>EncodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
		<init-param>
			<param-name>forceEncoding</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>EncodingFilter</filter-name>
		<url-pattern>*</url-pattern>
	</filter-mapping>

<url-pattern>*</url-pattern> uses the wildcard character * to indicate that all requests will be intercepted by the filter first, encoded according to the specified utf-8, and then forwarded downward.

After the first three, a web project has been launched successfully.

4.servlet和servlet-mapping

In the previous article, a simple summary of novice web development (1)-What is Tomcat also mentioned Servlet, which is mainly used to process business logic. After the Servlet is initialized, it will always exist in the Servlet container, usually only when the web application is closed. Destroy the Servlet only when. The Servlet container calls Servlet's doGet()/doPost() to process and respond to the request, or uniformly uses service() to respond to the request. When the Servlet container destroys the Servlet, it will call the destroy() of the Servlet. If the Servlet can respond to user requests, Serlvet must be configured in the web application.

Generally, Servlet can be configured in two ways in the project:

  • (1) One is to configure via @WebServlet Annotation in the Serlvet class;
  • (2) The other is to configure through <servlet><servlet-mapping> and in web.xml.

Generally speaking, <servlet> is instantiated when the request is initiated for the first time, and is generally not destroyed by the Serlvet container, and can serve multiple user requests.

So in summary, the loading order of the first four is <context-param> -> <listener> -> <filter> -> <servlet>.

But <servlet> can also create a Servlet instance immediately when the web application starts by configuring <load-on-startup>. An example is used to illustrate this <servlet>: When configuring Spring MVC, Spring MVC's front controller is usually configured to intercept requests (I understand the current project has Tomcat, Spring MVC and SOA services, then this DispatcherServlet intercepts the request originally handed over to Controller by Spring MVC, and then passes it to Tomcat Servlet for processing. I don’t know if my understanding is correct...) .

	<servlet>
<!--定义Servlet的名字,全局唯一,和"<servlet-mapping>"中的保一致-->
		<servlet-name>SpringMvc</servlet-name>
<!--指定Servlet类-->
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--初始化参数-->
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:config/spring-mvc.xml</param-value>
		</init-param>
<!--该Serlvet载入容器的顺序-->
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>SpringMvc</servlet-name>
		<url-pattern>*.html</url-pattern>
	</servlet-mapping>

<servlet> is used to configure Servlet, and must contain <servlet-name> and <servlet-class> or <servlet-name> and <jsp-file>.

  • <serlvet-name> defines the name of the servlet, which must be unique in the entire web application. 
  • <serlvet-class> specifies the Serlvet class; if you do not specify <serlvet-class>, you can also specify <jsp-file>. When <jsp-file> is specified and <load-on-startup> is also set, the JSP file will also be compiled into a Servlet and placed in memory.
  • <load-on-startup> is used to specify the order of containers loaded by the servlet:
  • If the value of <load-on-startup> is empty or negative, the Servlet container decides which Serlvet to load first;
  • If the value of <load-on-startup> is 1, it means that the Serlvet will be loaded when the web application starts, but the loading order is still after <context-param> -> <listener> -> <filter>;
  • If the value of <load-on-startup> is positive, the smaller the value, the more priority the servlet will be loaded.
  • The <init-param> initialization parameter is consistent with the usage of <context-param>. Only <context-param> is valid for all Serlvet and JSP applications, and <init-param> is only valid for the current Servlet. In the current Serlvet, the corresponding configuration value is obtained through getServletConfig().getInitParameter("name") (where name is the <param-name> configured by <context-param>). When configuring Spring MVC, the default read configuration file will be in /WEB-INF/SpringMvc-servlet-xml (the file is named: [servlet-name]-servlet.xml) configuration file, of course, it can also be read in <init -param> Set contextConfigLocation to specify the MVC configuration file. ( Then I have a question of my own here. What exactly needs to be configured in a configuration file like this SpringMVC??? It is not very clear what is configured in the applicationcontext.xml file???? But what I understand now should be: each part will have a configuration file)

<servlet-mapping> is used to configure the access path of the servlet.

  • <serlvet-name> The value must be consistent with <serlvet-name> of <servlet>
  • <url-pattern> is used to specify the URL processed by the servlet. After the container's Context object processes the requested URL, it matches the path mapping rule with the Servlet mapping rule (that is, the rule configured by <url-pattern>). If it happens to match the rule, the request is handed over to the Servlet To process.

(I think I need to continue to think about how ContextLoaderListener and DispatcherServlet work together? What does a Spring MVC need to configure? What is the relationship between Tomcat, Spring MVC, and SOA in the project??)

We can also configure other Servlets in the project to handle different requests separately.

For example, <filter> and <servlet> are equivalent to one configuration item. Multiple configuration items can be configured in one web.xml. When multiple configuration items are configured for the same configuration item, how are they instantiated in order when they are enabled? Example <filter>: <filter> and <filter-mapping> appear together. For <filter> and <filter-mapping> configuration items with the same <filter-name>, <filter-mapping> must appear in <filter > Behind. When the web container initializes these <filter>s, they will be initialized in the order in which they appear in web.xml. When there are multiple <filter> matches in the request sent by the client, the corresponding doFilter() method will be called in the order in which the <filter-mapping> appears.

5. Other configuration items

The remaining configuration items should belong to some configuration items that are easier to understand. All configuration items can refer to the official document https://docs.oracle.com/cd/E11035_01/wls100/webapp/web_xml.html#wp1070143

(1)session-config

Set the session parameters of the web container. For example, <session-timeout> is used to specify the event that the http session fails. The default unit is min. If it is set to 0 or a negative number, it means that it will never expire.

	<session-config>
<!--时间单位:分钟 -->
		<session-timeout>30</session-timeout>
	</session-config>

(2) mime-mapping

Specify the file types that the browser can open

 <mime-mapping> 
     <extension>doc</extension>
     <mime-type>application/msword</mime-type> 
 </mime-mapping> 
 <mime-mapping> 
      <extension>xls</extension> 
      <mime-type>application/msexcel</mime-type> 
  </mime-mapping> 
  <mime-mapping> 
      <extension>pdf</extension> 
      <mime-type>application/pdf</mime-type> 
  </mime-mapping>
  <mime-mapping> 
      <extension>zip</extension> 
      <mime-type>application/zip</mime-type> 
  </mime-mapping>
  <mime-mapping> 
      <extension>rar</extension> 
      <mime-type>application/rar</mime-type> 
  </mime-mapping>
  <mime-mapping> 
      <extension>txt</extension> 
      <mime-type>application/txt</mime-type> 
  </mime-mapping>
  <mime-mapping>
      <extension>mp3</extension>
      <mime-type>audio/x-mpeg</mime-type>
  </mime-mapping>

(3)welcome-file-list

Specify the welcome page of the web application. Can contain one or more <welcome-file>. Files that can be opened will be found in the order of configuration.

<welcome-file-list>
	<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

(4)error-page

Specify the error page, you can configure the page that needs to be displayed according to the error code and the exception information thrown

  <error-page>
      <error-code>404</error-code>
      <location>/jsp/common/404.html</location>
  </error-page>
  <error-page>
      <error-code>500</error-code>
      <location>/jsp/common/500.html</location>
  </error-page>
  <error-page>
      <exception-type>java.io.IOException</exception-type>
      <location>/jsp/common/IO.html</location>
  </error-page>

Three summary

To summarize the content that has been understood so far:

  • 1. A web.xml configuration item generally includes <context-param>, <listener>, <filter> and <filter-mapping>, <servlet> and <servlet> and other easy-to-understand configuration items;
  • 2. When the web container loads the web.xml configuration item, it will instantiate the content configured in the web application according to <context-param> -> <listener> -> <filter> when the web application is started;
  • 3. <context-param> configures the initialization parameters. For the entire web application, the content of the configuration is converted into key-value and written into the ServletContext. In Servlet, the content of configuration items is obtained through ServletContext, and the content of configuration items is obtained through application in JSP, so that data sharing between Serlvet and between servlet and JSP can be completed;
  • 4. <param-name>contextConfigLocation</param-name> is used to configure the configuration file. In <context-param>, the content of ApplicationContext is configured, which is aimed at the beans of the entire web application. These beans are some business logic beans. In <init-param>, the configuration file for Servlet is configured. , Only valid in the current Servlet;
  • 5. By configuring the ContextLoaderListener in the <listener> in the Spring MVC project, through the monitoring, when the web application is started, the ApplicationContext is configured, and a WebApplicationContext object is generated, and the WebApplicationContext is written to the ServletContext, so that all Serlvets are Can share all;
  • 6. <filter> is mainly to pre-process the request generated by the client, and then hand it over to the Servlet for processing, and perform post-processing on the response generated by the Servlet before returning it to the client;
  • 7. The configuration items of <servlet> generally only instantiate the Servlet after the client sends a request. The instantiated Servlet will always exist, and the Servlet container is used to manage the Servlet to process the request; only when the web application is closed Only then will Serlvet be destroyed;
  • 8. When configuring the Spring MVC project, <servlet> usually configures DispatcherServlet, matching the corresponding request through the rules defined by <servlet-mapping>, then these requests that meet the matching rules are handed over to the servlet for processing;
  • 9. <servlet> can set the priority of different servlets by configuring <load-on-startup>, of course, you can also use this configuration item to instantiate the servlet when the web application starts;
  • 10. Different <servlet> can be configured to process requests according to different servlets;
  • 11. A web.xml is the configuration file of a web application; by configuring contextConfigLocation in <context-param>, it is the configuration file of ApplicationContext; by configuring contextConfigLocation in <servlet>, it is the configuration file of Spring MVC;
  • 12. The same configuration item is allowed to have more than one. When there are more than one, they will be instantiated in the order of configuration. When they are working, they will be called in the order of the previous instantiations.
  • 13. <filter>, <servlet> are to define the corresponding filter and servlet, and <filter-mapping>, <servlet-mapping> are to set the matching rules, when the corresponding rules are matched, it will be handed over to the Filter and Servlet deal with.

Of course, there are still some areas that I have questions that I need to look up information and research, of course, I also hope that the big guys can give me pointers.

  • 1. I think a web.xml should be the entrance of a web application, but some also mentioned that you don’t need to add this web.xml file. If you don’t add this web.xml file, what about the project? ? There is still no concept of a simple framework for a web project, and we need to continue to understand it.
  • 2. What exactly are the two objects, ApplicationContext and WebApplicationContext generated in Article 5, used for? ? ?
  • 3. In response to Article 8, I have a question: Doesn't Spring MVC itself also have Controller to implement business logic, why should it be handed over to DispatcherServlet? What role do Tomcat, Spring MVC and SOA services play in a project? ? (Can it be understood that the web application is based on the Spring MVC architecture, the original request should be handed over to the Controller, and now the request is passed to Tomcat's Serlvet through the configured DispatcherServlet? SOA must provide services at the bottom. If so What are the benefits? If the web application is Spring MVC, wouldn’t it have its own MV?)
  • 4. Regarding Article 10, are the requests processed by these servlets distributed by the browser? Why do these requests need to be handled by different servlets? What are the common applications? ?
  • 5. For the configuration files of Article 11, we have already understood the web.xml configuration file. What should the other configuration files include? Why do we need these configuration files? If you want to add a configuration file, what should be included? ?

Come on, keep working hard! ! ! ! Later, I will analyze a simple web application development and understand what should be included in a web application development. See Xiaobai Novice Web Development Brief Summary (3)-A Simple Spring Project

Guess you like

Origin blog.csdn.net/nihaomabmt/article/details/113523267