ServletContext

ServletContext

基本概述

     servletContext接口是Servlet中最大的一个接口,呈现了web应用的Servlet视图。ServletContext实例是通过 getServletContext()方法获得的,由于HttpServlet继承GenericServlet的关系,GenericServlet类和HttpServlet类同时具有该方法。

     每个应用都会有一个ServletContext对象与之关联,当容器分布在在多个虚拟机上时,web应用在所分布的每个虚拟机上都拥有一个ServletContext实例.缺省情况下,ServletContext不是分布式的,并且只存在于一个虚拟机上。

参考文档:http://tomcat.apache.org/tomcat-5.5-doc/servletapi/index.html

 

ServletContext原理图


PS:一个WEB服务器上所有的Servlet共享一个ServletComtext

 

小结

1ServletContext 是在服务器
2ServletContext 是被所有客户端共享
3ServletContext 是当web应用启动的时候,自动创建
4ServletContext web应用关闭/tomcat关闭/web应用reload 会造成servletContext销毁
5ServletContext 与 SessionRequest一样都能存入属性、取出属性,但是其作用域和生命周期是不同的

     1ServletContext作用域是整个WEB应用,生命周期是从服务器启动到关闭

     2Session作用域是对应的会话,生命周期是从会话创建到会话销毁

     3Request作用域是一次响应,生命周期是一次响应(服务器将HTTP响应发给浏览器)

6ServletContext能够通过以下几种方式使用

     1、获取

        this.getServletConfig().getServletContext();

         this.getServletContext(); //两种效果一样,推荐下面这种

     2、添加属性

         this.getServletContext().setAttribute(String,Object);

     3、取出属性

         this.getServletContext().getAttribute(属性名);

     4、移除属性  //注意:痛SessionRequest一样,移除属性只能一个一个移除

         this.getServletContext().removeAttribute(属性名);

 

ServletContext应用

1获取WEB应用的初始化参数
<!-- 如果希望所有的servlet都可以访问该配置. -->
<context-param>
	<param-name>name</param-name>
	<param-value>scott</param-value>
</context-param>

如何获取

String val= this.getServletContext().getInitParameter("name");

2使用ServletContext实现跳转
//目前我们跳转到下一个页面
//1 response.sendRedirect("/web应用名/资源名");
//2 request.getRequestDispatcher("/资源名").forward(request, response);
/*
* 区别1. getRequestDispatcher 一个跳转发生在web服务器 sendRedirect发生在浏览器
 *     2. 如果request.setAttribute("name","Switch") 希望下一个页面可以使用属性值,则使用 getRequestDispatcher
*	   3. 如果session.setAttribute("name2","Switch2"), 希望下一个页面可以使用属性值,则两个方法均可使用,但是建议使用 getRequestDispatcher
*    4. 如果我们希望跳转到本web应用外的一个url,应使用sendRedirect
 */
//3.这种方法和2一样
this.getServletContext().getRequestDispatcher("/资源url").forward(request, response);

3读取文件,和获取文件全路径
//首先读取到文件
InputStream inputStream=this.getServletContext().getResourceAsStream("dbinfo.properties");
//创建Properties
Properties pp=new Properties();
pp.load(inputStream);
out.println("name="+pp.getProperty("username"));
//如果文件放在src目录下,应该使用类加载器来读取
//InputStream is=Servlet5.class.getClassLoader().getResourceAsStream("dbinfo.properties");
//获取文件全路径
//读取到一个文件的全路径
String path=this.getServletContext().getRealPath("/imgs/Sunset.jpg");
out.println("paht = "+path);

4.获取外部资源

1.通过getResource方式获取外部资源
        // 1. 通过getResource方式获取外部资源
        try {
            URL uri = context.getResource("/WEB-INF/classes/stuInfo.properties");
            InputStream in1 = uri.openStream();
            System.out.println(GeneralUtil.getProperty("name", in1));
            in1.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

2.通过getResourceAsStream方式获取外部资源
        // 2. 通过getResourceAsStream的方式获取外部资源
        try {
            InputStream in2 = context.getResourceAsStream("/WEB-INF/classes/stuInfo.properties");
            System.out.println(GeneralUtil.getProperty("name", in2));
            in2.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

3.通过getRealPath获取外部资源的绝对路径,再通过文件流获取外部资源
        // 3. 通过getRealPath获取外部资源的绝对路径,再通过文件流获取外部资源
        try {
            String path = context.getRealPath("/WEB-INF/classes/stuInfo.properties");
            FileInputStream in3 = new FileInputStream(path);
            System.out.println(GeneralUtil.getProperty("name", in3));
            in3.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
工具类及资源文件
package com.pc.utils;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * Created by switch on 16/8/23.
 */
public class GeneralUtil {
    public static String getProperty(String key, InputStream in) throws IOException{
            Properties pp = new Properties();
            pp.load(in);
            return pp.getProperty(key);
    }
}

# students info
name=zs
sex=man
age=20

目录结构


PS:该项目使用Maven管理,所以开发环境下的resource目录,在Tomcat部署之后,则在WEB-INF/classes目录下。

----------参考《韩顺平.细说Servlet


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值