也许是愚蠢的问题:我正在尝试使用 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/