ServletContext介绍及功能(十)

本文详细介绍了ServletContext对象的作用及使用方法,包括如何获取ServletContext对象、设置全局初始化参数、实现servlet间的信息共享、获取路径资源等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、Web应用对象:ServletContext

  • web容器在启动时,它会为每个web应用程序都创建一个对应的ServletContext对象,它代表当前web应用。
  • ServletConfig对象中维护了ServletContext对象的引用,开发人员在编写servlet时,可以通过ServletConfig.getServletContext方法获得ServletContext对象。
  • 由于一个web应用中的所有servlet共享同一个ServletContext对象,因此Servlet对象之间可以通过ServletContext对象来实现通讯。ServletContext对象通常也被称之为context对象

二、关于ServletContext对象

       1. 它代表一个web应用。

   2. 怎样获取一个ServletContext对象?

        可以通过ServletConfig对象获取。

         ServletConfig.getServletContext();

package com.it.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//获取ServletContext对象
public class Demo3Servlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//1.要先获取ServletContext对象,可以通过ServletConfig对象
		ServletContext context = this.getServletConfig().getServletContext();
		//2.在实际中,一般是以如下方式获取
		ServletContext context2 = this.getServletContext();
	}

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

}

三、ServletContext对象作用

1. ServletContext可以获取全局初始化参数

2. ServletContext可以帮助我们让servlet实现信息共享

3. 可以获取路径(资源)

4. 其他功能

四、ServletContext作用一:设置全局初始化参数

实际开发中,做一个初始化操作,是要求所有servlet,整个工程共享的,在整个web应用里面都OK的,都能用的。那么就可以设置全局初始化参数。

String  getInitParameter(String name);

Enumeration getInitParameterNames();

在web.xml文件中可以配置我们的全局初始化参数

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>day7_2</display-name>
  <!--配置全局初始化参数-->
  <context-param>
  	<param-name>name</param-name>
  	<param-value>tom</param-value>
  </context-param>
  <servlet>
    <servlet-name>Demo1Servlet</servlet-name>
    <servlet-class>com.it.servlet.Demo1Servlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>Demo1Servlet</servlet-name>
    <url-pattern>/demo1</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

com.it.servlet.Demo1Servlet

package com.it.servlet;

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 Demo1Servlet extends HttpServlet {

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

		//1.获取ServletContext对象
        ServletContext context = this.getServletContext();
		//2.获得初始化参数
        String name = context.getInitParameter("name");
		System.out.println(name);

	}

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

}

五、ServletContext作用一:设置全局初始化参数的应用

获取web应用的全局初始化参数,给整个工程用的。

例如:整个web工程连接数据库,它的数据源可以在里面配置。

           整个web工程有统一的编码,编码可以配置在此。

           整个web工程需要一个监听器或过滤器,也可以在里面配置。

总结:ServletContext的配置是针对于整个web应用,而ServletConfig是针对于某个servlet。

六、ServletContext作用二:让servlet实现信息共享

ServletContext是一个域对象。提到域对象想到两件事,一个是它相当于是一个map,另一个是它有作用域。ServletContext它的作用域是整个web应用。

setAttribute(String name, Object value);

getAttribute(String name);

removeAttribute(String name);

ServletContext既然相当于一个map,在整个web应用中,那么所有的servlet都可以访问。假设有两个servlet,A和B,A向ServletContext中存了一个,B就可以取出来,继而实现了servlet之间的通信。我们也称这种对象为上下文对象。

voidsetAttribute(String name, Object object)

Binds an object to a given attribute name in this ServletContext.

ObjectgetAttribute(String name)

Returns the servlet container attribute with the given name, or null if there is no attribute by that name.

com.it.servlet.FirstServlet

package com.it.servlet;

import java.io.IOException;
import java.io.PrintWriter;

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 FirstServlet extends HttpServlet {

	
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//1.获取ServletContext
		ServletContext context = this.getServletContext();
		//2.使用setAttribute方法存储
		context.setAttribute("name", "message");
	}

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

}

com.it.servlet.SecondServlet

package com.it.servlet;

import java.io.IOException;
import java.io.PrintWriter;

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 SecondServlet extends HttpServlet {

	
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//1.获取ServletContext
		ServletContext context = this.getServletContext();
		//2.从ServletContext取出数据
		String message = (String) context.getAttribute("name");
		System.out.println(message);
	}

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

}

七、ServletContext作用三:获取路径(资源)

在web开发中,如果要想获取资源,必须使用绝对的磁盘路径。

怎样可以得到在服务器上的文件的绝对磁盘路径?

1. String getRealPath(String str);  必会******

    servletContext.getRealPath("/");得到当前工程在磁盘上的绝对路径。

2. URL getResource(String s);

     得到一个URL路径,它也是指向我们的web工程下的资源。

3. InputStream getResourceAsStream(String s);

     得到一个指向资源的输入流

4. 扩展:对于classes目录下的文件,它有其他的方式可以获取到。

    对于webproject,classes放在classes目录下。java project则放在bin目录下。

    Class.getResource("/").getPath();  获取的就是class文件所在目录的绝对磁盘路径

   Class.getResource("/4.txt").getPath();

   对于存在于classes目录下的文件,我们可以通过classpath的方式去获取其绝对磁盘路径。

新建一个dynamic web project。在web工程下创建四个文件,存放在不同位置,要求读出来。在工程根目录下创建一个新的文件1.txt,在WebRoot目录下创建2.txt,在WEB-INF下创建3.txt,在src下创建4.txt。创建一个java 类,要求把四个文件读出来。

