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