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() 移除某个属性

[Servlet&amp;JSP] 初识ServletContext的更多相关文章

  1. Servlet,jsp,JSP技术 ,JSP编程

     一.Servlet 思考 1 浏览器可以直接打开JAVA/class文件吗? 不可以 2浏览器可以打开HTML.JS 文件吗? 可以 3 JAVA程序可以生成HTML文件吗?可以的,用IO流. 4 ...

  2. Servlet、JSP选择题(2)

    Java EE软件工程师认证考试 试题库-选择题 一.    选择题(包括单选和双选) 1.B 编写一个Filter,需要(  ) A. 继承Filter 类 B. 实现Filter 接口 C. 继承 ...

  3. javaEE servlet获取jsp内置对象

    既然jsp和servlet是等价的,在jsp中能够使用内置对象,那么在servlet中也能够使用. 1.获得out对象 能够使用例如以下代码获得out对象: import java.io.PrintW ...

  4. Servlet和JSP读书笔记(二)

    一. GenericServlet 1. 前面写的 Servlet和JSP学习笔记(一) 中的实例都是通过实现Servlet接口编写的,这样存在的问题就是:你必须实现Servlet中的所有方法,而不管 ...

  5. Servlet和JSP读书笔记(一)

    Java Servlet 技术,简称Servlet,是Java中用于开发web应用程序的基本技术. Servlet实际上也就是一个Java程序.一个Servlet应用程序通常包含很多Servlet.而 ...

  6. JavaWeb -- 服务器传递给Servlet的对象 -- ServletConfig, ServletContext,Request, Response

    1.  ServletConfig  有一些东西不合适在程序中写死,应该写在web.xml中,比如 文字怎么显示, 访问数据库名 和 密码, servlet要读取的配置文件 等等.. l在Servle ...

  7. Servlet和JSP之标签文件学习

    在上一篇文章中介绍了自定义标签的用法,接下来介绍标签文件的用法啦. tag file指令 tag file简介 用tag file的方式,无需编写标签处理类和标签库描述文件,也可以自定义标签.tag ...

  8. Servlet和JSP之有关Servlet和JSP的梳理(二)

    JSP JSP页面本质上是一个Servlet,JSP页面在JSP容器中运行,一个Servlet容器通常也是JSP容器. 当一个JSP页面第一次被请求时,Servlet/JSP容器主要做一下两件事情: ...

  9. Servlet和JSP之有关Servlet和JSP的梳理(一)

    大二第一学期的时候有学JSP的课,但是因为在开学之前做过JSP的小项目,所以一个学期的课也没听,直到期末考试成绩出来了,才回想JSP的内容还有多少记得,没想到模模糊糊也记不起多少,赶紧回头学回来.接下 ...

随机推荐

  1. 原生promise

    你应该会用事件加回调的办法来处理这类情况:   var img1 = document.querySelector('.img-1'); img1.addEventListener('load', f ...

  2. vue初级学习--路由router的编写(resolve的使用)

    一.导语 最近在用vue仿写淘宝的商品详情页面以及加入购物车页面,若是成功了,分享给大家~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 二.正文 我先用控制台创建了vue项目demo(如 ...

  3. 【持续更新】JavaScript常见面试题整理

    [重点提前说]这篇博客里的问题涉及到了了JS中常见的的基础知识点,也是面试中常见的一些问题,建议初入职场的园友Mark收藏,本文会持续更新~ 1. 引入JS的三种方式 1.在HTML标签中直接使用,直 ...

  4. spring boot跨域设置

    定义 跨域是指从一个域名的网页去请求另一个域名的资源 跨域背景 限制原因 如果一个网页可以随意地访问另外一个网站的资源,那么就有可能在客户完全不知情的情况下出现安全问题 为什么要跨域 公司内部有多个不 ...

  5. Python之getopt模块

    1.getopt——C风格命令行解析 http://docs.python.org/2.7/library/getopt.html#module-getopt getopt.getopt(args, ...

  6. FPGA时钟分频(转)

    http://www.cnblogs.com/fpga/archive/2009/10/24/1589318.html 占空比为50%的分频 偶数分频比较简单 比如N分频,那么计数到N/2-1,然后时 ...

  7. linux使用yum安装mariadb

    一,安装 yum install mariadb mariadb-server 二,如何设置密码 用root 进入mysql后  mysql>set password =password('你的 ...

  8. Unity3D获取资源的方法整理:

    在使用Unity3D做项目时,获取资源的方法大致分为两种.一种是通过写代码的方式,在程序运行时,自动获取资源:一种是通过手动拖拽的方式进行获取.不管是什么类型的资源都能通过这两种方式获得,下面拿图片资 ...

  9. redis配置文件之复制

    主从复制使用slaveof将Redis实例作为另一个Redis服务器的副本. 1) Redis复制是异步的,master可以配置成如果它连接的slave没有达到给定的数量,就停止接受写入.2) 如果断 ...

  10. 关于控制台输出 警告 log4j:WARN No appenders could be found for logger

    新建struts2项目时出现警告 log4j:WARN No appenders could be found for logger 于是上网搜查了解决方案 转自:最爱NBA 在src下面新建file ...