java程序读取

package com.it.demo;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

/**
 * 读取1.txt,2.txt,3.txt,4.txt
 * @author xie
 *
 */
public class Demo {
	public static void main(String[] args) {
		//在java程序里,myeclipse默认读取路径是在根路径下。
		String path1 = "1.txt";
		String path2 = "WebRoot/2.txt";
		String path3 = "WebRoot/WEB-INF/3.txt";
		String path4 = "src/4.txt";
		try {
			readFile(path1);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 给一个文件路径,将文件读取出来。
	 * @param path
	 * @throws IOException
	 */
	public static void readFile(String path) throws IOException {
		BufferedReader br = new BufferedReader(new FileReader(path));
		String msg = null;
		while((msg = br.readLine())!=null) {
			System.out.println(msg);
		}
	}
}

servlet读取

package com.it.servlet;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URL;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 在servlet中将1.txt,2.txt,3.txt,4.txt读取出来。
 * @author xie
 *
 */
public class ReadFileServlet extends HttpServlet {

	
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//1.txt
		//绝对路径,但是只能本机访问,如果客户端非本机访问,绝对报错,不可行。
		//记住,这不是服务器上的路径,只是eclipse工程上的路径。
		//因为只有eclipse下的WebRoot下的内容可以部署到服务器上,其他都不可以,所以1.txt根本不在服务器上,读取不到。
		//String path1 = "/Users/xie/Documents/黑马/day7-web-servlet/xxy/workspace/day7_4/1.txt";
		
		//2.txt --- 绝对路径,但是需要知道Tomcat安装路径。
		//String path2 = "/Users/xie/Documents/tomcat/apache-tomcat-9.0.11/webapps/day7_4/2.txt";
		//readFile(path2);
		//怎样可以得到服务器上文件的绝对磁盘路径?
		String path = this.getServletContext().getRealPath("/");
		//System.out.println(path);
		//   /Users/xie/Documents/tomcat/apache-tomcat-9.0.11/webapps/day7_4/
		//readFile(path + "2.txt");
		//readFile(path + "WEB-INF/3.txt");
		//readFile(path + "WEB-INF/classes/4.txt");
		
		//--------getResource()
		URL url = this.getServletContext().getResource("/");
		System.out.println(url);
		
		//--------getResourceAsStream()
		InputStream is = this.getServletContext().getResourceAsStream("/2.txt");
		System.out.println((char)is.read());
	}

	
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
	
	//给定一个文件路径,将文件读取出来。
	public void readFile(String path) throws IOException {
		BufferedReader br = new BufferedReader(new FileReader(path));
		String msg = null;
		while((msg = br.readLine())!=null) {
			System.out.println(msg);
		}
	}

}
package com.it.demo;

public class ClassPathDemo {
	public static void main(String[] args) {
		//获取.class文件所在目录的绝对磁盘路径
		String path = ClassPathDemo.class.getResource("/").getPath();
		System.out.println(path);
	}
}
package com.it.servlet;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URL;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 在servlet中将1.txt,2.txt,3.txt,4.txt读取出来。
 * @author xie
 *
 */
public class ReadFileServlet extends HttpServlet {

	
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//1.txt
		//绝对路径,但是只能本机访问,如果客户端非本机访问,绝对报错,不可行。
		//记住,这不是服务器上的路径,只是eclipse工程上的路径。
		//因为只有eclipse下的WebRoot下的内容可以部署到服务器上,其他都不可以,所以1.txt根本不在服务器上,读取不到。
		//String path1 = "/Users/xie/Documents/黑马/day7-web-servlet/xxy/workspace/day7_4/1.txt";
		
		//2.txt --- 绝对路径,但是需要知道Tomcat安装路径。
		//String path2 = "/Users/xie/Documents/tomcat/apache-tomcat-9.0.11/webapps/day7_4/2.txt";
		//readFile(path2);
		//怎样可以得到服务器上文件的绝对磁盘路径?
		String path = this.getServletContext().getRealPath("/");
		//System.out.println(path);
		//   /Users/xie/Documents/tomcat/apache-tomcat-9.0.11/webapps/day7_4/
		//readFile(path + "2.txt");
		//readFile(path + "WEB-INF/3.txt");
		//readFile(path + "WEB-INF/classes/4.txt");
		
		//--------getResource()
		//URL url = this.getServletContext().getResource("/");
		//System.out.println(url);
		
		//--------getResourceAsStream()
		//InputStream is = this.getServletContext().getResourceAsStream("/2.txt");
		//System.out.println((char)is.read());
		
		//对于4.txt它的位置比较特殊,它存在于classes目录下,它是class文件的目录。
		String classPath = this.getClass().getResource("/").getPath(); //得到Tomcat下class文件所在目录的绝对磁盘路径
		readFile(classPath + "4.txt");
		
	}

	
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
	
	//给定一个文件路径,将文件读取出来。
	public void readFile(String path) throws IOException {
		BufferedReader br = new BufferedReader(new FileReader(path));
		String msg = null;
		while((msg = br.readLine())!=null) {
			System.out.println(msg);
		}
	}

}

八、ServletContext作用四:其它功能

1. 获取MIME类型 ---- 文件下载时会用到

    String getMimeType(String file)

2. 分发请求

    RequestDispatcher getRequestDispatcher(String path)

    在开发中不常使用,如果使用通过request对象来操作。

3. 日志

    log方法时用来处理日志的。 

   基本不用,主要用log4j。

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值