Java ServletContext对象用法解析
ServletContext对象:
ServletContext类似字节码文件对象,在web创建的时候就自动生成了,并且是唯一的,跟随着项目和服务器共存亡了。通过这个对象,我们可以向里面存数据(键值对),也可以通过别的Servlet来获取这个数据;也可以根据相对(服务器)路径继来获取绝对路径。
ServletContext代表是一个web应用的环境(上下文)对象,ServletContext对象内部封装是该web应用的信息,ServletContext对象一个web应用只有一个。 一个web应用有几个servlet对象?----多个
ServletContext对象的生命周期?
创建:该web应用被加载(服务器启动或发布web应用(前提,服务器启动状态))
销毁:web应用被卸载(服务器关闭,移除该web应用)
获得ServletContext对象:
第一种:Servlet的init方法中获得ServletConfig 初始化方法
ServletContext servletContext = config.getServletContext ();
第二种:
ServletContext servletContext = config.getServletContext ();
ServletContext的作用:
获得web应用中任何资源的绝对路径(重要 重要 重要)
String path = context.getRealPath(相对于该web应用的相对地址);
public class Servlet01 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获取ServletContext对象 ServletContext context =getServletContext(); //获取相对于服务器的相对路径获取绝对路径 String patha=context.getRealPath("WEB-INF/classes/a.txt"); String pathb=context.getRealPath("b.txt"); String pathc=context.getRealPath("WEB-INF/c.txt"); //d.txt创建在WEB04文件下,不会在服务器上找到的。以后静态资源创建在WebContent下,项目文件、配置文件在src下 System.out.println(patha); System.out.println(pathb); System.out.println(pathc); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }
ServletContext是一个域对象(存储数据的区域):
存储数据的区域就是域对象;
ServletContext域对象的作用范围:整个web应用(所有的web资源都可以随意向 servletcontext域中存取数据,数据可以共享)
域对象的通用的方法:
setAtrribute(String name,Object obj); k是字符串 value是obj类型
getAttribute(String name); 强转
removeAttribute(String name);
public class Serlvlet03 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获取ServletContext对象 ServletContext context=getServletContext(); //获取ServletContext域中的值 String name=(String)context.getAttribute("name"); response.getWriter().write(name); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
相关文章
为什么在重写 equals方法的同时必须重写 hashcode方法
Object 类是所有类的父类,其 equals 方法比较的是两个对象的引用指向的地址,hashcode 是一个本地方法,返回的是对象地址值。他们都是通过比较地址来比较对象是否相等的2016-07-07java 集合之实现类ArrayList和LinkedList的方法
下面小编就为大家带来一篇java 集合之实现类ArrayList和LinkedList的方法。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧2017-10-10
最新评论