Search code examples
javaxmlservletscontextpath

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


I'm new to Java Servlets, and for the application I'm currently working on, (some kind of Proxy without forwading or Redirect classes) I would like to save an object to the context path of the application.

I know there are similar questions, but I can't get it to work or I just don't understand it.

Do I have to specifiy the context path in the web.xml? Do I Need a context listener?

This is the code snippet but the Objects within the saved Object are null; how can I save the current state of an Object to the context path?

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

Solution

  • The response object of HttpServletResponse is never null, because it is created by the web container when a first request is made to your servlet.

    Therefore, the attribute "oldConnector" is not set, so you are getting its value as null.

    Suggestion: Set the context attribute "oldConnector" by removing the if(response==null) condition. And retrieve that attribute in another servlet or same then remove it if required to.

    Below code may help you for your query in comments.

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