日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

[Servlet]研究ServletContext对象

發布時間:2024/1/17 编程问答 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 [Servlet]研究ServletContext对象 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

作者信息
作者姓名:金云龍
個人站點:http://www.longestory.com
個人公眾帳號:搜索“longestory”或“龍哥有話說

ServletContext概述

ServletContext對象是Servlet三大域對象之中的一個,每一個Web應用程序都擁有一個ServletContext對象,該對象是Web應用程序的全局對象或者上下文。Tomcatserver在啟動時,會自己主動創建一個ServletContext對象,在關閉時,會自己主動銷毀這個ServletContext對象。每一個Web應用程序僅僅擁有一個ServletContext對象,ServletContext對象能夠在整個Web應用中共享數據資源。

下列是ServletContext提供的方法列表:

Method Summary
ObjectgetAttribute(String name)
EnumerationgetAttributeNames()
StringgetInitParameter(String name)
EnumerationgetInitParameterNames()
StringgetMimeType(String file)
StringgetRealPath(String path)
StringgetServletContextName()
EnumerationgetServletNames()
voidlog(String msg)
voidremoveAttribute(String name)
voidsetAttribute(String name, Object object)

獲取ServletContext對象

在自己定義Servlet中有以下幾種方式獲取到ServletContext對象:

  • 通過ServletConfig對象的getServletContext()方法獲取。

  • 通過繼承GenericServlet類或HttpServlet類,調用GenericServlet類或HttpServlet類的getServletContext()方法獲取。

我們通過一個案例來討論一下。

  • 首先,創建一個自己定義Servlet。用來獲取ServletContext對象。

public class AServlet extends GenericServlet {@Overridepublic void service(ServletRequest req, ServletResponse res)throws ServletException, IOException {ServletConfig config = getServletConfig();ServletContext context1 = config.getServletContext();context1.log("這是通過ServletConfig對象獲取到的ServletContext對象.");ServletContext context2 = getServletContext();context2.log("這是通過繼承GenericServlet類獲取到的ServletContext對象.");} }
  • 在web.xml文件里配置Servlet相關信息。

<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"><servlet><servlet-name>AServlet</servlet-name><servlet-class>app.java.context.AServlet</servlet-class></servlet><servlet-mapping><servlet-name>AServlet</servlet-name><url-pattern>/servlet/AServlet</url-pattern></servlet-mapping> </web-app>
  • 將Web應用程序公布到Tomcatserver,并啟動Tomcatserver。
  • 打開瀏覽器。在地址欄中輸入http://localhost:8080/08_servlet/servlet/AServlet,在控制臺打印相關信息。

  • 通過ServletContext對象的log(Stirng msg)方法,能夠向控制臺信息打印。

配置全局初始化參數

在web.xml文件里,使用定義的初始化參數。僅僅能在當前Servlet中使用,而其它Servlet是無權限訪問當前Servlet下配置的初始化參數的。而能夠使用ServletContext在web.xml文件里配置全局初始化參數,這樣當前Web應用程序中的全部Servlet都能夠訪問。

  • 在web.xml文件里使用<context-param>來定義全局初始化參數。
<?

xml version="1.0" encoding="UTF-8"?>

<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <context-param> <param-name>weixin</param-name> <param-value>longestory</param-value> </context-param> <servlet> <servlet-name>AServlet</servlet-name> <servlet-class>app.java.context.AServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>AServlet</servlet-name> <url-pattern>/servlet/AServlet</url-pattern> </servlet-mapping> <servlet> <servlet-name>BServlet</servlet-name> <servlet-class>app.java.context.BServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>BServlet</servlet-name> <url-pattern>/servlet/BServlet</url-pattern> </servlet-mapping> </web-app>
  • 在兩個自己定義Servlet中。分別利用ServletContext對象獲取全局初始化參數。
public class BServlet extends GenericServlet {@Overridepublic void service(ServletRequest req, ServletResponse res)throws ServletException, IOException {ServletContext context = getServletContext();String weixin = context.getInitParameter("weixin");System.out.println(weixin);} }
  • 將Web應用程序公布到Tomcatserver。并啟動Tomcatserver。
  • 打開瀏覽器,在地址欄中分別輸入http://localhost:8080/08_servlet/servlet/AServlet和http://localhost:8080/08_servlet/servlet/BServlet,在控制臺打印相關信息。

在自己定義Servlet中,能夠通過ServletContext對象的getInitParameter(String name)方法獲取相應參數名稱的全局初始化參數值。也能夠通過ServletContext對象的getInitParameterNames()方法獲取全部全局初始化參數的名稱。

還能夠通過ServletContext對象的getMineType(String file)方法依據文件擴展名獲取文件MIME類型。

public class BServlet extends GenericServlet {@Overridepublic void service(ServletRequest req, ServletResponse res)throws ServletException, IOException {ServletContext context = getServletContext();String html = context.getMimeType("1.html");String css = context.getMimeType("2.css");String javascript = context.getMimeType("3.js");System.out.println("HTML的文件類型為"+html+", CSS的文件類型為"+css+", javascript的文件類型為"+javascript);} }

公布Web應用程序,并啟動Tomcatserver,在控制臺中打印:

HTML的擴展名為text/html, CSS的擴展名為text/css, javascript的擴展名為application/javascript

ServletContext對象的getMineType(String file)方法會自己主動讀取Tomcat安裝文件夾中conf文件夾中的web.xml文件。

<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"><mime-mapping><extension>html</extension><mime-type>text/html</mime-type> </mime-mapping> <mime-mapping><extension>css</extension><mime-type>text/css</mime-type> </mime-mapping><mime-mapping><extension>js</extension><mime-type>application/javascript</mime-type> </mime-mapping> </web-app>

多個Servlet共享數據

在同一個Web應用程序中,多個Servlet之間能夠共享ServletContext對象中的數據信息。

主要是通過ServletContext對象的setAttribute(String name, Object object)方法和getAttribute(String name)方法完畢,以下我們來實現統計站點訪問次數的案例。

  • 創建一個VisitServlet用來獲取訪問次數。并存儲在ServletContext對象中。
public class VisitServlet extends HttpServlet {@Overridepublic void init() throws ServletException {ServletContext context = getServletContext();context.setAttribute("times", 0);}public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {ServletContext context = getServletContext();int times = (Integer)context.getAttribute("times");times ++;context.setAttribute("times", times);}public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet(request, response);} }
  • 創建一個ShowTimeServlet用來顯示訪問次數。
public class ShowTimeServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {ServletContext context = getServletContext();int times = (Integer)context.getAttribute("times");response.setContentType("text/html;charset=utf-8");PrintWriter out = response.getWriter();out.println("<h1>VisitServlet共被訪問了"+times+"次</h1>");}public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet(request, response);} }
  • 配置web.xml文件里有關Servlet信息。
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"><servlet><servlet-name>VisitServlet</servlet-name><servlet-class>app.java.context.VisitServlet</servlet-class></servlet><servlet><servlet-name>ShowTimeServlet</servlet-name><servlet-class>app.java.context.ShowTimeServlet</servlet-class></servlet><servlet-mapping><servlet-name>VisitServlet</servlet-name><url-pattern>/visit</url-pattern></servlet-mapping><servlet-mapping><servlet-name>ShowTimeServlet</servlet-name><url-pattern>/show</url-pattern></servlet-mapping> </web-app>
  • 公布Web應用程序到Tomcatserver,并啟動Tomcatserver。
  • 打開瀏覽器。在地址欄輸入http://localhost:8080/08_servlet/visit。訪問VisitServlet。
  • 再新打開瀏覽器。在地址欄輸入http://localhost:8080/08_servlet/show。顯示訪問次數。

讀取Webproject中資源文件

讀取project中的資源文件,Java中的IO流事實上就能夠完畢,以下使用Java中的IO流完畢讀取資源文件。

  • 首先在Webproject中,創建四個資源文件。
    • 在Webproject的根文件夾下創建1.txt。

    • 在Webproject的WebRoot文件夾下創建2.txt。
    • 在Webproject的WebRoot文件夾的WEB-INF文件夾下創建3.txt。
    • 在Webproject的src文件夾下創建4.txt。

  • 創建一個Java文件用于讀取上述的四個資源文件。
public class ReaderFileTest {// 編寫readfile()方法完畢資源文件的讀取工作.public static void readfile(String fileName) throws Exception{BufferedReader reader = new BufferedReader(new FileReader(fileName));String line;while ((line = reader.readLine()) != null) {System.out.println(line);}reader.close();}public static void main(String[] args) throws Exception {// 讀取1.txtString filename1 = "1.txt";readfile(filename1);// 讀取2.txtString filename2 = "WebRoot/2.txt";readfile(filename2);// 讀取3.txtString filename3 = "WebRoot/WEB-INF/3.txt";readfile(filename3);// 讀取4.txtString filename4 = "src/4.txt";readfile(filename4);} }
  • 執行該Java文件會在控制臺打印響應信息。

假設要想利用Servlet API的內容來讀取Webproject中的資源文件,又要怎樣來做呢?ServletContext對象的getRealPath()方法能夠來完畢此項工作。

  • 創建一個自己定義Servlet,使用ServletContext對象的getRealPath()方法來完畢讀取資源文件。

public class ReadFileServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response.setContentType("text/html;charset=utf-8");OutputStream out = response.getOutputStream();/** 讀取1.txt* * 由于1.txt資源文件在Webproject的根文件夾.* * Webproject的WebRoot文件夾公布到Tomcatserver.* * 所以,1.txt資源文件是不會公布到Tomcatserver的,Servlet無法讀取.*/// 讀取2.txtString filename2 = getServletContext().getRealPath("/2.txt");InputStream in2 = new FileInputStream(new File(filename2));IOUtils.copy(in2, out);// 讀取3.txtString filename3 = getServletContext().getRealPath("/WEB-INF/3.txt");InputStream in3 = new FileInputStream(new File(filename3));IOUtils.copy(in3, out);// 讀取4.txtString filename4 = getServletContext().getRealPath("/WEB-INF/classes/4.txt");InputStream in4 = new FileInputStream(new File(filename4));IOUtils.copy(in4, out);}public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet(request, response);} }
  • 公布Web應用程序到Tomcatserver。并啟動Tomcatserver。
  • 打開瀏覽器。在地址欄中分別輸入http://localhost:8080/08_servlet/read,在控制臺打印相關信息。

除了能夠使用ServletContext對象的getRealPath()方法之外,還能夠使用ServletContext對象的getResourceAsStream()方法來完畢讀取資源文件的工作。

public class ReadFileServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {InputStream in = getServletContext().getResourceAsStream("/WEB-INF/classes/4.txt");IOUtils.copy(in, out);}public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet(request, response);} }

另一種通用的方法:利用Class類的getResource()方法也能夠完畢讀取資源文件的工作。

public class ReadFileServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// 利用類載入器讀取Webproject的資源文件String filename = ReadFileServlet.class.getResource("/4.txt").getFile();InputStream in = new FileInputStream(new File(filename));IOUtils.copy(in, out);}public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet(request, response);} }

轉載說明:請注明作者及原文鏈接。謝謝!

轉載于:https://www.cnblogs.com/llguanli/p/8400290.html

總結

以上是生活随笔為你收集整理的[Servlet]研究ServletContext对象的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。