ServletContext

 

 

 

三大域对象

ØServletContext

ØHttpSession

ØHttpServletRequest

 

功能

Ø获取WEB应用程序的初始化参数。

Ø获取项目的真实的路径。

Ø做为域对象,保存多个客户共享的数据。

例如

<!-- 配置整个项目的初始化参数 --> 
<context-param>
  <param-name>companyName</param-name>
  <param-value>hpe</param-value>
</context-param>
<context-param>
  <param-name>addr</param-name>
  <param-value>jining</param-value>
</context-param>
//获取全局初始化参数
ServletContext ctx = getServletContext();
Enumeration<String> en = ctx.getInitParameterNames();
while (en.hasMoreElements()) {
  String nm = (String) en.nextElement();
  //根据初始化的名字获取值
  String value = ctx.getInitParameter(nm);
  out.print(nm+":"+value+"<hr>");
}
//获取真实路径
out.print(ctx.getRealPath("/")+"<hr>");
//获取项目应用上下文
out.print(ctx.getContextPath()+"<hr>");

输出结果:

在浏览器上输出一组图片

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//设置响应格式
		resp.setContentType("text/html;charset=utf-8");
		PrintWriter out=resp.getWriter();//浏览器输出对象
		//1.获取ServletContext对象
		ServletContext context= getServletContext();
		//2.获取项目上图片的文件夹的真实路径
		String path =context.getRealPath("/img");
		out.write("目录的路径为:"+path+"<hr />");
		//3.列出当前目录向的所有文件,用file
		File file=new File(path);
		String[] names=file.list();
		//遍历所有图片名称
		for (String string : names) {
			out.write(string+"<hr/>");
		}
		//在浏览器上显示img图片
		for(String string1 : names){
			out.write("<img src='img/"+string1+"' />");
		}
		
		
	}

显示效果:

作为域对象,共享数据

获取访问量

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  //1、获取ServletContext
  ServletContext sct = getServletContext();
  //2、取值
  int count = (int) sct.getAttribute("count");
  count++;
  //3、在放回ServletContext
  sct.setAttribute("count", count);
  resp.setContentType("text/html;charset=UTf-8");
  resp.getWriter().print("好文章.....<hr/>");
  resp.getWriter().print("Count is:"+count);
}

 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值