2011-06-27 56 views
5

我使用下面的代碼作爲GWT-RPC的GWT服務器端類(servlet)的一部分。如何使用servlet獲取圖像並使用GWT圖像類顯示它?

private void getImage() { 
     HttpServletResponse res = this.getThreadLocalResponse(); 
     try { 
      // Set content type 
      res.setContentType("image/png"); 

      // Set content size 
      File file = new File("C:\\Documents and Settings\\User\\image.png"); 
      res.setContentLength((int) file.length()); 

      // Open the file and output streams 
      FileInputStream in = new FileInputStream(file); 
      OutputStream out = res.getOutputStream(); 

      // Copy the contents of the file to the output stream 
      byte[] buf = new byte[1024]; 
      int count = 0; 
      while ((count = in.read(buf)) >= 0) { 
       out.write(buf, 0, count); 
      } 
      in.close(); 
      out.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 

當我按下客戶端上的按鈕時,servlet正在運行。我想使用Image類將圖像加載到客戶端,但我不知道如何從servlet獲取圖像的URL到客戶端的代碼以顯示它。這是正確的程序還是有另一種方式?我爲客戶端和GWT-RPC使用GWT進行客戶端 - 服務器通信。

回答

12

Servlets響應varios HTTP方法:GET,POST,PUT,HEAD。由於您使用GWT的new Image(url),並且它使用GET,所以您需要有一個處理GET方法的servlet。

爲了讓servlet處理GET方法,它必須覆蓋HttpServlet的doGet(..)方法。

public class ImageServlet extends HttpServlet { 

    public void doGet(HttpServletRequest req, HttpServletResponse resp) 
     throws IOException { 

     //your image servlet code here 
     resp.setContentType("image/jpeg"); 

     // Set content size 
     File file = new File("path/to/image.jpg"); 
     resp.setContentLength((int)file.length()); 

     // Open the file and output streams 
     FileInputStream in = new FileInputStream(file); 
     OutputStream out = resp.getOutputStream(); 

     // Copy the contents of the file to the output stream 
     byte[] buf = new byte[1024]; 
     int count = 0; 
     while ((count = in.read(buf)) >= 0) { 
      out.write(buf, 0, count); 
     } 
     in.close(); 
     out.close(); 
    } 
} 

然後,你必須在web.xml文件中配置路徑到Servlet:

<servlet> 
    <servlet-name>MyImageServlet</servlet-name> 
    <servlet-class>com.yourpackage.ImageServlet</servlet-class> 
</servlet> 
<servlet-mapping> 
    <servlet-name>MyImageServlet</servlet-name> 
    <url-pattern>/images</url-pattern> 
</servlet-mapping> 

然後調用它在GWT:new Image("http:yourhost.com/images")

+0

如果我有一組圖片,他們可以由你的例子中的單個servlet顯示? –

+0

是的,你需要傳遞一個參數給servlet:'/ images?name = something' –

+1

然後你可以通過'String param = req.getParameter(「name」)' –

相關問題