ServletContext是整个Web应用程序运行后的代表对象,能够通过ServletConfig的getServletContext()方法来取得,之后就能够利用ServletContext来取得Web应用程序的相关资源或信息。

ServletContext简单介绍

能够用ServletContext来与Web应用程序进行沟通。甚至是取得同一server上其它Web应用程序的ServletContext。

getRequestDispatcher()

该方法能够取得RequestDispatcher实例,使用时路径的指定必须以“/”作为开头,这个斜杠代表应用程序环境根文件夹(Context Root)。取得RequestDispatcher实例之后,就能够进行请求的转发(Forward)或包括(Include)。

this.getRequestDispatcher("/pages/some.jsp").forward(request, response);

以”/”作为开头时成为环境相对(context-relative)路径。没有以”/”作为开头则成为请求相对(request-relative)路径。

getResourcePaths()

假设想要知道Web应用程序的某个文件夹中都有哪些文件,则能够使用getResourcePaths()方法。

使用时,指定路径必须以”/”作为开头,表示相对于应用程序环境根文件夹。比如:

public class ShowPathServlet extends HttpServlet{
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE html>");
out.println("<head>");
out.println("<title>Resource Paths</title");
out.println("</head>");
out.println("<body>");
out.println("<ul>");
Iterator<String> paths = getServletContext().getResourcePaths("/").iterator();
while (paths.hasNext()) {
String path = paths.next();
out.println("<li>" + path + "</li>");
}
out.println("</ul>");
out.println("</body>");
out.println("</html>");
out.close();
}
}

getResourceAsStream()

假设想在Web应用程序中读取某个文件的内容,则能够使用getResourceAsStream()方法,运行路径时必须以“/”作为开头,表示相对于应用程序环境根文件夹,运行结果会返回InputStream实例,接着就能够运用它来读取文件内容。

使用java.io下的File、FileReader、FileInputStream等与文件读取相关的类时。能够指定绝对路径或相对路径。绝对路径是指文件在server上的真实路径。必须注意的是,指定相对路径时,此时路径不是相对于Web应用程序根文件夹,而是相对于启动Web容器时的命令运行文件夹。

以Tomcat为例,若在Servlet中运行下面语句:

out.println(new File("filename").getAbsolutePath());

则显示的是filename位于Tomcat文件夹下的bin文件夹中。

ServletContext初始參数

每一个Servlet都会有一个相相应的ServletConfig对象,我们能够在web.xml中定义Servlet时设置初始參数,之后通过ServletConfig的getInitParameter()方法来读取初始參数。通常最适合读取初始參数的位置在Servlet的无參数init()方法之中,由于Web容器初始Servlet后,会调用有參数的init()方法,而该方法又会调用无參数的init()方法。

每一个Web应用程序都会有一个相相应的ServletContext,针相应用程序初始化时所需用到的一些參数数据,能够在web.xml中设置应用程序初始化參数,设置时使用<context-param>标签来定义。比如:

<web-app ...>
<context-param>
<param-name>MESSAGE</param-name>
<param-value>/WEB-INF</param-value>
</context-param>
</web-app>

ServletContextListener

假设想要知道Web应用程序何时初始化或何时结束销毁,能够实现ServletContextListener,并在web.xml中设置告知web容器,在web应用程序初始化后果结束销毁前,调用ServletContextListener实现类中相相应的contextInitialized()或contextDestroyed()。

ServletContextListener接口定义例如以下:

/**
* Implementations of this interface receive notifications about changes to the
* servlet context of the web application they are part of. To receive
* notification events, the implementation class must be configured in the
* deployment descriptor for the web application.
*
* @see ServletContextEvent
* @since v 2.3
*/ public interface ServletContextListener extends EventListener { /**
** Notification that the web application initialization process is starting.
* All ServletContextListeners are notified of context initialization before
* any filter or servlet in the web application is initialized.
* @param sce Information about the ServletContext that was initialized
*/
public void contextInitialized(ServletContextEvent sce); /**
** Notification that the servlet context is about to be shut down. All
* servlets and filters have been destroy()ed before any
* ServletContextListeners are notified of context destruction.
* @param sce Information about the ServletContext that was destroyed
*/
public void contextDestroyed(ServletContextEvent sce);
}

当web容器调用contextInitialized()或contextDestroyed()时,会传入ServletContextEvent,其封装了ServletContext。能够通过ServletContextEvent的getServletContext()方法取得ServletConfig。之后就能够进行ServletContext初始參数的读取了。

对于多个Servlet都会使用到的信息,能够把它设置为ServletContext初始參数。能够在web.xml中做例如以下定义:

...
<context-param>
<param-name>BOOKMARK</param-name>
<param-value>/WEB-INF/bookmarks.txt</param-value>
</context-param>
<listener>
<listener-class>club.cuxing.web.BookmarkInitializer</listener-class>
</listener>
...

<listener><listener-class>标签用来定义实现了ServletContextListener接口的类名称。

一个实现了ServletContextListener接口的简单样例:

package club.chuxing.web;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.*; import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener; import club.chuxing.model.Bookmark; public class BookmarkInitializer implements ServletContextListener{
public void contextInitialized(ServletContextEvent sce) {
BufferedReader reader = null;
try {
ServletContext context = sce.getServletContext();
String bookmarkFile = context.getInitParameter("BOOKMARK");
reader = new BufferedReader(new InputStreamReader(
context.getResourceAsStream(bookmarkFile), "UTF-8")); List<Bookmark> bookmarks = new LinkedList<Bookmark>();
List<String> categories = new LinkedList<String>();
String input = null;
while ((input = reader.readLine()) != null) {
String[] tokens = input.split(",");
Bookmark bookmark = new Bookmark(tokens[0], tokens[1], tokens[2]);
bookmarks.add(bookmark);
if (!categories.contains(tokens[2])) {
categories.add(tokens[2]);
}
}
context.setAttribute("bookmarks", bookmarks);
context.setAttribute("categories", categories);
} catch (IOException ex) {
Logger.getLogger(BookmarkInitializer.class.getName())
.log(Level.SEVERE, null, ex);
} finally {
try {
reader.close();
} catch (IOException ex) {
Logger.getLogger(BookmarkInitializer.class.getName())
.log(Level.SEVERE, null, ex);
}
}
} public void contextDestroyed(ServletContextEvent sce) {
// TODO Auto-generated method stub
}
}

ServletContext属性

在整个web应用程序生命周期内,Servlet所需共享的数据能够设置为ServletContext属性。

由于ServletContext在web应用程序期间都会一直存在,所以对于设置为ServletContext属性的数据,除非你主动移除,否则也是一直存活于web应用程序之中的。ServletContext的相关方法:

  • setAttribute() 设置对象为ServletContext属性
  • getAttribute() 取出某个属性
  • removeAttribute() 移除某个属性

最新文章

  1. Android开发-API指南-Manifest介绍
  2. JNI层问题
  3. XML中的Xpath解析的例子
  4. MySQL锁机制
  5. 编程算法 - 最长上升子序列问题 代码(C)
  6. javascript笔记整理(运算符 )
  7. css基础和心得(四)
  8. Ajax实现页面动态加载,添加数据
  9. 自适应滤波:最小均方误差滤波器(LMS、NLMS)
  10. JAVA加密算法系列-AesEBC
  11. ServiceStack.OrmLite T4模板使用记录
  12. mac配置go使用gopm下载第三方包
  13. [Swift]LeetCode70. 爬楼梯 | Climbing Stairs
  14. Callback方法和JQuery链的解释
  15. Activiti6事件及监听器配置(学习笔记)
  16. python常见的数据转化函数
  17. ffmpeg源码编译安装(Compile ffmpeg with source) Part 2 : 扩展安装
  18. 浅谈Quartz定时任务调度
  19. luogu P1858 多人背包
  20. Redis数据&quot;丢失&quot;讨论及规避和解决的几点总结

热门文章

  1. Luogu 2296 寻找道路
  2. JS外链
  3. HTML学习笔记 div布局及table布局案例 第三节 (原创)参考使用表
  4. 原生js实现简单移动端轮播图
  5. Spring AOP高级——源码实现(2)Spring AOP中通知器(Advisor)与切面(Aspect)
  6. 使用.NET Core在RESTful API中进行路由操作
  7. C语言一些知识点回顾
  8. 通过 Visual Studio 的“代码度量值”来改进代码质量
  9. get和post请求及函数调用模式
  10. You may rarely look at it. But you&#39;ll always feel it