JavaWeb web.xml configuration details

reference:

The three major components of Javaweb are: Servlet, Filter, and Listener.

  • 1. Servlet
    Servlet, as a container for transit processing, connects the information interaction and processing between the client and server.
  • 2. Filter
    intercepts user requests. Before the server responds, the request and response can be modified after interception to realize the functions that developers want.
  • 3. Listener
    Listener is a listener. It mainly listens to the creation and destruction events of ServletContext, HttpSession, and ServletRequest. It also listens to the operation of domain object properties. When these events occur, it will perform some appropriate actions. operation.

0. Overview

The web.xml file is not required

  1. A web may not have a web.xml file, that is to say, a web.xml file is not necessary for a web project.
  2. The web.xml file is used to initialize configuration information: such as Welcome page, servlet, filter, listener, startup loading level, etc.
  3. When your web project does not use these, you can configure your web application without the web.xml file.

The loading order of the web container is ServletContext -> context-param -> listener -> filter -> servlet.

Start a web project, the web container will read its configuration file web.xml, read and two nodes.
Create a ServletContext (Servlet Context), which will be shared by all parts of the web project. The
container will be converted into key-value pairs and handed over to ServletContext.
The class instance in the container creation, creates the listener.

1. Header file

reference:

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
</web-app>
  • xmlns:xsi , xmlns, xsi:schmeLocation What do these similar attributes mean, and why are their values ​​different URLs?
  • Do these URLs correspond to some accessible resources, and do the parsing of the file require downloading the resources corresponding to these URLs?

①. Define a namespace xmlns:h="http://xmlns.jcp.org/xml/ns/javaee"
for an element, which is a unique string that identifies the space (often in the form of URL) ②. The unique identifier of the default spaceh"http://xmlns.jcp.org/xml/ns/javaee"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
"http://xmlns.jcp.org/xml/ns/javaee"

For namespace identifiers, the role of URI is only to ensure uniqueness, it does not need to correspond to an accessible resource or file! However, many companies will make the URI of the namespace point to a web page that contains information about the namespace.

③, xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
④. xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
According to the previous knowledge, we can understand that xmlns:xsi defines a unique string xsicorresponding to http://www.w3.org/2001/XMLSchema-instance. But readers will find that this seems to appear xmlns:xsiin different xml documents. This is because it xsihas become an industry default namespace for XSD (XML Schema Definition) files. The XSD file (also often referred to as the Schema file) is used to define the structure of the xml document.

Note: An XML parser can parse another XML file based on the content of an XSD file, and judge whether the structure of the file is consistent with that defined in the XSD file. XSD files can be understood as syntax or format checkers for XML documents that can be customized

④The syntax of this line is actually xsi:schemaLocation= "键" “值”, that is xsi, schemaLocationthe value of the element under the namespace is a key-value pair separated by spaces.

The former “键” http://maven.apache.org/POM/4.0.0refers to [namespace], which is just a globally unique string.

The latter value refers to 【XSD location URI】, which indicates the location of the XSD file corresponding to the previous namespace. This information can be used to xml parserobtain the XSD file, so that all element structures http://maven.apache.org/POM/4.0.0belonging Therefore, this value must be accessible, and the accessed content is the content of an XSD file.

example:

<beans 
	xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context 
		http://www.springframework.org/schema/context/spring-context.xsd
		http://www.springframework.org/schema/util 
		http://www.springframework.org/schema/util/spring-util.xsd">
</beans>
  • xmlns="http://www.springframework.org/schema/beans"It is to define a default namespace, xmlnsthe value of which can be changed at will, as long as it is unique, if the value here is changed, the ones in the following should xsi:schemaLocationalso be modified to the corresponding value.
  • xmlns:context="http://www.springframework.org/schema/context"It is to define contexta namespace, and to use contextthe elements under it, you need to add contextthe prefix .
  • xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance", creates a xsinamespace that can be xsi:schemaLocationpassed to define the location of xsdthe file for the XML parser to parse the XML file.

2. Configure the welcome page

