context-param与init-param的区别与作用,web.xml加载顺序,容器访问认证

<context-param>的作用:
web.xml
的配置中<context-param>配置作用
1. 启动一个WEB项目的时候,容器(:Tomcat)会去读它的配置文件web.xml.读两个节点:<listener></listener>  <context-param></context-param>

2.紧接着,容器创建一个ServletContext(上下文),这个WEB项目所有部分都将共享这个上下文.

3.容器将<context-param></context-param>转化为键值对,并交给ServletContext.

4.容器创建<listener></listener>中的类实例,即创建监听.

5.在监听中会有contextInitialized(ServletContextEvent args)初始化方法,在这个方法中获得ServletContext =ServletContextEvent.getServletContext();
context-param
的值 =ServletContext.getInitParameter("context-param的键");

6.得到这个context-param的值之后,你就可以做一些操作了.注意,这个时候你的WEB项目还没有完全启动完成.这个动作会比所有的Servlet都要早.
换句话说,这个时候,你对<context-param>中的键值做的操作,将在你的WEB项目完全启动之前被执行.

7.举例.你可能想在项目启动之前就打开数据库.
那么这里就可以在<context-param>中设置数据库的连接方式,在监听类中初始化数据库的连接.

8.这个监听是自己写的一个类,除了初始化方法,它还有销毁方法.用于关闭应用前释放资源.比如说数据库连接的关闭.

:
<!-- 
加载spring的配置文件 -->
<context-param>
    <param-name>contextConfigLocation</param-name>
   <param-value>/WEB-INF/applicationContext.xml,/WEB-INF/action-servlet.xml,/WEB-

INF/jason-servlet.xml</param-value>
</context-param>
<listener>
   <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

又如: --->自定义context-param,且自定义listener来获取这些信息

<context-param>
    <param-name>urlrewrite</param-name>
    <param-value>false</param-value>
</context-param>
<context-param>
    <param-name>cluster</param-name>
    <param-value>false</param-value>
</context-param>
<context-param>
    <param-name>servletmapping</param-name>
    <param-value>*.bbscs</param-value>
</context-param>
<context-param>
    <param-name>poststoragemode</param-name>
    <param-value>1</param-value>
</context-param>
<listener>
   <listener-class>com.laoer.bbscs.web.servlet.SysListener</listener-class>
</listener>

public classSysListener extendsHttpServlet implements ServletContextListener {

private staticfinal Log logger = LogFactory.getLog(SysListener.class);

public void contextDestroyed(ServletContextEventsce) {

   //用于在容器关闭时,操作
}

//用于在容器开启时,操作

public void contextInitialized(ServletContextEventsce) {
   String rootpath =
 sce.getServletContext().getRealPath("/");
  System.out.println("-------------rootPath:"+rootpath);

   if(rootpath != null) {
    rootpath = rootpath.replaceAll("\\\\","/");
   } else {
    rootpath = "/";
   }
   if (!rootpath.endsWith("/")) {
    rootpath = rootpath + "/";
   }
   Constant.ROOTPATH = rootpath;
   logger.info("Application Run Path:" + rootpath);
   String urlrewrtie =
 sce.getServletContext().getInitParameter("urlrewrite");
   boolean burlrewrtie = false;
   if (urlrewrtie != null) {
    burlrewrtie = Boolean.parseBoolean(urlrewrtie);
   }
   Constant.USE_URL_REWRITE = burlrewrtie;
   logger.info("Use Urlrewrite:" + burlrewrtie);
   
其它略之....

   }

}
   /*
最终输出
   -------------rootPath:D:\tomcat_bbs\webapps\BBSCS_8_0_3\
   2009-06-09 21:51:46,526[com.laoer.bbscs.web.servlet.SysListener]-[INFO]

Application RunPath:D:/tomcat_bbs/webapps/BBSCS_8_0_3/
   2009-06-09 21:51:46,526[com.laoer.bbscs.web.servlet.SysListener]-[INFO]

UseUrlrewrite:true
   2009-06-09 21:51:46,526[com.laoer.bbscs.web.servlet.SysListener]-[INFO]

UseCluster:false
   2009-06-09 21:51:46,526[com.laoer.bbscs.web.servlet.SysListener]-[INFO]

SERVLETMAPPING:*.bbscs
   2009-06-09 21:51:46,573 [com.laoer.bbscs.web.servlet.SysListener]-[INFO]

Post StorageMode:1
   */

