• web.xml配置详解


    参考:

    Javaweb三大组件是:Servlet,Filter,Listener。

    • 1、Servlet
      Servlet作为中转处理的容器,连接了客户端和服务器端的信息交互和处理。
    • 2、Filter
      拦截用户请求,在服务器作出响应前,可以在拦截后修改request和response,实现开发者想得到的功能。
    • 3、Listener
      Listener就是监听器,监听主要是对ServletContext,HttpSession,ServletRequest这三大域对象的创建和销毁事件监听,还有就是对域对象属性的操作监听,当监听这些事件发生是就会进行一些适当的操作。

    0、概述

    web.xml文件不是必须的

    1. 一个web中可以没有web.xml文件,也就是说,web.xml文件并不是web工程必须的。
    2. web.xml文件是用来初始化配置信息:比如Welcome页面、servlet、filter、listener、启动加载级别等。
    3. 当你的web工程没用到这些时,你可以不用web.xml文件来配置你的web应用。

    web容器的加载顺序 ServletContext -> context-param -> listener -> filter -> servlet。

    启动一个web项目,web容器会读取它的配置文件web.xml,读取和两个结点。
    创建一个ServletContext(Servlet上下文),这个web项目的所有部分都将共享这个上下文
    容器将转换为键值对,并交给ServletContext。
    容器创建中的类实例,创建监听器

    1、头文件

    参考:

    <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>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • xmlns:xsi , xmlns, xsi:schmeLocation 这些看上去相近的属性是什么含义, 为什么他们的值是不一样的 URL?
    • 这些 URL 是否对应一些可以访问的资源,对于该文件的解析是否会需要下载这些 URL 对应的资源?

    ①、xmlns:h="http://xmlns.jcp.org/xml/ns/javaee"
    h元素定义一个命名空间,"http://xmlns.jcp.org/xml/ns/javaee"是标识该空间的唯一字符串(常采用URL形式)
    ②、xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    默认空间的唯一标识符"http://xmlns.jcp.org/xml/ns/javaee"

    对于命名空间的标识符, URI 的作用仅仅是保证唯一性, 它并不需要对应一个可以访问的资源或文件 ! 但是, 有很多公司都会让namespace 的 URI 指向一个包含该命名空间信息的网页。

    ③、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"
    根据之前的知识我们可以理解, xmlns:xsi 定义了一个命名空间前缀 xsi 对应的唯一字符串 http://www.w3.org/2001/XMLSchema-instance。 但是读者会发现, 这个 xmlns:xsi 在不同的 xml 文档中似乎都会出现。 这是因为, xsi 已经成为了一个业界默认的用于 XSD(XML Schema Definition) 文件的命名空间。 而 XSD 文件(也常常称为 Schema 文件)是用来定义 xml 文档结构的。

    注: XML 解析器可以根据 一个 XSD 文件的内容来解析另一个 XML 文件, 判断该文件的结构是否和 XSD 文件中定义的一致。 XSD 文件 可以理解为 XML 文档可以自定义的语法或格式检查器

    这行的语法其实是, xsi:schemaLocation = "键" “值”,即 xsi 命名空间下 schemaLocation 元素的值为一个由空格分开的键值对。

    前一个“键” http://maven.apache.org/POM/4.0.0 指代 【命名空间】, 只是一个全局唯一字符串而已。

    后一个值指代 【XSD location URI】 , 这个值指示了前一个命名空间所对应的 XSD 文件的位置, xml parser 可以利用这个信息获取到 XSD 文件, 从而通过 XSD 文件对所有属于 命名空间 http://maven.apache.org/POM/4.0.0 的元素结构进行校验, 因此这个值必然是可以访问的, 且访问到的内容是一个 XSD 文件的内容。

    例:

    <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>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • xmlns="http://www.springframework.org/schema/beans"就是定义了一个默认命名空间, xmlns 的值可以随便改,只要是唯一的就行,如果更改了这里的值,下面的xsi:schemaLocation中的也要修改为对应的值。
    • xmlns:context="http://www.springframework.org/schema/context"就是定义了一个 context 的命名空间,使用 context 下的元素,需要加上 context 前缀。
    • xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance",创建了一个 xsi 命名空间,可以通过xsi:schemaLocation来定义 xsd 文件的位置,以便 XML 解析器解析 XML 文件。

    2、配置欢迎页面

    <web-app>
    	<welcome-file-list>
    		<welcome-file>wecome1.jspwelcome-file>
    		<welcome-file>wecome2.jspwelcome-file>
    		<description>欢迎页面description>
    	welcome-file-list>
    web-app>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    上面代码中就配置了两个欢迎页面 wecome1.jsp 和 wecome2.jsp,显示时按照配置顺序显示,如果能找到 wecome1.jsp 文件就显示该文件,如果找不到就找第二个,依次类推。

    欢迎页面是用于访问 web 工程时,只给了根名,没有给出具体的页面,这时就回去访问配置的欢迎页面,如果没有配置欢迎页面,不同的应用服务器可能会有不同的行为。对于 Tomcat 来说,会默认先查找 index.html 文件,如果找到了,就将其返回给浏览器;如果没有找到,就继续查找 index.jsp 文件,如果都没有找到,那么 Tomcat 就会显示 The requested resource is not available 的页面。

    欢迎页面只是在没有给出具体的访问页面时会被用到,如果指定了具体页面,只要访问的路径正确,是可以正常访问的。

    3、配置Servlet

    Servlet命名和定制URL

    <web-app>
    	<servlet>
    		<servlet-name>TestServletservlet-name>
    		<servlet-class>com.yiyu.servlet.showAllServletservlet-class>
    	servlet>
    	<servlet-mapping>
    		<servlet-name>TestServletservlet-name>
    		<url-pattern>/TestServleturl-pattern>
    	servlet-mapping>
    web-app>
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    :注册的名字
    :配置的 Servlet 的全类名
    :为这个 Servlet 映射一个对外访问路径
    servlet 和 url-pattern 之间的关系是 一对多的关系。

    4、配置Filter

    参考:

    详见该博客

    包:servlet-api.jar
    在这里插入图片描述

    过滤器配置

    <web-app>
    	<filter>
    		<filter-name>Filter1filter-name>
    		<filter-class>D2020128.TestFilterfilter-class>
    		
    	filter>
    	
    	<filter-mapping>
    		<filter-name>Filter1filter-name>
    		<url-pattern>/TestServleturl-pattern>
    	filter-mapping>
    	<filter-mapping>
    		<filter-name>Filter1filter-name>
    		
    		<url—pattern>/*url-pattern>
    		
    		
    		
    		
    		
    		
    	filter-mapping>
    web-app>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • Filter 的 url-pattern 中配置的路径是访问已经存在的网络资源,如静态页面、jsp、servlet等。
    • filter 和 url-pattern 之间的关系是 多对多的关系。即,Filter可负责拦截多个请求或响应;一个请求或响应也可被多个Filter拦截。(多个 filter 会根据 web.xml 中配置的顺序组成 filter 链)。

    常用场合:
    (1)认证Filter
    (2)日志和审核Filter
    (3)图片转换Filter
    (4)数据压缩Filter
    (5)密码Filter
    (6)令牌Filter
    (7)触发资源访问事件的Filter
    (8)XSLT Filter
    (9)媒体类型链Filter

    此时你就可以对请求或响应(Request、Response)统一设置编码,简化操作;同时还可进行逻辑判断,如用户是否已经登陆、有没有权限访问该页面、权限管理、过滤敏感词汇 等等工作。它是随你的web应用启动而启动的,只初始化一次,以后就可以拦截相关请求,只有当你的web应用停止或重新部署的时候才销毁

    过滤器生命周期:初始化init() → 过滤doFilter() → 析构(销毁)destroy()
    过滤器有四种拦截方式!分别是:REQUEST、FORWARD、INCLUDE、ERROR。
    过滤器链 顺序:按照web.xml中配置的顺序

    4.1、如何创建Filter?

    类似于servlet,需两步
    第一步:创建Filter处理类(一般我们都用现有的)
    Filter必须实现javax.servlet.Filter接口,在该接口中定义了三个方法:
    (1) void init(FilterConfig config):用于Filter的初始化。FilteConfig用于访问Filter的配置信息。
    (2) void destroy():Filter销毁前的操作,例如完成某些资源的回收。
    (3) void doFilter(ServletRequest request,ServletResponse response,FilterChain chain):
    实现过滤功能的核心方法,实现对请求request进行预处理,也可以实现对服务器响应response进行后处理—它们的分界线为是否调用了chain.doFilter(request,response),执行该方法之前,即对用户请求request进行预处理,执行该方法之后,即对服务器响应response进行后处理。

    第二步:Web.xml文件中配置Filter
    Filter配置与Servlet的配置非常相似,区别在于Servlet通常只配置一个URL,而Filter可以同时配置多个请求的URL。配置Filter有两种方式:
    (1). 在Filter类中通过Annotation进行配置。
    (2). 在web.xml文件中通过配置文件进行配置。

    5、监听器

    <listener> 
        <listerner-class>com.listener.SessionListenerlistener-class> 
    listener>
    
    • 1
    • 2
    • 3

    监听器可以监听就是在 applicationsessionrequest 三个对象创建、销毁或者往其中添加修改删除属性时自动执行代码的功能组件。

    applicationServletContext类型的对象。ServletContext 代表整个web应用,在服务器启动的时候,tomcat会自动创建该对象。在服务器关闭时会自动销毁该对象。
    在这里插入图片描述

    6、配置会话超时

    单位为秒

    <session-config>
        <session-timeout>120session-timeout>
    session-config>
    
    • 1
    • 2
    • 3

    7、配置上下文参数

    声明应用范围内的初始化参数。用于向Servlet+Context提供键值对,即应用程序上下文信息。后续的listener,filter在初始化时会用到这些上下文信息。在servlet里面可以通过getServletContext().getInitParameter(“context/param”)得到

    <context-param>
        <param-name>log4jConfigurationparam-name>
        <param-value>/WEB-INF/log4j2.xmlparam-value>
    context-param>
    
    • 1
    • 2
    • 3
    • 4

    8、配置应用描述

    <disciption>Tomcat Example servlets and JSP pages.disciption>
    
    • 1

    9、配置应用名称

    <display-name>Tomcat Exampledisplay-name>
    
    • 1

    10、指定错误处理页面

    可以通过“异常类型”或“错误码”来指定错误处理页面。

    <error-page>
        <error-code>404error-code>
        <location>/error404.jsplocation>
    error-page>
    <error-page>
        <exception-type>java.lang.Exception<exception-type>
        <location>/exception.jsp<location>
    error-page>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    11、配置Web应用图标

    <icon>    
    	<small-icon>/images/app_small.gifsmall-icon>    
    	<large-icon>/images/app_large.giflarge-icon>    
    icon>
    
    • 1
    • 2
    • 3
    • 4

    12、配置安全限制

    <security-constraint>    
      <display-name>Example Security Constraintdisplay-name>    
       <web-resource-collection>    
          <web-resource-name>Protected Areaweb-resource-name>    
          <url-pattern>/jsp/security/protected/*url-pattern>
          <url-pattern>*.jspurl-pattern>
          
          <http-method>DELETEhttp-method>    
          <http-method>GEThttp-method>    
          <http-method>POSThttp-method>    
          <http-method>PUThttp-method>    
       web-resource-collection>
       
       
       
       <auth-constraint>
       	 <role-name>All Rolerole-name>
         <role-name>tomcatrole-name>    
         <role-name>role1role-name>    
       auth-constraint>
       
    security-constraint>
    
    <login-config>Xml代码   
        
      <auth-method>FORMauth-method>    
      <form-login-config>    
       <form-login-page>/login.htmlform-login-page>    
       <form-error-page>/error.htmlform-error-page>    
      form-login-config>    
    login-config>    
    <security-role>    
      <role-name>All Rolerole-name>    
    security-role>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36

    13、配置登录验证

    <login-config>    
      <auth-method>FORMauth-method>    
      <realm-name>Example-Based Authentiation Arearealm-name>    
      <form-login-config>    
         <form-login-page>/jsp/security/protected/login.jspform-login-page>    
         <form-error-page>/jsp/security/protected/error.jspform-error-page>    
      form-login-config>    
    login-config>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    初始化参数

    <web-app>
    	<servlet>
    		<servlet-name>InitParamServletservlet-name>
    		<servlet-class>InitParamServletservlet-class>
    		<init-param>
    			<param-name>encodingparam-name>
    			<param-value>utf-8param-value>
    		init-param>
    		<init-param>
    			<param-name>helloweenparam-name>		
    			<param-value>passwordparam-value>
    		init-param>
    		<init-param>
    			<param-name>adminparam-name>			
    			<param-value>adminparam-value>
    		init-param>
    		<init-param>
    			<param-name>babyfaceparam-name>	
    			<param-value>babyfaceparam-value>
    		init-param>
    		<load-on-startup>1load-on-startup>	
    		
    	servlet>
    	<servlet-mapping>
    		<servlet-name>InitParamServletservlet-name>
    		<url-pattern>/initParamServleturl-pattern>
    	servlet-mapping>
    web-app>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    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不匹配,显示登录页面。
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    使用到了枚举类型: Enumeration params = this.getInitParameterNames();

    1. 获取web.xml中所有的参数名: this.getInitParameterNames();
    2. 对枚举的遍历: while (params.hasMoreElements()){ …}
    3. 获取下一个元素: params.nextElement();
    4. 获取名称对应的值: getInitParameter(nameParam);
    5. 重定向: request.getRequestDispatcher(“/WEB-INF/notice.html”).forward(request,response);
  • 相关阅读:
    【云原生 | 从零开始学Kubernetes】十七、Kubernetes核心技术Service
    Java SOAP 调用 C# 的WebService
    Linux 服务器(Ubuntu) 安装 golang记录
    【软件测试】作为测试人,因工作与开发吵了一架碰撞,该咋办......
    Spring-AOP和事务管理
    Python里的list是数组吗?
    第3章 Linux多线程开发 01线程
    【无标题】
    手把手带你安装和使用 Git
    SpringCloud学习笔记 - 基础项目搭建
  • 原文地址:https://blog.csdn.net/weixin_41544662/article/details/128147204