2013-08-30 59 views
2

我已經編寫了ServletContext對象的演示程序,其中我使用context.setAttribute(arg1,arg2)來設置值。我想在另一個servlet中訪問同一個對象。 如何在另一個servlet中訪問context對象設置的值。如何在另一個servlet中訪問相同的ServletContext對象?

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 

    response.setContentType("text/html"); 
    PrintWriter out = response.getWriter(); 

    String name = "Amrut"; 

    ServletContext context = request.getServletContext(); 

    context.setAttribute("contextuname", name); 

    out.println("Context==>" + context.getAttribute("contextuname")); 
} 

我的問題是,訪問這個對象我要創建ServletContext對象,並使用context.getAttribute(arg1,arg2),我會得到價值。或者有另外的價值來做到這一點。

+1

每個應用程序只有一個「ServletContext」可用。它的'ServletConfig'是不同的。 –

回答

0

我的問題是,訪問這個對象我要創建ServletContext對象,並通過使用context.getAttribute(ARG1,ARG2),我會得到價值。或者有另外的價值來做到這一點。

您將通過在另一個servlet中創建context對象與上述內容相同來獲得價值。
java docs

有每Java虛擬機 「Web應用程序」 一個上下文。

1

按了Java文檔

There is one context per "web application" per Java Virtual Machine. 

所以你的語境對象將可用於所有servlet。並且上下文對象中的屬性也會。

my question is, for accessing this object i have to create ServletContext object 

它將返回相同的上下文對象,它不會產生一個新的對象

0

在服務(的doGet/doPost方法)在同一應用程序另一個servlet的方法,執行此

ServletContext的上下文= request.getServletContext();

String uName =(String)context.getAttribute(「contextuname」);

相關問題