ServletConfig与ServletContext
一、ServletConfig讲解
1.1、配置Servlet初始化参数
在通过eclipse创建servlet的时候就可以创建init初始化参数,如图:
创建好之后web.xml文件中就会加入新的内容:
<servlet>
<description></description>
<display-name>ServletDemo02</display-name>
<servlet-name>ServletDemo02</servlet-name>
<servlet-class>com.lovo.study.ServletDemo02</servlet-class>
<init-param>
<description></description>
<param-name>name</param-name>
<param-value>lovo</param-value>
</init-param>
<init-param>
<description></description>
<param-name>pwd</param-name>
<param-value>123456</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>ServletDemo02</servlet-name>
<url-pattern>/ServletDemo02</url-pattern>
</servlet-mapping>
其中<init-param>
包含的部分就是初始化参数
1.2、通过ServletConfig获取Servlet的初始化参数
当servlet配置了初始化参数后,web容器在创建servlet实例对象时,会自动将这些初始化参数封装到ServletConfig对象中,并在调用servlet的init方法时,将ServletConfig对象传递给servlet。进而,我们通过ServletConfig对象就可以得到当前servlet的初始化参数信息。
package com.lovo.study;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class ServletDemo02
*/
public class ServletDemo02 extends HttpServlet {
private static final long serialVersionUID = 1L;
public ServletDemo02() {
super();
}
/**
* 定义ServletConfig对象来接收配置的初始化参数
*/
private ServletConfig config;
/**
* 当servlet配置了初始化参数后,web容器在创建servlet实例对象时,
* 会自动将这些初始化参数封装到ServletConfig对象中,并在调用servlet的init方法时,
* 将ServletConfig对象传递给servlet。进而,程序员通过ServletConfig对象就可以
* 得到当前servlet的初始化参数信息。
*/
@Override
public void init(ServletConfig config) throws ServletException {
this.config = config;
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取在web.xml中配置的初始化参数
String paramValue = this.config.getInitParameter("name");//指定键名
PrintWriter out = response.getWriter();
out.append(paramValue);
out.append("<br/>");
//获取所有初始化参数
Enumeration<String> e = this.config.getInitParameterNames();
while(e.hasMoreElements()){
String name = e.nextElement();
String value = this.config.getInitParameter(name);
out.append(name + "=" + value + "<br/>");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
二、ServletContext对象
WEB容器在启动时,它会为每个WEB应用程序都创建一个对应的ServletContext对象,它代表当前web应用。 ServletConfig对象中维护了ServletContext对象的引用,开发人员在编写servlet时,可以通过ServletConfig.getServletContext方法获得ServletContext对象。 由于一个WEB应用中的所有Servlet共享同一个ServletContext对象,因此Servlet对象之间可以通过ServletContext对象来实现通讯。ServletContext对象通常也被称之为context域对象。
三、ServletContext的应用
3.1、多个Servlet通过ServletContext对象实现数据共享
新建ServletContext01和ServletContext02实现数据共享示例:
SerlvetContext01:
package com.lovo.study;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletContext01 extends HttpServlet {
private static final long serialVersionUID = 1L;
public ServletContext01() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String data = "lovo";
/**
* ServletConfig对象中维护了ServletContext对象的引用,开发人员在编写servlet时,
* 可以通过ServletConfig.getServletContext方法获得ServletContext对象。
*/
ServletContext context = this.getServletContext();//获得ServletContext对象
context.setAttribute("name", data);//将data存储到ServletContext对象中
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
ServletContext02:
package com.lovo.study;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletContext02 extends HttpServlet {
private static final long serialVersionUID = 1L;
public ServletContext02() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext context = this.getServletContext();
String value = context.getAttribute("name").toString();//从ServletContext对象中取出数据
response.getWriter().append(value);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
思考: 1.关闭浏览器之后,再次直接访问ServletContext02会不会有问题?
2.先关闭tomcat服务器再重新启动,然后再直接访问ServletContext02会不会有问题?
3.2、获取WEB应用的初始化参数
在web.xml文件中使用<context-param>
标签配置WEB应用的初始化参数,如下所示:
<?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_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>ServletDemo</display-name>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!-- 配置WEB应用的初始化参数 -->
<context-param>
<param-name>url</param-name>
<param-value>jdbs:mysql://localhost:3306/test</param-value>
</context-param>
</web-app>
获取Web应用的初始化参数,代码如下:
package com.lovo.study;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletContext03 extends HttpServlet {
private static final long serialVersionUID = 1L;
public ServletContext03() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext context = this.getServletContext();
//获取整个web站点的初始化参数
String value = context.getInitParameter("url");
response.getWriter().append(value);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
3.3、用servletContext实现请求转发
通过ServletContext还能实现请求转发,具体如下面的代码:
ServletContext04:
package com.lovo.study;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletContext04 extends HttpServlet {
private static final long serialVersionUID = 1L;
public ServletContext04() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext context = this.getServletContext();
//获取转发对象
RequestDispatcher rd = context.getRequestDispatcher("/ServletContext05");
rd.forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
ServletContext05:
package com.lovo.study;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletContext05 extends HttpServlet {
private static final long serialVersionUID = 1L;
public ServletContext05() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().append("ServletContext05");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
效果如图:
3.4、利用ServletContext对象读取资源文件
项目目录结构如下:
可以看到几个properties文件分别在不同的位置,现在我们通过ServletContext06.java
文件来读取这几个在不同位置的属性文件
ServletContext06.java
package com.lovo.study;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.text.MessageFormat;
import java.util.Properties;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletContext06 extends HttpServlet {
private static final long serialVersionUID = 1L;
public ServletContext06() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/**
* response.setContentType("text/html;charset=UTF-8");
* 目的是控制浏览器用UTF-8进行解码
* 防止出现中文乱码
*/
response.setHeader("Content-Type","text/html;charset=UTF-8");
//读取com.lovo.study包中的db1.properties属性文件
InputStream in = this.getServletContext()
.getResourceAsStream("/WEB-INF/classes/com/lovo/study/db1.properties");
//读取src中的db2.properties属性文件
// InputStream in = this.getServletContext()
// .getResourceAsStream("/WEB-INF/classes/db2.properties");
//读取webContent中的db3.properties属性文件
// InputStream in = this.getServletContext()
// .getResourceAsStream("db3.properties");
//读取config包中的db4.properties属性文件
// InputStream in = this.getServletContext()
// .getResourceAsStream("/WEB-INF/classes/config/db4.properties");
//获取属性对象
Properties prop = new Properties();
prop.load(in);
String name = prop.getProperty("name");
String pwd = prop.getProperty("pwd");
String db = prop.getProperty("db");
PrintWriter out = response.getWriter();
out.append(MessageFormat.format("name={0},pwd={1},db={2}",
name, pwd, db));
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
当然,除了通过ServletContext来读取文件,通过类加载器ClassLoader
同样可以来读取属性文件.
ServletContext07.java
package com.lovo.study;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.text.MessageFormat;
import java.util.Properties;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletContext07 extends HttpServlet {
private static final long serialVersionUID = 1L;
public ServletContext07() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setHeader("Content-type", "text/html;charset=UTF-8");
//通过反射获取ClassLoader类加载器
ClassLoader loader = ServletContext07.class.getClassLoader();
//获取com.lovo.study包中的db1.properties文件
//InputStream in = loader.getResourceAsStream("com/lovo/study/db1.properties");
//获取src中的db2.properties文件
InputStream in = loader.getResourceAsStream("db2.properties");
Properties prop = new Properties();
prop.load(in);
String name = prop.getProperty("name");
String pwd = prop.getProperty("pwd");
String db = prop.getProperty("db");
PrintWriter out = response.getWriter();
out.append(MessageFormat.format("name={0},pwd={1},db={2}",
name, pwd, db));
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
Comments