ServletContext的使用

ServletContext——每一个web工程都只有一个ServletContext对象。直白地说就是不管在哪个servlet里面,获取到的这个类的对象都是同一个。
通过ServletContext context = getServletContext()获取ServletContext对象。
配置文件如下所示:

<!--用于配置全局的参数,那个servlet都可以拿-->
<context-param>
	<param-name>address</param-name>
	<param-value>深圳</jparam-value>
</context-param>

ServletContext的作用

  1. 获取全局配置参数
    在class文件中
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	//1.获取对象
	String address = context.getInitparameter("address");
	System.out.println("address="+address);
}
  1. 获取web应用中的资源

2.1获取资源在tomcat里面的绝对路径——先得到路径,然后自己new InputStream。

String path = context.getRealPath("");//得到的是项目在tomcat里面的根目录。
//结果为:C:\Users\Software\Eclipse\projects\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\ServletRegister
Properties properties = new Properties();
InputStream is = new FileInputStream();
properties.load(is);
//获取name属性的值
String name = properties.getProperty("name");
System.out.println(name);
String path = context.getRealPath("file/config.properties");//得到的是文件config.properties
//结果为:C:\Users\Software\Eclipse\projects\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\ServletRegister\file\config.properties

绝对路径没有参照物。
相对路径有参照物,是相对工程在tomact里面的根目录。
2.2getResourceAsStream获取资源,流对象。——直接给出相对路径,然后获取流对象。

//获取web工程下的资源,转化成流对象。前面隐藏当前工程的根目录。
InputStream  is = context.getResourceAsStream("file/config.properties");
properties.load(is);
//获取name属性的值
String name = properties.getProperty("name");
System.out.println("name="+name);

2.3根据classloader去获取工程下的资源,类加载器(JDBC同样使用)。

默认classloader的路径是在classes文件夹中,因此必须回到项目的目录下,再进入file目录。返回上一级目录,使用…/。

//1.创建属性对象
Properties properties = new Properties();
//2.获取该java文件的class,然后获取到加载这个class到虚拟机中的那个类加载器对象
InputStream is = this.getClass().getClassLoader().getResourceAsStream("../../file/config.properties");
properties.load(is);
//3.获取name属性的值
String name =properties.getProperty("name");
System.out.println("name="+name);
  1. 存储数据即servlet间共享数据,获取数据。
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	 Integer count = context.getServletContext.setAttribute("count", ++count);
	 resp.setContextType("text/html;charset=UTF-8");
	 resp.getWriter().write("<h3>访问成功</h3>");
 }

ServletContex创建、销毁

当服务器启动的时候,会为托管的每一个web应用程序创建一个ServletContex对象。当从服务器移除托管的时候,或者关闭服务器的时候,ServletContext将销毁。

ServletContex作用范围

只要再相同项目中都可以取值。但A项目存,在B项目中无法取得。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值