<web-app>
	<welcome-file-list>
		<welcome-file>wecome1.jsp</welcome-file>
		<welcome-file>wecome2.jsp</welcome-file>
		<description>欢迎页面</description>
	</welcome-file-list>
</web-app>

The above code configures two welcome pages, wecome1.jsp and wecome2.jsp, which are displayed in the order of configuration. If the wecome1.jsp file can be found, it will be displayed, and if not found, the second one will be found, and so on.

The welcome page is used to access the web project. Only the root name is given, but no specific page is given. At this time, go back to visit the configured welcome page. If the welcome page is not configured, different application servers may have different behaviors. For Tomcat, it will first search for the index.html file by default, and if it is found, it will return it to the browser; if it is not found, it will continue to search for the index.jsp file, if it is not found, then Tomcat will display The requested resource is not available page.

The welcome page is only used when no specific access page is given. If a specific page is specified, as long as the access path is correct, it can be accessed normally.

3. Configure Servlet

ServletName and customize the URL for

<web-app>
	<servlet>
		<servlet-name>TestServlet</servlet-name>
		<servlet-class>com.yiyu.servlet.showAllServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>TestServlet</servlet-name>
		<url-pattern>/TestServlet</url-pattern>
	</servlet-mapping>
</web-app>

<!-- <servlet-name></servlet-name> 指定servlet的名称 
<servlet-class></servlet-class> 指定servlet的类名称 \
<jsp-file></jsp-file> 指定web站台中的某个JSP网页的完整路径 
<init-param></init-param> 用来定义参数,可有多个init-param。在servlet类中通过getInitParamenter(String name)方法访问初始化参数 

<load-on-startup></load-on-startup>指定当Web应用启动时,装载Servlet的次序。当值为正数或零时:Servlet容器先加载数值小的servlet,再依次加载其他数值大的servlet。当值为负或未定义:Servlet容器将在Web客户首次访问这个servlet时加载它。 

<servlet-mapping></servlet-mapping> 用来定义servlet所对应的URL,包含两个子元素 <servlet-name></servlet-name> 指定servlet的名称 
<url-pattern></url-pattern> 指定servlet所对应的URL -->

<servlet-name>: Registered name
<servlet-class>: The full class name of the configured Servlet
<url-pattern>: Map an external access path for this Servlet.
The relationship between servlet and url-pattern is a one-to-many relationship.

4. Configure Filter

reference:

See this blog for details

Bag:servlet-api.jar
insert image description here

filter configuration

