Servlet中的ServletContext

1.ServletContext的生命周期,随软件发行或上线而存在,随软件卸载或停用而消失。

2.ServletContext主要应用于拿到路径,或拿到加载参数

1 拿到web.xml中配置的driver路径
ServletContext servletContext = this.getServletContext();
String driver = servletContext.getInitParameter("driver");
System.out.println(driver);
2.拿到webContent下的a.txt
String aPath = servletContext.getRealPath("/a.txt");
System.out.println(aPath);
3拿到web-inf下的b.txt的路径
String bPath = servletContext.getRealPath("/WEB-INF/b.txt");
System.out.println(bPath);
4.拿到src下的c.txt路径
String cPath = servletContext.getRealPath("/WEB-INF/classes/c.txt");
System.out.println(cPath);
//在读取src(classes)下的资源是可以同类加载器 ----专门加载classes 下的文件的
//getResource("")也是一个相对地址,相对于classes的
String path = ContextServlet.class.getClassLoader().getResource("c.txt").getPath();
System.out.println(path);

3.同时也可在servletContext中存储公共变量


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值