Java Servlet(三):Servlet中ServletConfig对象和ServletContext对象
本文将记录ServletConfig/ServletContext中提供了哪些方法,及方法的用法。
ServletConfig是一个抽象接口,它是由Servlet容器使用,在一个servlet对象初始化时,Servlet容器传递信息给正在初始化的servlet对象。
public abstract interface javax.servlet.ServletConfig {
public abstract java.lang.String getServletName();
public abstract javax.servlet.ServletContext getServletContext();
public abstract java.lang.String getInitParameter(java.lang.String arg0);
public abstract java.util.Enumeration getInitParameterNames();
}
- getServletName()方法:
用来返回当前servlet在web.xml注册的servlet-name;
- getServletContext()方法:
获取servlet上下文信息。
- getInitParameter(String arg0)方法:
根据一个指定的参数名称,获取在servlet初始化时传递的参数值,而这样的参数信息往往配置在web.xml。
- getInitParameters()方法:
返回servlet初始化时,传递进来的所有参数名称集合。
为了能了解到ServletConfig相关的使用,我们需要在之前新建的MyServlet001工程中,修改web.xml,在<servlet>节点中添加<init-param>节点:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0"> <!-- 配置和映射 servlet -->
<servlet>
<!-- Servlet注册的名字 -->
<servlet-name>helloServlet</servlet-name>
<!-- Servlet全类名 -->
<servlet-class>com.dx.hello.HelloServlet</servlet-class> <!-- 配置Servlet的初始化参数。且节点必须在 load-on-startup节点的前边 -->
<init-param>
<param-name>username</param-name>
<param-value>user001</param-value>
</init-param>
<init-param>
<param-name>password</param-name>
<param-value>123456</param-value>
</init-param> <!-- 指定servlet被初始化的时机 -->
<load-on-startup>-1</load-on-startup>
</servlet>
<servlet-mapping>
<!-- 对应servlet节点下的servlet-name的注册名字一致 -->
<servlet-name>helloServlet</servlet-name>
<!-- 映射具体的访问路径,其中/代表当前web的根目录 -->
<url-pattern>/hello</url-pattern>
</servlet-mapping> </web-app>
在配置参数时,需要注意事项:
<load-on-startup>节点必须在<init-param>节点的下边,否则会抛出异常信息,配置不通过。
之后再HelloServlet的init方法中,添加代码:
public void init(ServletConfig config) throws ServletException {
System.out.println("init");
// 根据ServletConfig的getInitParameter()方法,根据特定初始化参数名称,获取对应的初始化参数值。
String username = config.getInitParameter("username");
String password = config.getInitParameter("password");
System.out.println("username:" + username);
System.out.println("password:" + password);
// 根据ServletConfig的getInitParameterNames()方法,获取初始化参数信息。
Enumeration<String> names = config.getInitParameterNames();
while (names.hasMoreElements()) {
String name = names.nextElement();
String value = config.getInitParameter(name);
System.out.println(name + ":" + value);
}
// 获取Servlet名称。
String servletName = config.getServletName();
System.out.println(servletName);
ServletContext servletContext = config.getServletContext();
}
重新启动tomcat,并在浏览器中输入地址:http://localhost:8080/MyServlet001/hello,回车,之后查看tomcat服务器输出信息:
INFO: Server startup in 1262 ms
HelloServlet constructor
init
username:user001
password:123456
username:user001
password:123456
helloServlet
service
从上边的输出信息,及代码中,就可以理解,getInitParameter(),getInitParameters(),getServletName()的用法。
ServletContext servletContext=config.getServletContext();
这个ServletContext是怎么解释,有什么用处呢?
我们查看官网对ServletContext的介绍:
- public interface ServletContext
Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file.
There is one context per "web application" per Java Virtual Machine. (A "web application" is a collection of servlets and content installed under a specific subset of the server's URL namespace such as
/catalogand possibly installed via a.warfile.)In the case of a web application marked "distributed" in its deployment descriptor, there will be one context instance for each virtual machine. In this situation, the context cannot be used as a location to share global information (because the information won't be truly global). Use an external resource like a database instead.
The
ServletContextobject is contained within theServletConfigobject, which the Web server provides the servlet when the servlet is initialized.
ServletContext接口:
1、Servlet引擎为每个web应用程序都创建了一个对应的ServletContext对象,ServletContext对象被包含在ServletConfig对象中,调用ServletConfig.getServletContext()方法就可以返回ServletContext对象的引用。
2、由于一个web应用程序中的所有Servlet都共享一个ServletContext对象,所以ServletContext对象被称之为application对象(web应用程序对象)。
3、功能:
获取web应用程序的初始化参数;
记录日志;
application域范围的属性;
访问资源文件;
获取虚拟路径所映射的本地路径;
web应用程序之间的访问;
ServletContext的其他方法。
- 获取web应用程序的初始化参数;
首先,需要在web.xml中配置应用程序级别(<context-param>)的参数信息;
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0"> <!-- 配置当前web应用的初始化参数 -->
<context-param>
<param-name>driver</param-name>
<param-value>com.mysql.jdbc.Driver</param-value>
</context-param>
<context-param>
<param-name>jdbcUrl</param-name>
<param-value>jdbc:mysql://test</param-value>
</context-param> <!-- 配置和映射 servlet -->
<servlet>
<!-- Servlet注册的名字 -->
<servlet-name>helloServlet</servlet-name>
<!-- Servlet全类名 -->
<servlet-class>com.dx.hello.HelloServlet</servlet-class> <!-- 配置Servlet的初始化参数。且节点必须在 load-on-startup节点的前边 -->
<init-param>
<param-name>username</param-name>
<param-value>user001</param-value>
</init-param>
<init-param>
<param-name>password</param-name>
<param-value>123456</param-value>
</init-param> <!-- 指定servlet被初始化的时机 -->
<load-on-startup>-1</load-on-startup>
</servlet>
<servlet-mapping>
<!-- 对应servlet节点下的servlet-name的注册名字一致 -->
<servlet-name>helloServlet</servlet-name>
<!-- 映射具体的访问路径,其中/代表当前web的根目录 -->
<url-pattern>/hello</url-pattern>
</servlet-mapping> </web-app>
注意:
这里的context-param是应用程级别的初始化参数,<servlet>节点下的<init-param>属于servlet局部的初始化参数,他们具有作用域范围不同。
然后,使用:
public void init(ServletConfig config) throws ServletException {
System.out.println("init");
// 根据ServletConfig的getInitParameter()方法,根据特定初始化参数名称,获取对应的初始化参数值。
String username = config.getInitParameter("username");
String password = config.getInitParameter("password");
System.out.println("username:" + username);
System.out.println("password:" + password);
// 根据ServletConfig的getInitParameterNames()方法,获取初始化参数信息。
Enumeration<String> names = config.getInitParameterNames();
while (names.hasMoreElements()) {
String name = names.nextElement();
String value = config.getInitParameter(name);
System.out.println(name + ":" + value);
}
// 获取Servlet名称。
String servletName = config.getServletName();
System.out.println(servletName);
// 使用getServletContext(),获取ServletContext对象。
ServletContext servletContext = config.getServletContext();
// ServletContext获取初始化参数函数getInitParameter(String arg0)
String driver=servletContext.getInitParameter("driver");
String jdbc=servletContext.getInitParameter("jdbc");
System.out.println("driver:"+driver);
System.out.println("jdbc:"+jdbc);
// ServletContext获取初始化参数集合函数getInitParameterNames()
Enumeration<String> names2= servletContext.getInitParameterNames();
while (names2.hasMoreElements()) {
String name = names2.nextElement();
String value = servletContext.getInitParameter(name);
System.out.println(name + ":" + value);
}
}
查看输出信息:
HelloServlet constructor
init
username:user001
password:123456
username:user001
password:123456
helloServlet
driver:com.mysql.jdbc.Driver
jdbcUrl:jdbc:mysql://test
driver:com.mysql.jdbc.Driver
jdbcUrl:jdbc:mysql://test
service
- 访问资源文件(获取当前web应用的某一个文件对应的输入流。);
// 获取当前web应用的某一个文件对应的输入流。
try {
ClassLoader classLoader = this.getClass().getClassLoader();
InputStream stream = classLoader.getResourceAsStream("jdbc.properties");
//stream with method0:java.io.BufferedInputStream@1cd3bd82
System.out.println("stream with method0:"+stream);
} catch (Exception e) {
e.printStackTrace();
} try {
InputStream stream = servletContext.getResourceAsStream("/WEB-INF/classes/jdbc.properties");
// stream with method1:java.io.FileInputStream@113eb097
System.out.println("stream with method1:"+stream);
} catch (Exception e) {
e.printStackTrace();
}
- 获取当前web应用的某一个文件,在服务器上的一个绝对路径
// 获取当前web应用的某一个文件,在服务器上的一个绝对路径:
// D:\java\workset\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\MyServlet001\WEB-INF\web.xml
String realPath=servletContext.getRealPath("/WEB-INF/web.xml");
System.out.println(realPath);
- 获取web当前应用的名称;
// 获取web当前应用的名称
String webName=servletContext.getContextPath();
// "/MyServlet001"
System.out.println(webName);
Java Servlet(三):Servlet中ServletConfig对象和ServletContext对象的更多相关文章
- java 从spring容器中获取注入的bean对象
java 从spring容器中获取注入的bean对象 CreateTime--2018年6月1日10点22分 Author:Marydon 1.使用场景 控制层调用业务层时,控制层需要拿到业务层在 ...
- 小谈-—ServletConfig对象和servletContext对象
一.servletContext概述 servletContext对象是Servlet三大域对象之一,每个Web应用程序都拥有一个ServletContext对象,该对象是Web应用程序的全局对象或者 ...
- ServletConfig对象和ServletContext对象有什么区别?
一个Servlet对应有一个ServletConfig对象,可以用来读取初始化参数. 一个webapp对应一个ServletContext对象. ServletContext对象获取初始化定义的参数. ...
- Servlet接口的实现类,路径配置映射,ServletConfig对象,ServletContext对象及web工程中文件的读取
一,Servlet接口实现类:sun公司为Servlet接口定义了两个默认的实现类,分别为:GenericServlet和HttpServlet. HttpServlet:指能够处理HTTP请求的se ...
- Java的三种代理模式(Spring动态代理对象)
Java的三种代理模式 1.代理模式 代理(Proxy)是一种设计模式,提供了对目标对象另外的访问方式;即通过代理对象访问目标对象.这样做的好处是:可以在目标对象实现的基础上,增强额外的功能操作,即扩 ...
- Servlet(三)----Servlet体系与HTTP
## Servlet的体系结构 Servlet --- 接口 | | GenericServlet --- 抽象类 | | HttpServlet -- 抽象类 GenericServle ...
- ServletConfig对象和ServletContext对象
(1)ServletConfig:用来保存一个Servlet的配置信息的(比如 : name, class, url ... ) 这些配置信息没什么大用处,我们还可以在ServletConfig中保存 ...
- JavaWeb-----ServletConfig对象和servletContext对象
1.ServletConfig ServletConfig:代表当前Servlet在web.xml中的配置信息 String getServletName() -- 获取当前Servlet在web. ...
- Java Web(三) Servlet会话管理
会话跟踪 什么是会话? 可简单理解为,用户打开一个浏览器,点击多个超链接,访问服务器多个web资源,然后关闭服务器,整个过程称为一个会话.从特定客户端到服务器的一系列请求称为会话.记录会话信息的技术称 ...
随机推荐
- Introducing the Accelerated Mobile Pages Project, for a faster, open mobile web
https://googleblog.blogspot.com/2015/10/introducing-accelerated-mobile-pages.html October 7, 2015 Sm ...
- Error:(12) No resource identifier found for attribute 'titles' in package 'com.itheima52.mobilesafe5
http://stackoverflow.com/questions/5819369/error-no-resource-identifier-found-for-attribute-adsize-i ...
- nodejs fs 模块
件系统操作相关的函数挺多的.首先可以分为两大类. 一类是异步+回调的. 一类是同步的. 在这里只对异步的进行整理,同步的只需要在函数名称后面加上Sync即可 1. 首先是一类最常规的读写函数,函数名称 ...
- 【转】unity地形插件T4M使用帮助
unity的地形系统在手机游戏中因为效率问题基本无法使用,只能通过T4M这个地形插件来进行优化制作.下面大概讲解一下使用流程及方法. 先中U3D里面用自带的地形系统刷出想要的地形和贴图.贴图可以大概刷 ...
- 深入了解php opcode缓存原理
什么是opcode opcode(operate code)是计算机指令中的一部分,用于指定要执行的操作,指令的格式和规范由处理器的指定规范指定 opcode是一种php脚本编译后的中间语言,就像ja ...
- html之内联元素与块状元素;
html之内联元素与块状元素 一.html之内联元素与块状元素 1.块状元素一般比较霸道,它排斥与其他元素位于同一行内.比如div,并且width与height对它起作用. 2.内联元素只能容纳文本或 ...
- 基于ace后台管理系统模板--CMS(Thinkphp框架)的筹划
临近春节,准备自己做一个关于宠物的cms网站,特写下此博客提醒自己,尽量争取在过年前做好.废号少说,先梳理下接下来准备使用的工具.. 由于最近在学习thinkphp,所以打算用这个框架来作为主体,可能 ...
- 常用ARM汇编指令
常用ARM汇编指令 [日期:2012-07-14] 来源:Linux社区 作者:xuyuanfan77 [字体:大 中 小] 在嵌入式开发中,汇编程序常常用于非常关键的地方,比如系统启动时初 ...
- [LeetCode]题解(python):086 - Partition List
题目来源 https://leetcode.com/problems/partition-list/ Given a linked list and a value x, partition it s ...
- Introduction to Project Management(II)
Introduction The purpose of this paper is to gain an understanding of project management and to give ...