Search code examples
javahashmaphttphandlercom.sun.net.httpserver

sun Httpserver: access from the Handler to an object created externally


Maybe dumb question: I'm trying to realize a little server in Java with com.sun.net.httpserver package. I am at the very beginning of server programming, so probably I'm missing something.

It should work like this:

  • first, it creates an object (an HashMap) which will be lately and periodically updated every 24 hours
  • then there will be an handler which will process the requests received. This processing phase is done basing on the content of the HashMap, which is created outside the handler.

pseudo code (something very dirt)

public static void main(String args[]){

  // creation of the HashMap (which has to be periodically updated)

 HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
 server.createContext("/hashmap", new Handler());
 server.start();
 }

 class Handler implements HttpHandler {
     public void handle(HttpExchange xchg) throws IOException {

         //operations which involves (readonly) the HashMap previously created
     }
 }

The question is: how to allow my handler to read the Hashmap? Is there some way to pass the object as a parameter to the handler?


Solution

  • Yes, with a wrapper class:

        public class httpServerWrapper{
            private HashMap map = ...;
    
            public httpServerWrapper(int port) {
                HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
                server.createContext("/hashmap", new Handler());
                server.start();
            }
    
            public static void main(String args[]){
                int port = 8000;
                new httpServerWrapper(port);
            }
    
            public class Handler implements HttpHandler {
                public void handle(HttpExchange xchg) throws IOException {
    
                    map.get(...);
                }
            }
        }