ServletContext


得到ServletContext的方式:

public class ServletDemo6 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		//得到ServletContext的方式1
		ServletContext context = this.getServletConfig().getServletContext();
		
		//得到ServletContext的方式2
		context = this.getServletContext();
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
通过ServletContext实现多个servlet的数据共享:

public class ServletDemo7 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		String data = "aaa";
		
		this.getServletContext().setAttribute("data", data);
		
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
/**
 * ServletContext域:
 * 1.这是一个容器
 * 2.ServletContext域这句话说明了这个容器作用范围,也就是应用程序范围
 */

//用过ServletContext实现ServletDemo7和ServletDemo8的数据共享
public class ServletDemo8 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		String value = (String)this.getServletContext().getAttribute("data");
		System.out.println(value);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}

获得Web应用的初始化参数:

web.xml配置文件:

<context-param>
  	<param-name>data1</param-name>
  	<param-value>xxxx</param-value>
  </context-param>
  <context-param>
  	<param-name>data2</param-name>
  	<param-value>yyyy</param-value>
  </context-param>
  <context-param>
  	<param-name>data3</param-name>
  	<param-value>zzzz</param-value>
  </context-param>
Servlet代码:

//获取web应用的初始化参数
public class ServletDemo9 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		String value =(String)this.getServletContext().getInitParameter("data1");
		response.getOutputStream().write(("<font color='red'>" + value + "</font>").getBytes());
		
		Enumeration e = this.getServletContext().getInitParameterNames();
		while(e.hasMoreElements()){
			String name = (String)e.nextElement();
			String value1 = (String)this.getInitParameter(name);
			System.out.println(name+" = "+value1);
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}

实现Servlet转发:

jsp代码:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP '1.jsp' starting page</title>
  </head>
  
  <body>
  	
  	<h1>
  	<font color="red">
    <%
    	//在jsp中,application就是ServletContext
    	String data = (String)application.getAttribute("data");
    	out.write(data);
     %>
     </font>
     </h1>
     
  </body>
</html>
Servlet代码:
//通过ServletContext实现请求转发
public class ServletDemo10 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		String data = "aaaaaaaaaa";
		
		//把数据带给1.jsp (不能通过context域,要通过request域)
		this.getServletContext().setAttribute("data", data);
		
		//转发到1.jsp
		RequestDispatcher rd = this.getServletContext().getRequestDispatcher("/1.jsp");
		rd.forward(request, response);
		
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}


利用ServletContext读取资源文件:

db.properties属性文件内容:

url=jdbc:mysql://localhost:3306/test
username=root
password=root

Servlet代码:

//通过ServletContext读取资源文件
public class ServletDemo11 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		test5();
		  
	}
	
	//通过servletContext的getRealPath得到资源的绝对路径后,再通过传统流读取资源文件
	//此方法适用于下载,因为可以得到资源名称
	private void test5() throws IOException {
		
		String path = this.getServletContext().getRealPath("/WEB-INF/classes/db.properties");
		String filename = path.substring(path.lastIndexOf("\\")+1);
		
		System.out.println("当前读取到的资源名称是:"+filename);
		
		FileInputStream in = new FileInputStream(path);
		//java专门用来读取properties文件的对象
		Properties props = new Properties();//内部用map保存数据
		props.load(in);
		
		System.out.println("当前读取到的资源数据是:");
		String url = props.getProperty("url");
		String username = props.getProperty("username");
		String password = props.getProperty("password");
		
		System.out.println(url);
		System.out.println(username);
		System.out.println(password);
	}
	
	//读取资源文件需要注意的问题:下面传统代码不可行,最好采用servletContext去读
	private void test4() throws IOException {
		
		FileInputStream in = new FileInputStream("classes/db.properties");
		//java专门用来读取properties文件的对象
		Properties props = new Properties();//内部用map保存数据
		props.load(in);
		
		String url = props.getProperty("url");
		String username = props.getProperty("username");
		String password = props.getProperty("password");
		
		System.out.println(url);
		System.out.println(username);
		System.out.println(password);
	}
	//db.properties属性文件在Web应用(WebRoot)目录下	
	private void test3() throws IOException {
		InputStream in = this.getServletContext().getResourceAsStream("/db.properties");
		//java专门用来读取properties文件的对象
		Properties props = new Properties();//内部用map保存数据
		props.load(in);
		
		String url = props.getProperty("url");
		String username = props.getProperty("username");
		String password = props.getProperty("password");
		
		System.out.println(url);
		System.out.println(username);
		System.out.println(password);
	}
	//db.properties属性文件在cn.itcast包目录下
	private void test2() throws IOException {
		InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/cn/itcast/db.properties");
		//java专门用来读取properties文件的对象
		Properties props = new Properties();//内部用map保存数据
		props.load(in);
		
		String url = props.getProperty("url");
		String username = props.getProperty("username");
		String password = props.getProperty("password");
		
		System.out.println(url);
		System.out.println(username);
		System.out.println(password);
	}
	//db.properties属性文件在src目录下	
	private void test1() throws IOException {
		InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
		//java专门用来读取properties文件的对象
		Properties props = new Properties();//内部用map保存数据
		props.load(in);
		
		String url = props.getProperty("url");
		String username = props.getProperty("username");
		String password = props.getProperty("password");
		
		System.out.println(url);
		System.out.println(username);
		System.out.println(password);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}

