sun Httpserver:从Handler访问外部创建的对象
也许是愚蠢的问题:我正在尝试使用 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? 有什么方法可以将对象作为参数传递给处理程序吗?
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:
- first, it creates an object (an HashMap) which will be lately and periodically updated every 24 hours
- then there will be an handler which will process the requests received. This processing phase is done basing on the content of the HashMap, which is created outside the handler.
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,使用包装类:
Yes, with a wrapper class: