java - 太阳http服务器: access from the Handler to an object created externally

标签 java hashmap httphandler com.sun.net.httpserver

也许是愚蠢的问题:我正在尝试使用 com.sun.net.httpserver 包在 Java 中实现一个小服务器。我正处于服务器编程的最初阶段,所以可能我遗漏了一些东西。

它应该像这样工作:

  • 首先,它创建一个对象(HashMap),该对象将每 24 小时定期更新一次
  • 然后会有一个处理程序来处理收到的请求。此处理阶段是根据 HashMap 的内容完成的,HashMap 是在处理程序外部创建的。

伪代码(非常肮脏的东西)

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
     }
 }

问题是:如何允许我的处理程序读取 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(...);
            }
        }
    }

关于java - 太阳http服务器: access from the Handler to an object created externally,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6707735/

相关文章:

java - 我们可以在 java 中使用 replaceAll() 进行多次替换吗

java - 将 Scala 单位转换为 Java Void

java - 为什么自定义对象不是 HashMap 的等效键?

java - 如何写入/放入具有两个键(键对、值)的 HashMap?

c# - 通过HttpHandler用ajax获取数据

asp.net - 未调用 HttpHandler

java - 无法解析 org.springframework.cloud :spring-cloud-starter-netflix-eureka-client:unknown

java - 如何在应用层正确实现乐观锁?

java - 我应该使用什么数据结构来在恒定时间内从一对变化的值到java中的对象进行查找?

javascript - 使用 jQuery AJAX 和 ASP.NET 与数据库通信