Servlet调用其他程序,在其他程序中通过类装载器读取资源文件(文件不能太大):
Servlet代码:

//Servlet调用其他程序,在其他程序中如何读取资源文件(通过类装载器,文件不能太大)
public class ServletDemo12 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		UserDao dao = new UserDao();
		dao.update();
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
//如果读取资源文件的程序不是Servlet的话,就只能通过类装载器去读了
public class UserDao {
	
	private static Properties dbconfig = new Properties();
	
	//静态代码块
	static{
		try{
			InputStream in = UserDao.class.getClassLoader().getResourceAsStream("db.properties");
			dbconfig.load(in);
		}
		catch(Exception e){
			//抛出初始化错误
			throw new ExceptionInInitializerError(e);
		}
		
	}
	
	public void update(){
		System.out.println(dbconfig.getProperty("url"));
	}
	
	public void find()throws IOException{
		
		//以下代码虽然可以读取资源文件的数据,但是无法获取更新后的数据,
		//因为类装载器只装载一次资源文件到内存中,即使修改了资源文件,这种方法仍然读取内存中的原资源文件数据
		//所以此方法适用于数据不会更新的情况
//		Properties dbconfig = new Properties();
//		InputStream in = UserDao.class.getClassLoader().getResourceAsStream("db.properties");
//		dbconfig.load(in);
//		System.out.println(dbconfig.getProperty("url"));
		
		//如果要读取更新后的资源文件数据,则先用类装载器得到资源路径,再用传统文件流方式读取资源文件数据
		String path = UserDao.class.getClassLoader().getResource("db.properties").getPath();
		FileInputStream in = new FileInputStream(path);
		Properties dbconfig = new Properties();
		dbconfig.load(in);
		System.out.println(dbconfig.getProperty("url"));
	}
	
	public void delete(){
		
	}
}





 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
