Servlet學習(二):ServletConfig獲取參數;ServletContext應用:請求轉發,參數獲取,資源讀取;類裝載器讀取文件

轉載:http://www.cnblogs.com/xdp-gacl/p/3763559.html

1、ServletConfig講解

1.一、配置Servlet初始化參數

  在Servlet的配置文件web.xml中,能夠使用一個或多個<init-param>標籤爲servlet配置一些初始化參數。html

例如:java

<servlet>
    <servlet-name>ServletConfigDemo1</servlet-name>
    <servlet-class>gacl.servlet.study.ServletConfigDemo1</servlet-class>
    <!--配置ServletConfigDemo1的初始化參數 -->
    <init-param>
        <param-name>name</param-name>
        <param-value>gacl</param-value>
    </init-param>
     <init-param>
        <param-name>password</param-name>
        <param-value>123</param-value>
    </init-param>
    <init-param>
        <param-name>charset</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
</servlet>

1.二、經過ServletConfig獲取Servlet的初始化參數

  當servlet配置了初始化參數後,web容器在建立servlet實例對象時,會自動將這些初始化參數封裝到ServletConfig對象中,並在調用servlet的init方法時,將ServletConfig對象傳遞給servlet。進而,咱們經過ServletConfig對象就能夠獲得當前servlet的初始化參數信息。mysql

例如:程序員

package gacl.servlet.study; import java.io.IOException; import java.util.Enumeration; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ServletConfigDemo1 extends HttpServlet { /** * 定義ServletConfig對象來接收配置的初始化參數 */
    private ServletConfig config; /** * 當servlet配置了初始化參數後,web容器在建立servlet實例對象時, * 會自動將這些初始化參數封裝到ServletConfig對象中,並在調用servlet的init方法時, * 將ServletConfig對象傳遞給servlet。進而,程序員經過ServletConfig對象就能夠 * 獲得當前servlet的初始化參數信息。 */ @Override public void init(ServletConfig config) throws ServletException { this.config = config; } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //獲取在web.xml中配置的初始化參數
        String paramVal = this.config.getInitParameter("name");//獲取指定的初始化參數
 response.getWriter().print(paramVal); response.getWriter().print("<hr/>"); //獲取全部的初始化參數
        Enumeration<String> e = config.getInitParameterNames(); while(e.hasMoreElements()){ String name = e.nextElement(); String value = config.getInitParameter(name); response.getWriter().print(name + "=" + value + "<br/>"); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }

運行結果以下:web

  

2、ServletContext對象

  WEB容器在啓動時,它會爲每一個WEB應用程序都建立一個對應的ServletContext對象,它表明當前web應用。
  ServletConfig對象中維護了ServletContext對象的引用,開發人員在編寫servlet時,能夠經過ServletConfig.getServletContext方法得到ServletContext對象。
  因爲一個WEB應用中的全部Servlet共享同一個ServletContext對象,所以Servlet對象之間能夠經過ServletContext對象來實現通信。ServletContext對象一般也被稱之爲context域對象。sql

3、ServletContext的應用

  3.一、多個Servlet經過ServletContext對象實現數據共享

  範例:ServletContextDemo1和ServletContextDemo2經過ServletContext對象實現數據共享瀏覽器

package gacl.servlet.study; 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 ServletContextDemo1 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String data = "xdp_gacl"; /** * ServletConfig對象中維護了ServletContext對象的引用,開發人員在編寫servlet時, * 能夠經過ServletConfig.getServletContext方法得到ServletContext對象。 */ ServletContext context = this.getServletConfig().getServletContext();//得到ServletContext對象
        context.setAttribute("data", data);  //將data存儲到ServletContext對象中
 } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
package gacl.servlet.study; 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 ServletContextDemo2 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletContext context = this.getServletContext(); String data = (String) context.getAttribute("data");//從ServletContext對象中取出數據
        response.getWriter().print("data="+data); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }

