Java sun Httpserver:从处理程序访问外部创建的对象

Java sun Httpserver:从处理程序访问外部创建的对象,java,hashmap,httphandler,com.sun.net.httpserver,Java,Hashmap,Httphandler,Com.sun.net.httpserver,可能是一个愚蠢的问题:我正试图用com.sun.net.httpserver包在Java中实现一个小服务器。我正处于服务器编程的最开始阶段,因此可能遗漏了一些东西 它应该是这样工作的: 首先,它创建一个对象(HashMap),该对象将在最近每隔24小时定期更新一次 然后将有一个处理程序来处理收到的请求。这个处理阶段是基于HashMap的内容完成的,HashMap是在处理程序外部创建的 伪代码(非常肮脏的东西) 问题是:如何允许我的处理程序读取Hashmap? 是否有某种方法将对象作为参数传递

可能是一个愚蠢的问题:我正试图用com.sun.net.httpserver包在Java中实现一个小服务器。我正处于服务器编程的最开始阶段,因此可能遗漏了一些东西

它应该是这样工作的:

  • 首先,它创建一个对象(HashMap),该对象将在最近每隔24小时定期更新一次
  • 然后将有一个处理程序来处理收到的请求。这个处理阶段是基于HashMap的内容完成的,HashMap是在处理程序外部创建的
伪代码(非常肮脏的东西)

问题是:如何允许我的处理程序读取Hashmap?
是否有某种方法将对象作为参数传递给处理程序?

是,使用包装类:

    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(...);
            }
        }
    }
    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(...);
            }
        }
    }