【项目资源】:包含前端、后端、移动开发、操作系统、人工智能、物联网、信息化管理、数据库、硬件开发、大数据、课程资源、音视频、网站开发等各种技术项目的源码。包括STM32、ESP8266、PHP、QT、Linux、iOS、C++、Java、MATLAB、python、web、C#、EDA、proteus、RTOS等项目的源码。 【项目质量】:所有源码都经过严格测试,可以直接运行。功能在确认正常工作后才上传。 【适用人群】:适用于希望学习不同技术领域的小白或进阶学习者。可作为毕设项目、课程设计、大作业、工程实训或初期项目立项。 【附加价值】:项目具有较高的学习借鉴价值,也可直接拿来修改复刻。对于有一定基础或热衷于研究的人来说,可以在这些基础代码上进行修改和扩展,实现其他功能。 【沟通交流】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。鼓励下载和使用,并欢迎大家互相学习,共同进步。【项目资源】:包含前端、后端、移动开发、操作系统、人工智能、物联网、信息化管理、数据库、硬件开发、大数据、课程资源、音视频、网站开发等各种技术项目的源码。包括STM32、ESP8266、PHP、QT、Linux、iOS、C++、Java、MATLAB、python、web、C#、EDA、proteus、RTOS等项目的源码。 【项目质量】:所有源码都经过严格测试,可以直接运行。功能在确认正常工作后才上传。 【适用人群】:适用于希望学习不同技术领域的小白或进阶学习者。可作为毕设项目、课程设计、大作业、工程实训或初期项目立项。 【附加价值】:项目具有较高的学习借鉴价值,也可直接拿来修改复刻。对于有一定基础或热衷于研究的人来说,可以在这些基础代码上进行修改和扩展,实现其他功能。 【沟通交流】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。鼓励下载和使用,并欢迎大家互相学习,共同进步。【项目资源】:包含前端、后端、移动开发、操作系统、人工智能、物联网、信息化管理、数据库、硬件开发、大数据、课程资源、音视频、网站开发等各种技术项目的源码。包括STM32、ESP8266、PHP、QT、Linux、iOS、C++、Java、MATLAB、python、web、C#、EDA、proteus、RTOS等项目的源码。 【项目质量】:所有源码都经过严格测试,可以直接运行。功能在确认正常工作后才上传。 【适用人群】:适用于希望学习不同技术领域的小白或进阶学习者。可作为毕设项目、课程设计、大作业、工程实训或初期项目立项。 【附加价值】:项目具有较高的学习借鉴价值,也可直接拿来修改复刻。对于有一定基础或热衷于研究的人来说,可以在这些基础代码上进行修改和扩展,实现其他功能。 【沟通交流】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。鼓励下载和使用,并欢迎大家互相学习,共同进步。【项目资源】:包含前端、后端、移动开发、操作系统、人工智能、物联网、信息化管理、数据库、硬件开发、大数据、课程资源、音视频、网站开发等各种技术项目的源码。包括STM32、ESP8266、PHP、QT、Linux、iOS、C++、Java、MATLAB、python、web、C#、EDA、proteus、RTOS等项目的源码。 【项目质量】:所有源码都经过严格测试,可以直接运行。功能在确认正常工作后才上传。 【适用人群】:适用于希望学习不同技术领域的小白或进阶学习者。可作为毕设项目、课程设计、大作业、工程实训或初期项目立项。 【附加价值】:项目具有较高的学习借鉴价值,也可直接拿来修改复刻。对于有一定基础或热衷于研究的人来说,可以在这些基础代码上进行修改和扩展,实现其他功能。 【沟通交流】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。鼓励下载和使用,并欢迎大家互相学习,共同进步。【项目资源】:包含前端、后端、移动开发、操作系统、人工智能、物联网、信息化管理、数据库、硬件开发、大数据、课程资源、音视频、网站开发等各种技术项目的源码。包括STM32、ESP8266、PHP、QT、Linux、iOS、C++、Java、MATLAB、python、web、C#、EDA、proteus、RTOS等项目的源码。 【项目质量】:所有源码都经过严格测试,可以直接运行。功能在确认正常工作后才上传。 【适用人群】:适用于希望学习不同技术领域的小白或进阶学习者。可作为毕设项目、课程设计、大作业、工程实训或初期项目立项。 【附加价值】:项目具有较高的学习借鉴价值,也可直接拿来修改复刻。对于有一定基础或热衷于研究的人来说,可以在这些基础代码上进行修改和扩展,实现其他功能。 【沟通交流】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。鼓励下载和使用,并欢迎大家互相学习,共同进步。【项目资源
ServletContext是Java Web的一个重要接口,它代表了Web应用程序在服务器的上下文环境。在一个Web应用程序,每个Servlet都可以访问同一个ServletContext对象,从而实现Servlet之间的数据共享和通信。 在Java,可以使用ServletConfig对象的getServletContext()方法来获取ServletContext对象,然后使用该对象的方法来实现一系列操作,例如: 1. 获取Web应用程序的初始化参数:可以使用ServletContext对象的getInitParameter()方法来获取Web应用程序的初始化参数,例如数据库连接等配置信息。 ```java String username = context.getInitParameter("username"); ``` 2. 获取Web应用程序的真实路径:可以使用ServletContext对象的getRealPath()方法来获取Web应用程序的真实路径,例如获取Web应用程序的一个文件的绝对路径。 ```java String path = context.getRealPath("/WEB-INF/config.properties"); ``` 3. 在ServletContext保存数据:可以使用ServletContext对象的setAttribute()方法来在ServletContext保存数据,从而实现Servlet之间的数据共享。 ```java context.setAttribute("key", value); ``` 4. 从ServletContext获取数据:可以使用ServletContext对象的getAttribute()方法来从ServletContext获取数据,例如获取其他Servlet保存的数据。 ```java Object value = context.getAttribute("key"); ``` 需要注意的是,ServletContext对象的作用域为整个Web应用程序,因此需要注意数据的安全性和可靠性。另外,ServletContext对象是在Web应用程序启动时创建的,因此可以在Servlet的init()方法获取ServletContext对象并进行初始化操作,例如读取配置文件等。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值