1,WEB容器在啓動時,它會爲每一個WEB應用程序都建立一個對應的ServletContext對象,它表明當前web應用。html
2,ServletConfig對象中維護了ServletContext對象的引用,開發人員在編寫servlet時,能夠經過ServletConfig.getServletContext方法得到ServletContext對象。java
代碼:(經過context-param標籤爲整個web應用配置初始化參數)
mysql
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <context-param> <param-name>name</param-name> <param-value>zxx</param-value> </context-param> <context-param> <param-name>url</param-name> <param-value>jdbc:mysql://localhost:3306/test</param-value> </context-param> <context-param> <param-name>username</param-name> <param-value>root</param-value> </context-param> <context-param> <param-name>password</param-name> <param-value>root</param-value> </context-param> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
1,代碼(獲取上下文);web
//獲取servletContext對象 public class ContextDemo1 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 通過ServletConfig對象得到上下文 this.getServletConfig().getServletContext(); // 也能夠直接獲取 this.getServletContext(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
ServletContext應用sql
1,獲取web應用的初始化參數:app
代碼:jsp
//獲取web應用初始化參數 public class ContextDemo4 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Enumeration e = this.getServletContext().getInitParameterNames(); while(e.hasMoreElements()){ String name = (String) e.nextElement(); String value = this.getServletContext().getInitParameter(name); System.out.println(name + "=" + value); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
2,在多個servlet之間共享數據:this
代碼1(往上下文中存入數據):url
//經過ServletContext共享數據 public class ContextDemo2 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String data = "aaaaaa"; //給上下文設置數據 this.getServletContext().setAttribute("data", data); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
代碼2(從上下文中取出數據):spa
public class ContextDemo3 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //從上下文中取出數據 String data = (String) this.getServletContext().getAttribute("data"); System.out.println(data); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
3,實現Servlet的轉發:
//實現請求轉發 public class ContextDemo5 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String data = "aaaaa"; this.getServletContext().setAttribute("data", data); //請求轉給1.jsp,並在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); } }
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> <font color="red"> <h1>${data }</h1> </font> </body> </html>
4,利用ServletContext對象讀取資源文件
//讀取配置文件 public class ContextDemo6 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { test4(); } //使用getRealPath讀取資源文件 private void test4() throws IOException { //獲取在WEB-INF底下的db.properties的絕對路徑 String path = this.getServletContext().getRealPath("/WEB-INF/db.properties"); String filename = path.substring(path.lastIndexOf("\\")+1); FileInputStream in = new FileInputStream(path); System.out.println(filename); System.out.println(in); } //讀取不一樣位置的資源文件 private void test3() throws IOException { //資源文件在cn.yujian.context包下面 InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/cn/yujian/context/db.properties"); System.out.println(in); //資源文件在WEB-INF目錄下 in = this.getServletContext().getResourceAsStream("/WEB-INF/db.properties"); System.out.println(in); } //經過servletContext讀取web應用下的資源文件,資源文件在src目錄下 private void test2() throws IOException { InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties"); Properties prop = new Properties(); //map prop.load(in); String driver = prop.getProperty("driver"); String url = prop.getProperty("url"); String username = prop.getProperty("username"); String password = prop.getProperty("password"); System.out.println(driver); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
附加:
不是servlet的普通類中如何讀取資源文件?
public class Dao { //在不是servlet的普通類讀取資源文件,(經過類加載的方式讀取) private static Properties config = new Properties(); static{ try{ //這是直接在src下面的,若是文件在某一個包下面,它前面須要加上包名,如:cn/nihao/db.properties InputStream in = Dao.class.getClassLoader().getResourceAsStream("db.properties");//經過類加載器讀取資源文件 config.load(in); }catch (Exception e) { throw new ExceptionInInitializerError(e); } } public String test(){ String driver = config.getProperty("driver"); System.out.println(driver); return ""; } public String get() throws IOException{ //InputStream in = Dao.class.getClassLoader().getResourceAsStream("db.properties"); //這種方式能夠讓配置文件改變以後就能生效 URL url = Dao.class.getClassLoader().getResource("db.properties"); String path = url.getPath(); FileInputStream in = new FileInputStream(path); Properties prop = new Properties(); prop.load(in); System.out.println(prop.getProperty("driver")); return ""; } }
這種方式的缺點是,若是資源文件過大會致使內存溢出