Java的ServletContext的演示

第一个servlet保存数据
演示ServletContext中保存数据

public class AServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
//1、获取ServletContext对象
//2、调用其ServletContext()方法完成保存数据
		ServletContext application=this.getServletContext();
		application.setAttribute("name", "张三");
	}
}

第二个Servlet获取数据

public class BServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
//1、获取ServletContext对象
//2、调用其getAttribute()方法完成获取数据
		ServletContext appContext=this.getServletContext();
		String name=(String) appContext.getAttribute("name");
		System.out.println(name);
	}
}

第三个Servlet的是ServletContext公共的初始化参数

public class CServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
//1、获取ServletContext
//2、使用它getInitParameter(String)得到初始化参数
		ServletContext app=this.getServletContext();
		String value=app.getInitParameter("context-param");
		System.out.println(value);
	}
}

第四个Serlvet获取资源与路径
1、获取真实路径
还可以用SevletContext对象来获取Web应用下的资源,例如在hello应用的根目录下创建a.txt文件,现在想在Servlet中获取这个资源,就可以使用ServletContext来获取。
●获取a.txt的真实路径:String realPath=servletContext.getRealPath("/a.txt"),
realPath的值为a.txt文件的绝对路径:F:\tomcat6\webapps\hello\a.txt;有盘符的真实路径
●获取b.txt的真实路径:String path=servletContext.getRealPath("/WEB-INF/b.txt");

2、获取资源流
不只可以获取资源的路径,还可以通过ServletContext获取资源流,即把资源以输入流的方式获取
●获取a.txt资源流:InputStream in=servletContext.getResourceAsStream("/a.txt");
●获取b.txt资源流:InputStream in = servletContext.getResourceAsStream("/WEB-INF/b.txt");

3、获取指定目录下所有资源路径
还可以使用ServlerContext获取指定目录下所有资源路径,例如获取/WEB-INF下所有资源的路径
●Set set=context.getResourcePath("/WEB-INF");

public class DServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

//使用ServletContext获取资源路径,得到的是有盘符的路径
		String path=this.getServletContext().getRealPath("index.jsp");
		System.out.println(path);

//获取资源的路径后,再创建出输入流对象
InputStream inputStre=this.getServletContext().getResourceAsStream("index.jsp")
//获取当前路径所有资源下的路径

	Set<String>pathes=this.getServletContext().getResourcePaths("/WEB-INF");
		System.out.println(pathes);
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值