ServletContext

主要功能

在web容器啟動時,會為每個webapp創(chuàng)建一個ServletContext,代表了當前的web應用。

  • 數(shù)據(jù)共享
    通過Attributegetter,setter方法來實現(xiàn),Attribute本質為鍵值對。
  • 獲取初始參數(shù)
    可以通過getInitParameter方法獲取在web.xml中設置的初始參數(shù)。
    <context-param>
        <param-name>paramName</param-name>
        <param-value>value</param-value>
    </context-param>
  • 請求轉發(fā)
    <servlet>
        <servlet-name>hello</servlet-name>
        <servlet-class>com.servlet.HelloServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>
    
    <servlet>
        <servlet-name>forward</servlet-name>
        <servlet-class>com.servlet.ContextDemo</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>forward</servlet-name>
        <url-pattern>/forwardTest</url-pattern>
    </servlet-mapping>
public class ContextDemo extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = this.getServletContext();
        context.getRequestDispatcher("/hello").forward(req, resp);
    }
}

上述代碼會將指向ContextDemo的url轉發(fā)到HelloServlet中,但是在瀏覽器中的url欄路徑并不會發(fā)生變化,只是在服務器內(nèi)部進行的定位的轉移。但是與重定向并不等同。

  • 獲取資源文件
    ServletContext 可以通過getResource方法獲取當前web應用目錄下的資源文件(可以通過配置將資源文件集中打包在classpath中即/WEB-INF/classes/*.*)
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = this.getServletContext();

        Properties properties = new Properties();
        properties.load(context.getResourceAsStream("/WEB-INF/classes/demo.properties"));

        String username = (String)properties.get("username");
        String password = (String)properties.get("password");

        resp.getWriter().print(username + ":" + password);
    }
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容