也许是愚蠢的问题:我正在尝试使用com.sun.net.httpserver包在Java中实现一个小服务器。我正处于服务器编程的最初阶段,所以可能我错过了一些东西。
它应该像这样工作:
伪代码(非常脏的东西)
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? 有没有办法将对象作为参数传递给处理程序?
答案 0 :(得分:1)
是的,使用包装类:
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(...);
}
}
}