我正在使用以下代码作为GWT-RPC的GWT服务器端类(servlet)的一部分。
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用于客户端,使用GWT-RPC进行客户端 - 服务器通信。
答案 0 :(得分: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")