先運行ServletContextDemo1,將數據data存儲到ServletContext對象中,而後運行ServletContextDemo2就能夠從ServletContext對象中取出數據了,這樣就實現了數據共享,以下圖所示:緩存

  

  3.二、獲取WEB應用的初始化參數

  在web.xml文件中使用<context-param>標籤配置WEB應用的初始化參數,以下所示:服務器

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 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_3_0.xsd">
    <display-name></display-name>
    <!-- 配置WEB應用的初始化參數 -->
    <context-param>
        <param-name>url</param-name>
        <param-value>jdbc:mysql://localhost:3306/test</param-value>
    </context-param>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

獲取Web應用的初始化參數,代碼以下:app

package gacl.servlet.study; 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 ServletContextDemo3 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletContext context = this.getServletContext(); //獲取整個web站點的初始化參數
        String contextInitParam = context.getInitParameter("url"); response.getWriter().print(contextInitParam); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }

運行結果:

  

  3.三、用servletContext實現請求轉發

ServletContextDemo4

package gacl.servlet.study; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.RequestDispatcher; 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 ServletContextDemo4 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String data = "<h1><font color='red'>abcdefghjkl</font></h1>"; response.getOutputStream().write(data.getBytes()); ServletContext context = this.getServletContext();//獲取ServletContext對象
        RequestDispatcher rd = context.getRequestDispatcher("/servlet/ServletContextDemo5");//獲取請求轉發對象(RequestDispatcher) rd.forward(request, response);//調用forward方法實現請求轉發
 } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
ServletContextDemo5

package gacl.servlet.study; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ServletContextDemo5 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getOutputStream().write("servletDemo5".getBytes()); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }

運行結果:

  

  訪問的是ServletContextDemo4,瀏覽器顯示的倒是ServletContextDemo5的內容,這就是使用ServletContext實現了請求轉發

  3.四、利用ServletContext對象讀取資源文件

  項目目錄結構以下:

   

代碼範例:使用servletContext讀取資源文件

讀取資源文件到輸入流的方法:

InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db/config/db3.properties")

第二種:

String path = this.getServletContext().getRealPath("/WEB-INF/classes/db/config/db3.properties"); InputStream in = new FileInputStream(path);

例子:

package gacl.servlet.study; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.text.MessageFormat; import java.util.Properties; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 使用servletContext讀取資源文件 * * @author gacl * */
public class ServletContextDemo6 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /** * response.setContentType("text/html;charset=UTF-8");目的是控制瀏覽器用UTF-8進行解碼; * 這樣就不會出現中文亂碼了 */ response.setHeader("content-type","text/html;charset=UTF-8"); readSrcDirPropCfgFile(response);//讀取src目錄下的properties配置文件
        response.getWriter().println("<hr/>"); readWebRootDirPropCfgFile(response);//讀取WebRoot目錄下的properties配置文件
        response.getWriter().println("<hr/>"); readPropCfgFile(response);//讀取src目錄下的db.config包中的db3.properties配置文件
        response.getWriter().println("<hr/>"); readPropCfgFile2(response);//讀取src目錄下的gacl.servlet.study包中的db4.properties配置文件
 } /** * 讀取src目錄下的gacl.servlet.study包中的db4.properties配置文件 * @param response * @throws IOException */
    private void readPropCfgFile2(HttpServletResponse response) throws IOException {
     //讀取資源文件的路徑不能/src/db4.properties方式,由於工程打包後src目錄就沒了,而會生成在一個名爲classs的文件夾下。必須使用如下方式: InputStream in
= this.getServletContext().getResourceAsStream("/WEB-INF/classes/gacl/servlet/study/db4.properties"); Properties prop = new Properties();
     prop.load(in);
String driver
= prop.getProperty("driver"); String url = prop.getProperty("url"); String username = prop.getProperty("username"); String password = prop.getProperty("password"); response.getWriter().println("讀取src目錄下的gacl.servlet.study包中的db4.properties配置文件:"); response.getWriter().println( MessageFormat.format( "driver={0},url={1},username={2},password={3}", driver,url, username, password)); } /** * 讀取src目錄下的db.config包中的db3.properties配置文件 * @param response * @throws FileNotFoundException * @throws IOException */ private void readPropCfgFile(HttpServletResponse response) throws FileNotFoundException, IOException { //經過ServletContext的方法:getRealPath獲取web資源的絕對路徑 String path = this.getServletContext().getRealPath("/WEB-INF/classes/db/config/db3.properties"); InputStream in = new FileInputStream(path); Properties prop = new Properties(); prop.load(in); String driver = prop.getProperty("driver"); String url = prop.getProperty("url"); String username = prop.getProperty("username"); String password = prop.getProperty("password"); response.getWriter().println("讀取src目錄下的db.config包中的db3.properties配置文件:"); response.getWriter().println( MessageFormat.format( "driver={0},url={1},username={2},password={3}", driver,url, username, password)); } /** * 經過ServletContext對象讀取WebRoot目錄下的properties配置文件 * @param response * @throws IOException */ private void readWebRootDirPropCfgFile(HttpServletResponse response) throws IOException { /** * 經過ServletContext對象讀取WebRoot目錄下的properties配置文件 * 「/」表明的是項目根目錄 */ InputStream in = this.getServletContext().getResourceAsStream("/db2.properties"); Properties prop = new Properties(); prop.load(in); String driver = prop.getProperty("driver"); String url = prop.getProperty("url"); String username = prop.getProperty("username"); String password = prop.getProperty("password"); response.getWriter().println("讀取WebRoot目錄下的db2.properties配置文件:"); response.getWriter().print( MessageFormat.format( "driver={0},url={1},username={2},password={3}", driver,url, username, password)); } /** * 經過ServletContext對象讀取src目錄下的properties配置文件 * @param response * @throws IOException */ private void readSrcDirPropCfgFile(HttpServletResponse response) throws IOException { /** * 經過ServletContext對象讀取src目錄下的db1.properties配置文件 */ InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db1.properties"); Properties prop = new Properties(); prop.load(in); String driver = prop.getProperty("driver"); String url = prop.getProperty("url"); String username = prop.getProperty("username"); String password = prop.getProperty("password"); response.getWriter().println("讀取src目錄下的db1.properties配置文件:"); response.getWriter().println( MessageFormat.format( "driver={0},url={1},username={2},password={3}", driver,url, username, password)); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }

運行結果以下:

  

 

代碼範例:使用類裝載器讀取資源文件

若是讀取資源文件的程序不是servlet的話,例如dao層,service層,沒有servlet的地方,就只能經過類裝載器去讀取

使用方式:

//獲取到裝載當前類的類裝載器 ClassLoader loader = ServletContextDemo7.class.getClassLoader(); //用類裝載器讀取src目錄下的db1.properties配置文件 InputStream in = loader.getResourceAsStream("db1.properties");

第二種:這種方式能讀取到最新的properties文件內容,而上面讀取到的永遠是裝載到類加載器裏面的內容,若是手動修改了properties文件,

那麼新的內容是讀取不到的

//獲取到裝載當前類的類裝載器 ClassLoader loader = ServletContextDemo7.class.getClassLoader(); //用類裝載器讀取src目錄下的db1.properties配置文件 String path = loader.getResource("db1.properties").getPath(); FillInputStream in=new FillInputStream(path);

實例:

package gacl.servlet.study; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.text.MessageFormat; import java.util.Properties; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 用類裝載器讀取資源文件 * 經過類裝載器讀取資源文件的注意事項:不適合裝載大文件,不然會致使jvm內存溢出 * @author gacl * */
public class ServletContextDemo7 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /** * response.setContentType("text/html;charset=UTF-8");目的是控制瀏覽器用UTF-8進行解碼; * 這樣就不會出現中文亂碼了 */ response.setHeader("content-type","text/html;charset=UTF-8"); test1(response); response.getWriter().println("<hr/>"); test2(response); response.getWriter().println("<hr/>"); //test3();
 test4(); } /** * 讀取類路徑下的資源文件 * @param response * @throws IOException */
    private void test1(HttpServletResponse response) throws IOException { //獲取到裝載當前類的類裝載器
        ClassLoader loader = ServletContextDemo7.class.getClassLoader(); //用類裝載器讀取src目錄下的db1.properties配置文件
        InputStream in = loader.getResourceAsStream("db1.properties"); Properties prop = new Properties(); prop.load(in); String driver = prop.getProperty("driver"); String url = prop.getProperty("url"); String username = prop.getProperty("username"); String password = prop.getProperty("password"); response.getWriter().println("用類裝載器讀取src目錄下的db1.properties配置文件:"); response.getWriter().println( MessageFormat.format( "driver={0},url={1},username={2},password={3}", driver,url, username, password)); } /** * 讀取類路徑下面、包下面的資源文件 * @param response * @throws IOException */
    private void test2(HttpServletResponse response) throws IOException { //獲取到裝載當前類的類裝載器
        ClassLoader loader = ServletContextDemo7.class.getClassLoader(); //用類裝載器讀取src目錄下的gacl.servlet.study包中的db4.properties配置文件
        InputStream in = loader.getResourceAsStream("gacl/servlet/study/db4.properties"); Properties prop = new Properties(); prop.load(in); String driver = prop.getProperty("driver"); String url = prop.getProperty("url"); String username = prop.getProperty("username"); String password = prop.getProperty("password"); response.getWriter().println("用類裝載器讀取src目錄下的gacl.servlet.study包中的db4.properties配置文件:"); response.getWriter().println( MessageFormat.format( "driver={0},url={1},username={2},password={3}", driver,url, username, password)); } /** * 經過類裝載器讀取資源文件的注意事項:不適合裝載大文件,不然會致使jvm內存溢出 */
    public void test3() { /** * 01.avi是一個150多M的文件,使用類加載器去讀取這個大文件時會致使內存溢出: * java.lang.OutOfMemoryError: Java heap space */ InputStream in = ServletContextDemo7.class.getClassLoader().getResourceAsStream("01.avi"); System.out.println(in); } /** * 讀取01.avi,並拷貝到e:\根目錄下 * 01.avi文件太大,只能用servletContext去讀取 * @throws IOException */
    public void test4() throws IOException { // path=G:\Java學習視頻\JavaWeb學習視頻\JavaWeb\day05視頻\01.avi // path=01.avi
        String path = this.getServletContext().getRealPath("/WEB-INF/classes/01.avi"); /** * path.lastIndexOf("\\") + 1是一個很是絕妙的寫法 */ String filename = path.substring(path.lastIndexOf("\\") + 1);//獲取文件名
        InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/01.avi"); byte buffer[] = new byte[1024]; int len = 0; OutputStream out = new FileOutputStream("e:\\" + filename); while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } out.close(); in.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }

運行結果以下:

  

4、在客戶端緩存Servlet的輸出

  對於不常常變化的數據,在servlet中能夠爲其設置合理的緩存時間值,以免瀏覽器頻繁向服務器發送請求,提高服務器的性能。例如:

package gacl.servlet.study; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ServletDemo5 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String data = "abcddfwerwesfasfsadf"; /** * 設置數據合理的緩存時間值,以免瀏覽器頻繁向服務器發送請求,提高服務器的性能 * 這裏是將數據的緩存時間設置爲1天 */ response.setDateHeader("expires",System.currentTimeMillis() + 24 * 3600 * 1000); response.getOutputStream().write(data.getBytes()); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }

相關文章
相關標籤/搜索