[Servlet&JSP] 初识ServletContext
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&JSP] 初识ServletContext的更多相关文章
- Servlet,jsp,JSP技术 ,JSP编程
一.Servlet 思考 1 浏览器可以直接打开JAVA/class文件吗? 不可以 2浏览器可以打开HTML.JS 文件吗? 可以 3 JAVA程序可以生成HTML文件吗?可以的,用IO流. 4 ...
- Servlet、JSP选择题(2)
Java EE软件工程师认证考试 试题库-选择题 一. 选择题(包括单选和双选) 1.B 编写一个Filter,需要( ) A. 继承Filter 类 B. 实现Filter 接口 C. 继承 ...
- javaEE servlet获取jsp内置对象
既然jsp和servlet是等价的,在jsp中能够使用内置对象,那么在servlet中也能够使用. 1.获得out对象 能够使用例如以下代码获得out对象: import java.io.PrintW ...
- Servlet和JSP读书笔记(二)
一. GenericServlet 1. 前面写的 Servlet和JSP学习笔记(一) 中的实例都是通过实现Servlet接口编写的,这样存在的问题就是:你必须实现Servlet中的所有方法,而不管 ...
- Servlet和JSP读书笔记(一)
Java Servlet 技术,简称Servlet,是Java中用于开发web应用程序的基本技术. Servlet实际上也就是一个Java程序.一个Servlet应用程序通常包含很多Servlet.而 ...
- JavaWeb -- 服务器传递给Servlet的对象 -- ServletConfig, ServletContext,Request, Response
1. ServletConfig 有一些东西不合适在程序中写死,应该写在web.xml中,比如 文字怎么显示, 访问数据库名 和 密码, servlet要读取的配置文件 等等.. l在Servle ...
- Servlet和JSP之标签文件学习
在上一篇文章中介绍了自定义标签的用法,接下来介绍标签文件的用法啦. tag file指令 tag file简介 用tag file的方式,无需编写标签处理类和标签库描述文件,也可以自定义标签.tag ...
- Servlet和JSP之有关Servlet和JSP的梳理(二)
JSP JSP页面本质上是一个Servlet,JSP页面在JSP容器中运行,一个Servlet容器通常也是JSP容器. 当一个JSP页面第一次被请求时,Servlet/JSP容器主要做一下两件事情: ...
- Servlet和JSP之有关Servlet和JSP的梳理(一)
大二第一学期的时候有学JSP的课,但是因为在开学之前做过JSP的小项目,所以一个学期的课也没听,直到期末考试成绩出来了,才回想JSP的内容还有多少记得,没想到模模糊糊也记不起多少,赶紧回头学回来.接下 ...
随机推荐
- 状态码为 200 from cache和304 Not modified的区别
1.请求状态码为 200 from cache: 表示该资源已经被缓存过,并且在有效期内,所以不再向浏览器发出请求,直接使用本地缓存. 如下图: 2.状态码为 304 Not modified: 表 ...
- 雅虎公司C#笔试题及参考答案
Question 1. (单选) 在计算机网络中,表征数据传输可靠性的指标是——21. 传输率2. 误码率3. 信息容量4. 频带利用率Question 2. (单选) 以下关于链式存储结构的叙述中哪 ...
- JDBC数据源 使用JNDI连接池实现数据库的连接
0.引言 许多Web应用程序需要通过JDBC驱动程序访问数据库,以支持该应用程序所需的功能.Java EE平台规范要求Java EE应用程序服务器为此目的提供一个DataSource实现(即,用于JD ...
- [转载] Tomcat架构分析
转载自http://gearever.iteye.com/category/223001
- [转载] Java并发编程:Callable、Future和FutureTask
转载自http://www.cnblogs.com/dolphin0520/p/3949310.html 在前面的文章中我们讲述了创建线程的2种方式,一种是直接继承Thread,另外一种就是实现Run ...
- [转]DBCC (Transact-SQL)
http://msdn.microsoft.com/zh-cn/library/ms188796.aspx Transact-SQL 编程语言提供 DBCC 语句以作为 SQL Server 的数据库 ...
- Linux 性能搜集【linux_reports-cpu/memory/disks/network】
为方便问题发生后,问题原因的分析排查,我们可以在服务器中事先部署如下脚本,方便故障发生后,问题原因的分析排查 脚本部署方法: 1.将脚本[linux_reports.sh]上传到服务器 2.登陆虚拟机 ...
- 程序、计算机程序、java初论
一.程序? 程序一词来自生活,通常指完成某些事情的一种既定方式和过程,可以将程序看成对一系列动作的执行过程的描述. 例如:个人去银行取钱 1.带上存折/银行卡去银行 2.取号排队 3.将存折或储蓄卡递 ...
- 为什么我的子线程更新了 UI 没报错?借此,纠正一些Android 程序员的一个知识误区
开门见山: 这个误区是:子线程不能更新 UI ,其应该分类讨论,而不是绝对的. 半小时前,我的 XRecyclerView 群里面,一位群友私聊我,问题是: 为什么我的子线程更新了 UI 没报错? 我 ...
- spring boot自定义log4j2日志文件
背景:因为从 spring boot 1.4开始的版本就要用log4j2 了,支持的格式有json和xml两种格式,此次实践主要使用的是xml的格式定义日志说明. spring boot 1.5.8. ...