2011-06-27 8 views
5

私はGWT-RPCのためのGWTサーバー側のクラス(サーブレット)の一環として、次のコードを使用しています。GWT Imageクラスを使用してサーブレットで画像を取得して表示する方法は?

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

私はクライアントのボタンを押すとサーブレットが実行されています。私は、クライアントにイメージをロードするためにImageクラスを使用したいが、私はそれを表示するために、クライアントのコードにサーブレットから画像のURLを取得する方法がわかりません。これは正しい手順ですか、別の方法がありますか?私は、クライアントとGWT-RPCをクライアントとサーバの通信に使用します。

答えて

12

サーブレットはVARIOSのHTTPメソッドに対応:GET、POST、PUT、HEADを。 GWTのnew Image(url)を使用し、GETを使用するため、GETメソッドを処理するサーブレットが必要です。

それはHttpServletののdoGet(..)メソッドをオーバーライドする必要がありますGETメソッドを処理するサーブレットのために。

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-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

私がイメージのセットを持っている場合、彼らができますあなたの例のように単一のサーブレットで表示されますか? –

+0

はい、サーブレットにパラメータを渡す必要があります: '/ images?name = something' –

+1

次に、' String param = req.getParameter( "name") 'でサーブレットのパラメータを取得できます。 –

関連する問題