context-paraminit-param区别
web.xml
里面可以定义两种参数:
(1)application范围内的参数,存放在servletcontext中,在web.xml中配置如下:
<context-param>
          <param-name>context/param</param-name>
          <param-value>avalible during application</param-value>
</context-param>

(2)servlet范围内的参数,只能在servletinit()方法中取得,web.xml中配置如下:
<servlet>
    <servlet-name>MainServlet</servlet-name>
   <servlet-class>com.wes.controller.MainServlet</servlet-class>
    <init-param>
      <param-name>param1</param-name>
       <param-value>avalible in servletinit()</param-value>
    </init-param>
    <load-on-startup>0</load-on-startup>
</servlet>

servlet中可以通过代码分别取用:
package com.wes.controller;

importjavax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

public classMainServlet extends HttpServlet ...{

   public MainServlet() ...{
        super();
     }
    public void init() throws ServletException ...{
         System.out.println("
下面的两个参数param1是在servlet中存放的");
        System.out.println(this.getInitParameter("param1"));
         System.out.println("
下面的参数是存放在servletcontext中的");
       System.out.println(getServletContext().getInitParameter("context/param"));
      }
}

第一种参数在servlet里面可以通过getServletContext().getInitParameter("context/param")得到
第二种参数只能在servletinit()方法中通过this.getInitParameter("param1")取得.

 

 

 

定义

  context-param元素含有一对参数名和参数值,用作应用的ServletContext上下文初始化参数。参数名在整个Web应用中必须是惟一的。

  <!ELEMENT context-param (param-name, param-value,description?)>

  <!ELEMENT param-name (#PCDATA)>

  <!ELEMENT param-value (#PCDATA)>

  <!ELEMENT description (#PCDATA)>

编辑本段描述参数

  param-name 子元素包含有参数名,而param-value子元素包含的是参数值。作为选择,可用description子元素来描述参数。

  下面是一个含有context-param元素的有效部署描述符:

  <?xml version="1.0"encoding="ISO-8859-1"?>

  <!DOCTYPE web-app

  PUBLIC "-//Sun Microsystems, Inc.//DTD WebApplication 2.3//EN"

  <web-app>

  <context-param>

  <param-name>jdbcDriver</param-name>

  <param-value>com.mysql.jdbc.Driver</param-value>

  </context-param>

</web-app>

 

 

 

The load-on-startup element indicates that this servletshould be loaded (instantiated and have its init() called) on the startup ofthe web application. The optional contents of these element must be an integerindicating the order in which the servlet should be loaded. If the value is anegative integer, or the element is not present, the container is free to loadthe servlet whenever it chooses.  If the value is a positive integer or 0,the container must load and initialize the servlet as the application isdeployed. The container must guarantee that servlets marked with lower integersare loaded before servlets marked with higher integers. The container maychoose the order of loading of servlets with the same load-on-start-up value. 
这个 load-on-startup 元素 在 web 应用启动的时候指定了servlet被加载的顺序,它的值必须是一个整数。如果它的值是一个负整数或是这个元素不存在,那么容器会在该servlet被调用的时候,加载这个servlet 。如果值是正整数或零,容器在配置的时候就加载并初始化这个servlet,容器必须保证值小的先被加载。如果值相等,容器可以自动选择先加载谁。

 

 

 

 web.xml 中的listener filterservlet 加载顺序及其详解

一、概述

1、启动一个WEB项目的时候,WEB容器会去读取它的配置文件web.xml,读取<listener><context-param>两个结点。 

2、紧急着,容创建一个ServletContextservlet上下文),这个web项目的所有部分都将共享这个上下文。 

3、容器将<context-param>转换为键值对,并交给servletContext 

4、容器创建<listener>中的类实例,创建监听器。 

 load-on-startup

load-on-startup 元素在web应用启动的时候指定了servlet被加载的顺序,它的值必须是一个整数。如果它的值是一个负整数或是这个元素不存在,那么容器会在该 servlet被调用的时候,加载这个servlet 。如果值是正整数或零,容器在配置的时候就加载并初始化这个servlet,容器必须保证值小的先被加载。如果值相等,容器可以自动选择先加载谁。  

servlet的配置当中,<load-on-startup>5</load-on-startup>的含义是: 

标记容器是否在启动的时候就加载这个servlet 

当值为0或者大于0时,表示容器在应用启动时就加载这个servlet 

当是一个负数时或者没有指定时,则指示容器在该servlet被选择时才加载。 

正数的值越小,启动该servlet的优先级越高。 

  、加载顺序

首先可以肯定的是,加载顺序与它们在 web.xml 文件中的先后顺序无关。即不会因为 filter 写在 listener 的前面而会先加载 filter。最终得出的结论是:ServletContext -> listener ->filter -> servlet

        同时还存在着这样一种配置节:context-param,它用于向 ServletContext 提供键值对,即应用程序上下文信息。我们的 listener, filter 等在初始化时会用到这些上下文中的信息,那么 context-param 配置节是不是应该写在listener 配置节前呢?实际上 context-param 配置节可写在任意位置,因此真正的加载顺序为:context-param -> listener ->filter -> servlet

        对于某类配置节而言,与它们出现的顺序是有关的。以 filter 为例,web.xml 中当然可以定义多个 filter,与filter 相关的一个配置节是 filter-mapping,这里一定要注意,对于拥有相同 filter-name  filter  filter-mapping 配置节而言,filter-mapping 必须出现在 filter 之后,否则当解析到 filter-mapping 时,它所对应的 filter-name 还未定义。web 容器启动时初始化每个 filter 时,是按照 filter 配置节出现的顺序来初始化的,当请求资源匹配多个 filter-mapping 时,filter 拦截资源是按照 filter-mapping 配置节出现的顺序来依次调用 doFilter() 方法的。

        servlet filter 类似,此处不再赘述。

       由此,可以看出,web.xml 的加载顺序是:ServletContext -> context-param-> listener -> filter -> servlet ,而同个类型之间的实际程序调用的时候的顺序是根据对应的 mapping 的顺序进行调用的。

 web.xml文件详解 

 

我将自己知道的web.xml的元素整理了一下:

1web.xml首先是肯定要包含它的schema.

<web-appxmlns="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/web-app_2_4.xsd"
    version="2.4">

</web-app>

其它的元素都放在<web-app></web-app>之中。

<discription></discription> 是对站台的描述
<display-name></display-name> 
定义站台的名称
<distributable/> 
是指定该站台是否可分布式处理
<context-param></context-param> 
用来设定web站台的环境参数,它包含两个子元素:
    <param-name></param-name> 
用来指定参数的名称
    <param-value></param-value> 
用来设定参数值

比如:
<context-param>
    <param-name>my_param</param-name>
    <param-value>hello</param-value>
</context-param>

在此设定的参数,可以在servlet中用getServletContext().getInitParameter("my_param") 来取得

2listener

<listener></listener> 用来设定Listener接口,它的主要子元素为
    <listener-class></listener-class> 
定义Listener的类名称

比如:
<listener>
   <listener-class>com.myTest.ContextListener</listener-class> 
</listener>

3.1filter
<filter></filter> 
是用来声明filter的相关设定,它包含以下子元素:
    <filter-name></filter-name> 
这当然就是指定filter的名字
    <filter-class></filter-class> 
这是用来定义filter的类的名称
    <init-param></init-param> 
用来定义参数,它有两个子元素:
       <param-name></param-name> 
用来指定参数的名称
        <param-value></param-value>
用来设定参数值

比如:
<filter>
       <filter-name>setCharacterEncoding</filter-name>
       <filter-class>com.myTest.setCharacterEncodingFilter</filter-class>
        <init-param>
           <param-name>encoding</param-name>
           <param-value>GB2312</param-value>
        </init-param>
</filter>

3.2filter-mapping

<filter></filter>同时使用的是<filter-mapping></filter-mapping>用来定义filter所对应的URL,它有两个子元素:
    <filter-name></filter-name> 
指定filter的名字
    <url-pattern></url-pattern> 
指定filter所对应的URL

比如:
<filter-mapping>
       <filter-name>setCharacterEncoding</filter-name>
       <url-pattern>/*</url-pattern>
</filter-mapping>

4.1servlet

<servlet></servlet> 用来声明一个servlet的数据,主要有以下子元素:
    <servlet-name></servlet-name> 
指定servlet的名称
    <servlet-class></servlet-class> 
指定servlet的类名称
    <jsp-file></jsp-file> 
指定web站台中的某个JSP网页的完整路径
    <init-param></init-param> 
用来定义参数,和前面的<init-param>差不多

4.2servlet-mapping

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

比如:
<servlet>
       <servlet-name>ShoppingServlet</servlet-name>
       <servlet-class>com.myTest.ShoppingServlet</servlet-class>
</servlet>
<servlet-mapping>
       <servlet-name>ShoppingServlet</servlet-name>
       <url-pattern>/shop/ShoppingServlet</url-pattern>
</servlet-mapping>

5session-config
<session-config></session-config> 
用来定义web站台中的session参数,包含一个子元素:
    <session-timeout></session-timeout> 
用来定义这个web站台所有session的有效期限,单位为分钟

6mime-mapping
<mime-mapping></mime-mapping> 
定义某一个扩展名和某一个MIME Type做对映,包含两个子元素:
    <extension></extension> 
扩展名的名称
    <mime-type></mime-type> MIME
格式

比如:
<mime-mapping>
    <extension>doc</extension>
    <mime-type>application/vnd.ms-word</mime-type>
</mime-mapping> 
<mime-mapping>
    <extension>xls</extension>
    <mime-type>application/vnd.ms-excel</mime-type>
</mime-mapping>

7welcom-file-list
<welcome-file-list></welcom-file-list> 
用来定义首页的列单,包含一个子元素:
    <welcome-file></welcome-file> 
指定首页的文件名称

比如:
<welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>index.html</welcome-file>
</welcom-file-list>

8error-page
<error-page></error-page> 
用来处理错误代码或异常的页面,有三个子元素:
    <error-code></error-code> 
指定错误代码
    <exception-type></exception-type> 
指定一个JAVA异常类型
    <location></location> 
指定在web站台内的相关资源路径

比如:
<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>

9taglib
<taglib></taglib> 
用来设定JSP网页所用到的Tag Library路径,有两个子元素:
    <taglib-uri></taglib-uri> 
定义TLD文件的URI,在JSP网页中用taglib指令便可取得该URI TLD文件
    <taglib-location></taglib-location> 
指定TLD文件相对于web站台的存放位置

比如:
<taglib>
      <taglib-uri>myTaglib</taglib-uri>
     <taglib-location>/WEB-INF/tlds/MyTaglib.tld</taglib-location>
</taglib>

10resource-ref
<resource-ref></resource-ref> 
定义利用JNDI取得站台可利用的资源,有五个子元素:
    <description></description> 
资源说明
    <rec-ref-name></rec-ref-name> 
资源名称
    <res-type></res-type> 
资源种类
    <res-auth></res-auth> 
资源经由ApplicationContainer来许可
    <res-sharing-scope></res-sharing-scope> 
资源是否可以共享,有ShareableUnshareable两个值,默认为Shareable

比如,配置数据库连接池就可在此配置:
<resource-ref>
        <description>JNDI JDBCDataSource of shop</description>
       <res-ref-name>jdbc/sample_db</res-ref-name>
       <res-type>javax.sql.DataSource</res-type>
        <res-auth>Container</res-auth>
</resource-ref>

11jsp-config
<jsp-config> 
包括<taglib> <jsp-property-group> 两个子元素。
    
其中<taglib>元素在JSP 1.2时就已经存在;而<jsp-property-group>JSP 2.0 新增的元素。
    <jsp-property-group>
元素主要有八个子元素,它们分别为:
    1).<description>
:设定的说明;
    2).<display-name>
:设定名称;
    3).<url-pattern>
:设定值所影响的范围,如:/CH2  /*.jsp
    4).<el-ignored>
:若为true,表示不支持EL 语法;
    5).<scripting-invalid>
:若为true,表示不支持<% scripting %>语法;
    6).<page-encoding>
:设定JSP 网页的编码;
    7).<include-prelude>
:设置JSP 网页的抬头,扩展名为.jspf
    8).<include-coda>
:设置JSP 网页的结尾,扩展名为.jspf
一个简单的<jsp-config>元素完整配置:

<jsp-config>
    <taglib>
       <taglib-uri>Taglib</taglib-uri>
       <taglib-location>/WEB-INF/tlds/MyTaglib.tld</taglib-location>
    </taglib>
    <jsp-property-group>
        <description>Special propertygroup for JSP Configuration JSP example.</description>
       <display-name>JSPConfiguration</display-name>
        <url-pattern>/jsp/*</url-pattern>
       <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>  
配置web.xml来限制对某些servlet的请求

有时我们只希望通过认证的用户才能请求某些servlet的话,就可以在web.xml中来进行相应的配置,来达到此目的。

这就要用到<security-constraint></security-constraint>元素。
对于 tomcat,中web.xml使用security-constraint元素需要在位于<Tomcat-installation-directory>/conf/tomcat-users.xmlXML文件中创建用户名和密码。比如下面的这个tomcat- users.xml文件:

<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
  <role rolename="tomcat"/>
  <role rolename="manager"/>
  <role rolename="admin"/>
  <user username="tomcat" password="tomcat"roles="tomcat"/>
  <user username="both" password="tomcat"roles="tomcat,manager"/>
  <user username="admin" password="admin"roles="admin"/>
</tomcat-users>

XML片段包括一个tomcat-users根元素,它包含一个或多个roleuser元素。
然后在Web应用程序的web.xml中创建security-constraintlogin-configsecurity-role元素。

<security-constraint>
      <web-resource-collection>
         <web-resource-name>HelloServlet</web-resource-name>
         <url-pattern>/HelloServlet</url-pattern>
         <http-method>GET</http-method>
         <http-method>POST</http-method>
      </web-resource-collection>
      <auth-constraint>
          <description>Thisapplies only to the "tomcat" security role</description>
         <role-name>admin</role-name>
      </auth-constraint>
      <user-data-constraint>
         <transport-guarantee>NONE</transport-guarantee>
      </user-data-constraint>
  </security-constraint>
  <login-config>
      <auth-method>BASIC</auth-method>
  </login-config>
  <security-role>
      <role-name>admin</role-name>
  </security-role>

其中security-constraint元素包含一个或多个web-resource-collection元素,它是描述Web应用程序中的哪些web资源受到指定安全限制的保护。http-method元素指定安全限制覆盖的HTTP方法。上面的例子中,当我们对/HelloServlet GETPOST请求时将触发配置的安全机制。
auth-constraint
元素用于描述允许访问Web组件的安全角色。此例中安全角色的例子有tomcatmanageradmin。而只有当作为admin角色的用户才可以访问HelloServlet

Web应用程序通过login-config元素来认证用户,并确认该用户是否为正确的角色。
longin-config
包含的 transport-guarantee子元素用来指定认证方法,BASIC是一种常见的Web认证方式,浏览器给用户提示一个对话框,要求输入用户名和密码,随后Tomcat将给出的用户名和密码与tomcat-users.xml中的用户名和密码进行比较,然后使用前面的security- constraint配置来确定用户是否可访问受保护的servlet

(除BASIC外,还可以是FORMCLIENT-CERTDIGEST等)

其实这种认证方法实际上有两个步骤:
1
、检查提供的用户名和密码是否正确。
2
、判断用户是否映射到特定的安全角色。例如,用户可能提供了正确的用户名和密码,但没有映射到特定的安全角色,也将被禁止访问特定的Web资源。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值