2011-06-27 32 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”)' –