ServletContext的常见使用

1. 获取到整个 web 应用的配置信息

string url=this.getServletContext().getInitParameter("url");

String username=this.getServletContext().getInitParameter("username");

String password=this.getServletContext().getInitParameter("password");

2.实现 servlet 转发

this.getServletContext().setAttribute("data","serlvet数据转发”);

RequestDispatcherrd=this.getServletContext().getRequestDispatcher("/viewdata.jsp");

rd.forward(request,response);

3. 读取资源文件

在实际开发中,用作资源文件的文件类型,通常是:xml、properties,而读取xml 文件必然要进行 xml文档的解析,所以以下例子只对 properties 文件进行读取(在一个 web 工程中,只要涉及到写地址,建议最好以/开头)

在 web 工程中,我们一般来说,是不能采用传统方式读取配置文件的,因为相对的是jvm 的启动目录(tomcat 的 bin 目录),所以我们要使用 Web 绝对目录来获取配置文件的地址。

第一种:使用ServletContext的getResourceAsStream 方法:返回资源文件的读取字节流。

InputStream in=this.getServletContext().getResourceAsstream("/WEB-INF/classes/db.properties");

Properties prop = newProperties();

prop.load(in);

String url =prop.getProperty("url");

第二种:使用ServletContext的getRealPath 方法,获得文件的完整绝对路径 path,再使用字节流读取 path 下的文件。

String path=this.getServletContextO.getRealPath("/WEB-INF/classes/db.properties");

String filename =path.substring(path.1astIndexOf("\\")+1);

//相比第一种方法的好处是,除了可以获取数据,还可以获取资源文件的名称

FileInputstream in = newFileInputStream(path);

Properties prop= newProperties();

prop.load(in);

String url =prop.getProperty("url");

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值