簡體   English   中英

如何在 Servlet 的上下文路徑中保存/獲取對象的當前狀態

[英]how to save/get current state of an object to/from the context path of a Servlet

我是 Java Servlet 的新手,對於我目前正在開發的應用程序(某種沒有轉發或重定向類的代理),我想將一個對象保存到應用程序的上下文路徑中。

我知道有類似的問題,但我無法讓它發揮作用,或者我只是不明白。

我是否必須在 web.xml 中指定上下文路徑? 我需要上下文偵聽器嗎?

這是代碼片段,但保存的對象中的對象為空; 如何將對象的當前狀態保存到上下文路徑?

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

    try {

        if(this.getServletContext().getAttribute("oldConnector")==null){
            Connector connection = new Connector(); 
            connection.sendRequest(request);
            this.getServletContext().setAttribute("oldConnector", connection);
        }else{
             ((Connector)this.getServletContext().getAttribute("oldConnector")).sendResponse(response); 
             this.getServletContext().removeAttribute("oldConnector");
        }

HttpServletResponse 的響應對象永遠不會為 null ,因為它是在向您的 servlet 發出第一個請求時由 Web 容器創建的。

因此,未設置屬性“oldConnector”,因此您將其值為 null。

建議:通過刪除 if(response==null) 條件來設置上下文屬性“oldConnector”。 並在另一個 servlet 或相同的 servlet 中檢索該屬性,然后根據需要將其刪除。

下面的代碼可以幫助您在評論中查詢。

        if(getServletContext().getAttribute("oldConnector") == null){
            getServletContext().setAttribute("oldConnector", "old value");//dummy value added, replace it with your connection object.
            System.out.println("oldConnector attribute has be set.");
        }else{
            getServletContext().removeAttribute("oldConnector");
            System.out.println("oldConnector attribute has be removed");
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM