如何获取全局的servlet对象的配置信息

ServletContext的定义和作用:
//ServletContext:表示全局的Servlet配置对象,整个项目就一个ServletContext对象,被所有的Servlet所共用

ServletContext的别名:application

//1.获取getServletContext()对象,三种方式创建的对象都是同一个对象
ServletContext sc1 = this.getServletConfig().getServletContext();
ServletContext sc2 = this.getServletContext();
ServletContext sc3 = request.getServletContext();


//2.使用ServletContext对象

① //获取文件的绝对路径(重要的用法*),其意义是当使用IO流时需要设置文件路径,用该方法可以快速获取
String realPath = sc1.getRealPath("img/1.jpg");
System.out.println(realPath);


② //获取全局的配置信息(获取初始化或请求参数)
String in = sc1.getInitParameter("gender");
System.out.println(in);

全局初始化参数的设置如下:

在web.xml文件中设置,使用于全局的配置信息

注意:是在<servlet>标签之外设置(类似的)如下信息

<context-param>
<param-name>gender</param-name>
<param-value>man</param-value>
</context-param>

③ //上下文路径(context root/context path):部署在tomcat/webapps下的目录名称或访问项目的项目路径
String contextPath = sc1.getContextPath();
System.out.println(contextPath);


④ //遍历某个文件夹下的资源路径
Set<String> resourcePaths = sc1.getResourcePaths("/img");
for (String string : resourcePaths) {
System.out.println(string);
}

⑤//设置一些数据保存在ServletContext中(重要的用法*)
sc1.setAttribute("msg", "hello");
System.out.println(this.getServletContext().getAttribute("msg"));

猜你喜欢

转载自www.cnblogs.com/su-chu-zhi-151/p/11200154.html