2011-07-15 55 views
0

也許愚蠢的問題:我試圖用com.sun.net.httpserver包實現Java中的一個小型服務器。我處於服務器編程的最初階段,所以可能我錯過了一些東西。sun Httpserver:從處理程序訪問外部創建的對象

它應該是這樣的:

  • 第一,它創建將每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的? 有沒有辦法將對象作爲參數傳遞給處理程序?

回答

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(...); 
      } 
     } 
    } 
相關問題