Servlet之ServletContext獲取web上下文路徑、全局參數、和Attribute(域)


1)獲取web上下文路徑

 

public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //獲取ServletContext對象
        //this.getServletConfig().getServletContext();
        //等同於下面一句,因為創建getServletContext必須要通過getServletConfig對象
        ServletContext context = this.getServletContext();
        
        //獲取web的上下文路徑,
        String path = context.getContextPath();
        
        //請求重定向,這樣的好處可以讓獲取的路徑更加靈活。不用考慮項目名是否發生了變化。
        response.sendRedirect(context.getContextPath()+"/index.jsp");
    }
}

 


2)獲取全局參數

 

public class ServletContextDemo1 extends HttpServlet {
    /**
     * 獲取全局參數
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
         ServletContext context = this.getServletContext();
         //根據參數名獲取參數值
         System.out.println(context.getInitParameter("MMM"));
         //獲取所有的參數名,返回枚舉類型
         Enumeration<String> emn = context.getInitParameterNames();
         while(emn.hasMoreElements()){
             String paramName = emn.nextElement();
             String paramValue = context.getInitParameter(paramName);
             System.out.println(paramName+"="+paramValue);
         }
    }
 
}

 

 

3)和域相關

域:域對象在不同的資源之間來共享數據,保存數據,獲取數據。

這個我使用了三個Servlet來說明這個問題,ScopeDemo1用於獲取Attribute,ScopeDemo2用於設置Attribute,ScopeDemo3用於刪除Attribute。

 

保存共享數據:

 

public class ScopeDemo2 extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //首先創建ServletContext對象
    ServletContext context =     this.getServletContext();
    //保存共享數據
    context.setAttribute("name", "zhangsan");//第一個參數為字符串,第二個是Object(也就是任意類型)
    System.out.println("設置成功");
    
    }
 
}

 

獲取恭喜數據:

 

public class ScopeDemo1 extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //創建ServletContext對象
        ServletContext context = this.getServletContext();
        //獲取共享數據內容
        String name = (String)context.getAttribute("nnn");
        System.out.println(name);
    }
}

 


刪除共享數據:

 

public class ScopeDemo3 extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //獲取ServletContext對象
        ServletContext context =     this.getServletContext();
        //刪除共享數據
        context.removeAttribute("name");
        System.out.println("刪除成功");        
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM