目前就這樣撸撸吧!
類代碼(同之前一樣的操作···········23333333333333)
package com.pzhu.servlet;
import java.io.IOException;
import java.io.InputStream;
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 ServletContextServlet2 extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//擷取ServletContext對象
//第一種方式:
ServletContext sc=this.getServletContext();
//第二種方式:
ServletContext sc2=this.getServletConfig().getServletContext();
//第三種方式:
ServletContext sc3=req.getSession().getServletContext();
System.out.println(sc==sc2);
System.out.println(sc==sc3);
//使用ServletContext對象完成資料共享
//資料存儲
sc.setAttribute("str", "ServletContext對象學習");
//擷取項目web.xml的全局配置資料
String str = sc.getInitParameter("name2");
System.out.println("全局配置參數:"+str);
//擷取項目根目錄下的資源的絕對路徑
//String path="D:\\apache-tomcat-7.0.56\\webapps\\sc\\doc\\1.txt";
String path=sc.getRealPath("/doc/1.txt");
System.out.println(path);
//擷取項目根目錄下資源的流對象
InputStream is = sc.getResourceAsStream("/doc/1.txt");
}
}
web.xml配置:
<?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">
<servlet>
<servlet-name>ServletContextServlet2</servlet-name>
<servlet-class>com.pzhu.servlet.ServletContextServlet2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletContextServlet2</servlet-name>
<url-pattern>/scs</url-pattern>
</servlet-mapping>
</web-app>
結果:
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiI0gTMx81dsQWZ4lmZf1GLlpXazVmcvwFciV2dsQXYtJ3bm9CX9s2RkBnVHFmb1clWvB3MaVnRtp1XlBXe0xCMy81dvRWYoNHLwEzX5xCMx8FesU2cfdGLwMzX0xiRGZkRGZ0Xy9GbvNGLpZTY1EmMZVDUSFTU4VFRR9Fd4VGdsYTMfVmepNHLrJXYtJXZ0F2dvwVZnFWbp1zczV2YvJHctM3cv1Ce-cGcq5CMwkDN2kzM4ImY4ADM4QjNzYzXwITO1ATM0AzLcFTMyIDMy8CXn9Gbi9CXzV2Zh1WavwVbvNmLvR3YxUjLyM3Lc9CX6MHc0RHaiojIsJye.jpg)