zoukankan      html  css  js  c++  java
  • web.xml配置文件详细解读

            对于一个J2EE应用的开发者,或者叫java web后台的开发者来说。经常会和web.xml打交道,偶尔用到几个标签不知道啥意思。然后就度娘一下,久而久之虽然大概知道web.xml的基本使用方法,但是没有一个系统的学习。我就是这样一个人,今天来系统的学习一遍。(http://docs.oracle.com/cd/E11035_01/wls100/webapp/web_xml.html#wp1070143

    1. web.xml学名叫做“部署描述文件”,是在Servlet规范中定义的。

    2. web.xml遵守DTD文件的定义,web-app为根元素,注意xml是区分大小写的。

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xmlns="http://java.sun.com/xml/ns/javaee"
             xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd "
             version="2.5">
    
    </web-app>

            3.icon、small-icon、large-icon:在GUI的IDEA中显示代表应用程序,因此没有实际意义。这个并不不是设置favicon。设置favicon应该在页面添加如下代码:

    <link rel="shortcut icon" href="http://example.com/favicon.ico" type="image/vnd.microsoft.icon" />
    <link rel="icon" href="http://example.com/favicon.ico" type="image/vnd.microsoft.icon" />

           4.<display-name>,<description>:作用分别是定义应用的名称和对应用做出描述。官网的描述:

            display-name:The optional display-name element specifies the Web application display name, a short name that can be displayed by GUI tools.可见意义也不是很大。

            description:The optional description element provides descriptive text about the Web application.

            5.<context-param>、param-name、param-value:设定上下文键值对,可在Java代码或JSP页面中按需读取。context-param也可放在servlet中,此时作用域就是servlet.

    <context-param>
       <param-name>param_name</param-name>
       <param-value>param_value</param-value>
    </context-param>

    在JSP页面读取:

    ${initParam.param_name}

    在servlet中读取:

    String param_name=getServletContext().getInitParamter("param_name");

    在Filter中读取:

            String param_name = request.getServletContext().getInitParameter("param_key");

             6.filter

    元素 选项 描述
    <icon> 可选 指定icon代表GUI的IDE中代表Filter,没有实际意义
    <filter-name> 必选 定义过滤器的名字,在部署描述文件的其他地方进行引用
    <display-name> 可选 在GUI的IDE中显示缩略名
    <description> 可选 A text description of the filter.
    <filter-class> 必选 过滤器对应的class
    <init-param> 可选 包含一个键值对,作为过滤器的初始属性

    一个简单的例子:

        <filter>
            <filter-name>LoginFilter</filter-name>
            <filter-class>com.xxxx.filter.LogFilter</filter-class>
            <init-param>
                <param-name>Site</param-name>
                <param-value>Hello world</param-value>
            </init-param>
        </filter>

    在过滤器初始化方法获取键值:

        public void init(FilterConfig config) throws ServletException {
            logger.info("Filter init");
            // 获取初始化参数
            String site = config.getInitParameter("Site");
            // 输出初始化参数
            logger.info("网站名称: " + site);
        }

    7、filter-mapping:

    元素 选项 描述
    <filter-name> 必选 映射URL或servlet的filter的名字
    <url-pattern> 必选或使用<servlet进行映射> 指定需要过滤的URL模式
    <servlet-name> 必选或者使用<url-pattern> 指定需要过滤的servlet name

    简要说明:使用<url-pattern>通过匹配URI调用过滤器,使用<servlet-name>,经过改servlet的所有请求都会走过滤器。如果同时配置<url-pattern>和<servlet-name>,只要满足其一都会走过滤器。

    一个简单的例子,所有的请求都会走LoginFilter过滤器:

        <filter-mapping>
            <filter-name>LoginFilter</filter-name>
            <url-pattern>/*</url-pattern>
            <!--<servlet-name>helloWorld</servlet-name>-->
        </filter-mapping>

    8、servlet

    元素 选项 描述
    <icon> 可选 指定icon代表GUI的IDE中代表Filter,没有实际意义
    <servlet-name> 必选 定义servlet名字,在部署描述文件其他地方可引用
    <display-name> 可选 在GUI的IDE中显示缩略名,没实际意义
    <description> 可选 servlet描述信息
    <servlet-class> 必选或使用<jsp-
    file>
    servlet对应的class,需使用完全限定名称(包含包名),在<servlet>中只能使用<servlet-class>或<jsp-
    file>其中之一
    <jsp-file> 必选或使用<servlet-class> 使用相对于应用程序根目录的全路径,在<servlet>中只能使用<servlet-class>或<jsp-
    file>其中之一
    <init-param> 可选 包含一个键值对作为servertd的初始化参数,每个键值对用<init-param> 分开
    <load-on-startup> 可选 设置web容器加载servlet的顺序,值为正整数,值越小优先级越高。不指定或者指定的值为非正整数加载顺序随机。
    <run-as> 可选 指定运行web程序的标识着,包含两个子标签 <description>和<role-name>
    <security-role-
    ref>
    可选

    引用定义在<security-role>中的安全角色名称,角色名称被硬编码在<security-role>,角色最终定义在容器对应的配置文件中,比如Tomcat中的tomcat-users.xml。该标签引用官网的一段说明如下:

    The security-role-ref element is used when an application uses the HttpServletRequest.isUserInRole(String role) method. The value of the role-name element must be the String used as the parameter to the HttpServletRequest.isUserInRole(String role) method. The role-link must contain the name of one of the security roles defined in the security-role elements. The container uses the mapping of security-role-ref to security-role when determining the return value of the call.

    https://docs.oracle.com/cd/E19226-01/820-7627/bncbb/index.html

    我理解的大概意思就是,为了配合servlet中代码对角色权限的控制,主要是isUserInRole方法,来决定servlet中的业务处理逻辑。

    9、servlet-mapping

    servlet-mapping元素定义了servlet和URL之间的映射

    元素 选项 描述
    <servlet-name> 必选 需要和URL映射的servlet的名称,名称和<servlet>中定义的名称一致
    <url-pattern> 必选 http://host:port + WebAppName后的部分的URL将会和这定义的URL比较,如果匹配的话就会调用其映射的servlet处理这次请求

    10、security-role

    元素 选项 描述
    <description> 可选 安全角色描述文本
    <role-name> 必选 角色名称。对于Tomcat和WebLogic,必须是两个容器中定义的角色,对于Tomcat在配置文件

    tomcat-users.xml中有相应角色和用户的对应。

    11、<security-role-ref>

    元素 选项 描述
    role-link
    必选 The <role-link> element in the security-role-ref element must match a <role-name> defined in the <security-role>element of the same web.xml deployment descriptor
    role-name
    可选

    在servlet中调用isUserInRole("tomcat-role"),参数就是该标签对应的值或者直接role-link标签对应的值。

     12、<security-constraint>

    定义对资源集合的访问权限

    元素 选项 描述
    <web-resource-
    collection>
    必选

    定义web应用程序资源集合

    <auth-constraint> 可选 定义访问这个集合资源的权限
    <user-data-
    constraint>
    可选 Defines how the client should communicate with the server.具体参考 user-data-constraint

    13、 <login-config>

    该标签用于配置验证方式。

    元素 选项 描述
    <auth-method> 可选

    指定验证的方法,可能值:

    BASIC—uses browser authentication. (This is the default value.)
    FORM—uses a user-written HTML form.
    CLIENT-CERT

    <realm-name> 可选  The name of the realm that is referenced to authenticate the user credentials
    <form-login-
    config>
    可选  Use this element if you configure the <auth-method> to FORM. 如果使用form表单进行验证的话还要配置form表单对应的文件,以及验证错误的跳转页面,具体参考:form-login-config

    针对以上8、9、10、11、12、13举个例子:

        <servlet>
            <servlet-name>ApiServlet</servlet-name>
            <servlet-class>com.xxxx.servlet.ApiServlet</servlet-class>
            <security-role-ref>
                <role-name>tomcat-role</role-name>
                <role-link>tomcat</role-link>
            </security-role-ref>
        </servlet>
        <servlet-mapping>
            <servlet-name>ApiServlet</servlet-name>
            <url-pattern>/api</url-pattern>
        </servlet-mapping>
        <security-constraint>
            <web-resource-collection>
                <web-resource-name>api</web-resource-name>
                <url-pattern>/api</url-pattern>
                <http-method>PUT</http-method>
                <http-method>DELETE</http-method>
                <http-method>GET</http-method>
                <http-method>POST</http-method>
            </web-resource-collection>
            <auth-constraint>
                <role-name>tomcat</role-name>
            </auth-constraint>
        </security-constraint>
        <login-config>
            <auth-method>BASIC</auth-method>
            <realm-name>My Hello World Application</realm-name>
        </login-config>    
        <security-role>
            <role-name>tomcat</role-name>
        </security-role>

    tomcat对应的tomcat-users.xml设置:

        <role rolename="tomcat"/>
        <!--<role rolename="role1"/>-->
        <user username="tomcat" password="tomcat123" roles="tomcat"/>
        <!--<user username="both" password="tomcat123" roles="tomcat,role1"/>-->
        <!-- <user username="role1" password="<must-be-changed>" roles="role1"/>-->
    ApiServlet中部分代码:
        @Override
        public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            RandomPwd randomPwd = RandomStringGenerator.getRandomString();
            Cookie cookie = new Cookie("tes123", "456");
            cookie.setMaxAge(60);
            response.addCookie(cookie);
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            PrintWriter out = response.getWriter();
            out.println(JSON.toJSONString(randomPwd));
            if (request.isUserInRole("tomcat")) {
                logger.info("Have tomcat role!");
            } else {
                logger.info("Don't have tomcat role!");
            }
    
            String param_name = getServletContext().getInitParameter("testkey");
            logger.info(param_name);
        }

     加上以上设置,只要访问/api接口就需要BASIC认证,验证通过了才能访问接口。

    14、resource-ref

    定义对外部资源的引用

    元素 选项 描述
    <description> 可选 简单的文本描述
    <res-ref-name> 必选 资源在JNDI树中的名字,servletz在web程序中使用这个名字去寻找这个资源的引用
    <res-type> 必选 资源在Java中定义的类型,必须使用完全限定名称。例如:<res-type>javax.sql.DataSource</res-type>
    <res-auth> 必选

    用于控制资源的安全性。

    If set to APPLICATION, indicates that the application component code performs resource sign on programmatically. If set to CONTAINER, WebLogic Server uses the security context established with the login-config element. See login-config.

    <res-sharing-scope> 可选 指定资源是否可以被共享,可选的值:
    • Shareable

    • Unshareable

    15、<listener>

    定义一个程序监听器

    元素 选项 描述
    <listener-class> 可选 响应web应用程序的的class

    注意:

    • Add an event declaration using the <listener> element. The event declaration defines the event listener class that is invoked when the event occurs. The <listener> element must directly follow the <filter> and <filter-mapping> elements and directly precede the <servlet> element. You can specify more than one event listener class for each type of event. WebLogic Server invokes the event listener classes in the order that they appear in the deployment descriptor (except for shutdown events, which are invoked in the reverse order). For example:
    <listener>
      <listener-class>myApp.MyContextListenerClass</listener-class>
    </listener>
    <listener>
      <listener-class>myApp.MySessionAttributeListenerClass</listener-class>
    </listener>

    大概意思是,listener-class必须跟在<filter>后面,<servlet>前面。

    常用的几个监听器:

    javax.servlet.http.HttpSessionEvent
    provides access to the HTTP session object
    javax.servlet.ServletContextEvent
    provides access to the servlet context object.
    javax.servlet.ServletContextAttributeEvent
    provides access to servlet context and its attributes
    javax.servlet.http.HttpSessionBindingEvent
    provides access to an HTTP session and its attributes
    Servlet Context Event Listener Class Example
    package myApp;
    import javax.servlet.http.*;
    public final class MyContextListenerClass implements
       ServletContextListener {
        public void contextInitialized(ServletContextEvent event) {
    
          /* This method is called when the servlet context is
             initialized(when the Web application is deployed). 
             You can initialize servlet context related data here.
          */ 
    
        }
        public void contextDestroyed(ServletContextEvent event) {
    
          /* This method is invoked when the Servlet Context 
             (the Web application) is undeployed or 
             WebLogic Server shuts down.
          */                
    
        }
    }

    参考链接:http://docs.oracle.com/cd/E13222_01/wls/docs81/webapp/app_events.html#178122

     16、welcome-file-list

    可选的welcome-file-list包含一个有顺序的welcome-file列表,当request请求的是一个目录的时候,该列表的第一个文件会被查找并返回,如果没找到就按列表顺序一值往下找。

    元素 选项 描述
    <welcome-file> 可选 被指定欢迎文件的名称,例如:index.html

    一个例子:

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

    17、session-config

    元素 选项 描述
    <session-timeout> 可选

    指定应用程序中session的有效时间,单位分钟。该值的设置会覆盖Tomcat或weblogic中的配置文件的设置,

    Default value: -2

    Maximum value: Integer.MAX_VALUE ÷ 60

    • -2:使用Tomcat或weblogic设置的值
    • -1:session永不过期,Tomcat或weblogic中设置的值被忽略。

    18、jsp-config

    元素 选项 描述
    <description> 可选 设定的说明 
    <display-name> 可选 设定名称 
    <url-pattern> 必选 设定值所影响的范围,如: /CH2 或 /*.jsp
    <el-ignored> 可选 若为 true,表示不支持 EL 语法 
    <scripting-invalid> 可选 若为 true,表示不支持 <% scripting %>语法 
    <page-encoding> 可选 设定 JSP 网页的编码 
    <include-prelude> 可选 设置 JSP 网页的抬头,扩展名为 .jspf
    <include-coda> 可选 设置 JSP 网页的结尾,扩展名为 .jspf
    trim-directive-whitespaces> 可选 sp中会经常使用到使用jsp标签和jstl的标签,比如<%@ page ..%>, <%@ taglib ...%>, <c:forEach....%>, 尤其是循环标签,在jsp最终输出的html中会产生大量的空行,使得性能降低。

    一个简单例子如下:

    <jsp-config>     
      <taglib>     
        <taglib-uri>Taglib</taglib-uri>     
        <taglib-location>/WEB-INF/tlds/MyTaglib.tld</taglib-location>     
      </taglib>     
      <jsp-property-group>     
        <description>Special property group for JSP Configuration JSP example.</description>     
        <display-name>JSPConfiguration</display-name>     
        <url-pattern>/jsp/* </url-pattern>     
      <trim-directive-whitespaces>true </trim-directive-whitespaces>  <el-ignored>true</el-ignored> <page-encoding>GB2312</page-encoding> <scripting-invalid>true</scripting-invalid> <include-prelude>/include/prelude.jspf</include-prelude> <include-coda>/include/coda.jspf</include-coda> </jsp-property-group> </jsp-config>
  • 相关阅读:
    使用vue做项目时,刷新页面,原本应该隐藏的东西闪一下
    input type="file" 上传文件的一些使用
    vue强制重新渲染
    元素focus页面不滚动不定位的JS处理
    js使用案例
    js使用setInterval简单实现一个时钟
    js日期封装方法
    scss简单使用总结
    JavaScript的内置对象(Global对象)
    JavaScript—Date对象详情
  • 原文地址:https://www.cnblogs.com/maxiaofang/p/7229563.html
Copyright © 2011-2022 走看看