[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的内容还有多少记得,没想到模模糊糊也记不起多少,赶紧回头学回来.接下 ...
随机推荐
- Android 开发笔记___复选框__checkbox
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout ...
- empty()和remove()的区别
这两个都是删除元素,但是两者还是有区别的. remove()这个方法呢是删除被选元素的所有文本和子元素,当然包括被选元素自己. 而empty()呢,被选元素自己是不会被删除的. 比如: <div ...
- JavaScript sort() 方法详解
定义和用法 sort() 方法用于对数组的元素进行排序. 语法 arrayObject.sort(sortby) 参数 描述 sortby 可选.规定排序顺序.必须是函数. 返回值 对数组的引用.请注 ...
- 安装MongoDB启动时报错‘发生系统错误2’的解决办法
安装数据库mongodb启动时报"发生系统错误2". 这个问题是如果你之前已经装过一次,并且两次安装目录不同,就绝对会碰到的,因为你之前安装的路径已经在注册表中生成了,并没有随着你 ...
- js函数整合队列顺序执行插件
前言 在日常开发中,也许我们会遇到这样的一个问题.我们利用[发布订阅模式](如果不了解的可以直接访问此链接www.cnblogs.com/xiaoxiaokun- )去执行[发布]事件时,遇到函数内部 ...
- stm32l053r8 nucelo板的串口实验
stm32cubel0的HAL驱动实例中,基于stm32l53R8 nucelo板的官方串口通讯例程,是使用USART1实现在两块stm32l053r8 nucelo板间通讯.而在实际中,笔者手中只 ...
- javaScript属性
------------------------------------行内样式------------------------------------ *基本标签html 网页的开始标记head 网 ...
- C#中抽象类和接口的区别2
1.接口是为了满足外部调用而定义的一个功能约定, 因此反映的是事物的外部特性 抽象类是从一系列相关对象中抽象出来的概念, 因此反映的是事物的内部共性: 2. 下面分别从声明, ...
- C#泛型集合之List
1.命名空间:System.Collections.Generic(程序集:mscorlib)2.描述: 1).表示可通过索引访问的对象的强类型列表:提供用于对列表进行搜索.排序和操作的方法. 2). ...
- .net core 使用X509 私钥加密请求
1.获取证书路径 var basePath = _environment.ContentRootPath; //商户私钥证书,用于对请求报文进行签名 "); 2.数据加密 .net core ...