5

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

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

4

1 に答える 1

12

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

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

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

于 2011-06-27T14:28:49.787 に答える