<web-app>
	<filter>
		<filter-name>Filter1</filter-name><!--过滤器名称-->
		<filter-class>D2020128.TestFilter</filter-class><!--过滤器类的包路径-->
		<!-- 可使用<init-param>标签初始化 -->
	</filter>
	<!-- 一个过滤器需要过滤多种文件,则可以配置多个<filter-mapping>,一个mapping定义一个url-pattern来定义过滤规则 -->
	<filter-mapping><!--过滤器映射-->
		<filter-name>Filter1</filter-name>
		<url-pattern>/TestServlet</url-pattern><!--指定过滤器作用的对象-->
	</filter-mapping>
	<filter-mapping>
		<filter-name>Filter1</filter-name>
		<!-- 所有外部访问都需要先经过该过滤器。 -->
		<url—pattern>/*</url-pattern>
		<!-- 作用于某一文件夹下所有文件 -->
		<!-- <url—pattern>/dir/*</url-pattern> -->
		<!-- 作用于某一种类型的文件 -->
		<!-- <url—pattern>*.扩展名</url-pattern> -->
		<!-- 作用于某一文件夹下某一类型文件 -->
		<!-- <url—pattern>/dir/*.扩展名</url-pattern> -->
	</filter-mapping>
</web-app>
  • url-patternThe path configured in Filter is to access existing network resources, such as static pages, jsp, servlet, etc.
  • url-patternThe relationship between filter and is a many-to-many relationship. That is, Filter can be responsible for intercepting multiple requests or responses; one request or response can also be intercepted by multiple Filters. (Multiple filters will form a filter chain according to the order configured web.xmlin ).

Common occasions:
(1) Authentication Filter
(2) Log and Audit Filter
(3) Image Conversion Filter
(4) Data Compression Filter
(5) Password Filter
(6) Token Filter
(7) Filter that triggers resource access events
(8) XSLT Filter
(9) media type chain Filter

At this point, you can uniformly set the code for the request or response (Request, Response) to simplify the operation; at the same time, you can also make logical judgments, such as whether the user has logged in, whether he has permission to access the page, permission management, filtering sensitive words, etc. . It is started when your web application is started. It is only initialized once, and related requests can be intercepted in the future, and it will only be destroyed when your web application is stopped or redeployed.

Filter life cycle: initialization init() → filter doFilter() → destruction (destruction) destroy()
filter has four interception methods! They are: REQUEST, FORWARD, INCLUDE, ERROR.
Filter chain order: according to the order configured in web.xml

4.1. How to create a Filter?

Similar to servlet, it takes two steps and
the first step is to create a Filter processing class (generally we use existing ones)
Filter must implement the javax.servlet.Filter interface, in which three methods are defined:
(1) void init( FilterConfig config): Used for Filter initialization. FilteConfig is used to access Filter configuration information.
(2) void destroy(): The operation before the Filter is destroyed, such as completing the recovery of certain resources.
(3) void doFilter(ServletRequest request, ServletResponse response, FilterChain chain):
the core method to realize the filtering function, realize the preprocessing of the request request, and also realize the postprocessing of the server response response—their dividing line is whether to call chain.doFilter(request, response), before executing this method, the user request request is preprocessed, and after this method is executed, the server response response is post-processed.

Step 2: Configure Filter in the Web.xml file
Filter configuration is very similar to Servlet configuration, the difference is that Servlet usually only configures one URL, while Filter can configure multiple requested URLs at the same time. There are two ways to configure Filter:
(1). Configure through Annotation in the Filter class.
(2). Configure through the configuration file in the web.xml file.

5. Listener

<listener> 
    <listerner-class>com.listener.SessionListener</listener-class> 
</listener>

The listener can listen to the functional components that automatically execute the code applicationwhen the three objects are created session, requestdestroyed, or added, modified, or deleted attributes.

applicationis ServletContextan object of type. ServletContext represents the entire web application, and tomcat will automatically create this object when the server starts. This object is automatically destroyed when the server shuts down.
insert image description here

6. Configure session timeout

in seconds

<session-config>
    <session-timeout>120</session-timeout>
</session-config>

7. Configure context parameters

Declares application-scoped initialization parameters. Used to provide key-value pairs to Servlet+Context, that is, application context information. Subsequent listeners and filters will use these context information when initializing. In the servlet, it can be obtained through getServletContext().getInitParameter("context/param")

<context-param>
    <param-name>log4jConfiguration</param-name>
    <param-value>/WEB-INF/log4j2.xml</param-value>
</context-param>

8. Configuration application description

<disciption>Tomcat Example servlets and JSP pages.</disciption>

9. Configure the application name

<display-name>Tomcat Example</display-name>

10. Specify the error handling page

The error handling page can be specified by "Exception Type" or "Error Code".

<error-page>
    <error-code>404</error-code>
    <location>/error404.jsp</location>
</error-page>
<error-page>
    <exception-type>java.lang.Exception<exception-type>
    <location>/exception.jsp<location>
</error-page>

11. Configure the web application icon

<icon>    
	<small-icon>/images/app_small.gif</small-icon>    
	<large-icon>/images/app_large.gif</large-icon>    
</icon>

12. Configure security restrictions

<security-constraint>    
  <display-name>Example Security Constraint</display-name>    
   <web-resource-collection>    
      <web-resource-name>Protected Area</web-resource-name>    
      <url-pattern>/jsp/security/protected/*</url-pattern>
      <url-pattern>*.jsp</url-pattern>
      <!-- 如果没有 <http-method> 元素,这表示将禁止所有 HTTP 方法访问相应的资源。 -->
      <http-method>DELETE</http-method>    
      <http-method>GET</http-method>    
      <http-method>POST</http-method>    
      <http-method>PUT</http-method>    
   </web-resource-collection>
   <!-- 子元素 <auth-constraint> 需要和 <login-config> 相配合使用,但可以被单独使用。 -->
   <!-- 如果没有 <auth-constraint> 子元素,这表明任何身份的用户都可以访问相应的资源。 -->
   <!-- 如果加入了 <auth-constraint> 子元素,但是其内容为空,这表示所有身份的用户都被禁止访问相应的资源。  -->
   <auth-constraint>
   	 <role-name>All Role</role-name>
     <role-name>tomcat</role-name>    
     <role-name>role1</role-name>    
   </auth-constraint>
   <!-- <user-data-constraint>   
     <transport-guarantee>NONE</transport-guarantee>   
   </user-data-constraint> -->
</security-constraint>

<login-config>Xml代码   
<!--四种验证方式,附在最后有说明-->    
  <auth-method>FORM</auth-method>    
  <form-login-config>    
   <form-login-page>/login.html</form-login-page>    
   <form-error-page>/error.html</form-error-page>    
  </form-login-config>    
</login-config>    
<security-role>    
  <role-name>All Role</role-name>    
</security-role>

13. Configure login verification

<login-config>    
  <auth-method>FORM</auth-method>    
  <realm-name>Example-Based Authentiation Area</realm-name>    
  <form-login-config>    
     <form-login-page>/jsp/security/protected/login.jsp</form-login-page>    
     <form-error-page>/jsp/security/protected/error.jsp</form-error-page>    
  </form-login-config>    
</login-config>

Initialization parameters

<web-app>
	<servlet>
		<servlet-name>InitParamServlet</servlet-name>
		<servlet-class>InitParamServlet</servlet-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>utf-8</param-value>
		</init-param>
		<init-param>
			<param-name>helloween</param-name>		<!--用户: helloween-->
			<param-value>password</param-value>
		</init-param>
		<init-param>
			<param-name>admin</param-name>			<!--用户: admin-->
			<param-value>admin</param-value>
		</init-param>
		<init-param>
			<param-name>babyface</param-name>	<!--用户: babyface-->
			<param-value>babyface</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>	
		<!-- 
		1、load-on-startup 元素标记容器是否应该在web应用程序启动的时候就加载这个servlet,(实例化并调用其init()方法)。
		2、它的值必须是一个整数,表示servlet被加载的先后顺序。
		3、如果该元素的值为负数或者没有设置,则容器会当Servlet被请求时再加载。
		4、如果值为正整数或者0时,表示容器在应用启动时就加载并初始化这个servlet,值越小,servlet的优先级越高,就越先被加载。值相同时,容器就会自己选择顺序来加载。 -->
	</servlet>
	<servlet-mapping>
		<servlet-name>InitParamServlet</servlet-name>
		<url-pattern>/initParamServlet</url-pattern>
	</servlet-mapping>
</web-app>
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    
    
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		Enumeration params = this.getInitParameterNames(); // 所有的初始化参数名称
		while (params.hasMoreElements()) {
    
    
			String nameParam = (String) params.nextElement(); // 获取参数名
			String valueParam = this.getInitParameter(nameParam); // 获取参数值
			// 如果用户名,密码匹配则显示notice.html
			if (nameParam.equalsIgnoreCase(username) && valueParam.equalsIgnoreCase(password)) {
    
     
				request.getRequestDispatcher("/WEB-INF/notice.html").forward(request, response);
				return;
			}
		}
		this.doGet(request, response); // 若username,password不匹配,显示登录页面。
	}

The enumeration type is used: Enumeration params = this.getInitParameterNames();

  1. Get all parameter names in web.xml: this.getInitParameterNames();
  2. Iterating over the enumeration: while (params.hasMoreElements()){ …}
  3. Get the next element: params.nextElement();
  4. Get the value corresponding to the name: getInitParameter(nameParam);
  5. 重定向: request.getRequestDispatcher(“/WEB-INF/notice.html”).forward(request,response);

Guess you like

Origin blog.csdn.net/weixin_41544662/article/details/128147204