servletConfig与servletContext

本文详细介绍了ServletConfig和ServletContext的概念、作用以及如何在Servlet中使用它们进行配置参数的获取。通过实例展示了如何配置参数并访问这些配置,旨在帮助开发者更高效地管理Servlet的配置。
 

servletConfig

servletconfig对象代表的servlet的配置对象,一般我们会将一些可能会产生变化的字符串配置在配置文件中,通过servletconfig去读取,每个servlet都有一个自己的congfig对象,servlet之间是不能共享config对象

 

参数可以配置很多个,但参数名不能相同

配置,在配置servlet的时候,需要配置两个元素

<servlet>

       <servlet-name>

       <servlet-class>

       <init-param>

                            <param-name>aaa</param-name>

                            <param-value>bbb</param-value>

       </init-param>

<servlet-mapping>

                            <servlet-name>

                            <url-pattern>

在servlet中使用ServletConfig

第一步,先获得servletcongfig对象

                     ServletConfig config = getServletConfig();

第二步,抓取配置参数

                     String value = config.getInitParameter("param-name");

 

servletContext

 

servletContext对象代表的是整个应用(项目),只有一份,任何servlet都能访问该对象,并且任何servlet访问到的context都是同一个

congfig用于给某个servlet配置一些常量,但是有些数据是很多servlet都需要的。那如果为每个servlet都配置一份,那么将来需要改动的时候就要为每个servlet的配置进行修改了。所以现在有了这个context之后,只需要配置一份,大家都共享,修改也只需要一份就好了

 

使用context

第一步,获得context对象

                     servletContext application= getServletContext();

第二步,抓取context的配置参数

              String value = application.getInitParameter("param-name");

 

 

配置context参数

<context-param>

              <param-name>...</param-name>

              <param-value>...</param-value>

</context-param>

 

使用servletContext保存对象,也就设置属性

设置在servletContext对象中的属性,任何servlet都是可以访问的。也就是说设置在servletContext的就是全局的。

 

设置属性

              application.setAttribute("属性名",属性值);

获得属性

              Object obj = application.getAttribute("属性名");

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值