深刻分析JavaWeb Item6 -- servletConfig 與servletContext詳解

1、ServletConfig講解

首先看ServletConfig API文檔html

這裏寫圖片描述

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

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

例如:mysql

<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的初始化參數信息。程序員

例如:web

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);
    }

}

運行結果以下:sql

  這裏寫圖片描述

2、ServletContext對象

  WEB容器在啓動時,它會爲每一個WEB應用程序都建立一個對應的ServletContext對象,它表明當前web應用。
  ServletConfig對象中維護了ServletContext對象的引用,開發人員在編寫servlet時,能夠經過ServletConfig.getServletContext方法得到ServletContext對象,可是還有更簡潔的this.getServletContext()方法;
  
  <font color="red">因爲一個WEB應用中的全部Servlet共享同一個ServletContext對象,所以Servlet對象之間能夠經過ServletContext對象來實現通信。ServletContext對象一般也被稱之爲context域對象:1,是一個容器 2。做用範圍是應用程序範圍。數據庫

3、ServletContext的應用

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

  範例:ServletContextDemo1ServletContextDemo2經過ServletContext對象實現數據共享apache

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應用的初始化參數

  若是想在全部的Servlet應用中都要配置並讀取初始化參數,則能夠在web.xml文件的<web-app>中使用<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應用的初始化參數,代碼以下:

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實現請求轉發

實現Servlet的轉發。

  • 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對象讀取資源文件,由於文件的位置不一樣,全部讀取的方式也不一樣,通常來講分爲兩種狀況:

  • 在Servlet的context域中讀取文件,工程目錄下的src目錄發佈到服務器中,會映射到「/WEB-INF/classes」文件夾下。因此要一一對應。並且這個是相對目錄,相對於web服務器的目錄。若是要用傳統的文件讀取文件,則要使用絕對路勁

PrintWriter out = response.getWriter();
        ServletContext context = this.getServletContext();
        String path = context.getRealPath("/WEB-INF/classes/itcast.properties");
        InputStream in = new FileInputStream(path);
        Properties pro = new Properties();
        pro.load(in);
  • 若是是非servlet中讀取配置文件,則要使用類加載器去讀取。稍後講到
     

項目目錄結構以下:

  這裏寫圖片描述

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

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 {
        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獲取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層讀取配置文件),採用類裝載器 classLoader,你能夠先採用servlet服務先讀取,而後在把servlet傳遞給dao,這樣雖然能夠實現,可是,這樣損壞了咱們編代碼的設計原則,就是層之間不能有交織在一塊兒的東西。

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);
    }

}

  運行結果以下:

這裏寫圖片描述

使用類裝載器讀取資源文件,存在的問題是;類裝載器,每次只會裝載一次。

//若是讀取資源文件的程序不是servlet的話,
//就只能經過類轉載器去讀了,文件不能太大
//用傳遞參數方法很差,耦合性高
public class UserDao {

    private static Properties dbconfig=new Properties();
    static {
        InputStream in=UserDao.class.getClassLoader().getResourceAsStream("db.properties");
        try {
            dbconfig.load(in);
        } catch (IOException e) {
            throw new ExceptionInInitializerError(e);
        }    
        //上面代碼類裝載器只裝載一次,下面代碼用類裝載方式獲得文件位置
        URL url=UserDao.class.getClassLoader().getResource("db.properties");
        String str=url.getPath();
        //file:/C:/apache-tomcat-7.0.22/webapps/day05/WEB-INF/classes/db.properties
        try {
            InputStream in2=new FileInputStream(str);
            try {
                dbconfig.load(in2);
            } catch (IOException e) {
                throw new ExceptionInInitializerError(e);
            }
        } catch (FileNotFoundException e1) {
            throw new ExceptionInInitializerError(e1);
        }        
    }
    public void update() {
        System.out.println(dbconfig.get("url"));
    }
}

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);
    }

}

這裏寫圖片描述

相關文章
相關標籤/搜索