GWT的RemoteServiceServlet可以在HttpServletResponse中写一个文件流吗?

时间:2011-06-01 07:31:48

标签: gwt servlets

我有一个扩展RemoteServiceServlet的类。这个类有几个方法,在一个方法中,我使用getThreadLocalResponse()来获取当前调用的HttpServletResponse,然后在响应中写入一个File。这是代码:

File aFile = new File("c://test.txt");
int iBufferSize = 1000;
int iLength = 0;

HttpServletResponse resp = getThreadLocalResponse();

ServletOutputStream op = resp.getOutputStream();
ServletContext context = getServletConfig().getServletContext();
String mimetype = context.getMimeType(aFile.getName());

resp.setContentType((mimetype != null) ? mimetype : "application/octet-stream");
resp.setContentLength((int) aFile.length());
resp.setHeader("Content-Disposition", "attachment; filename=\"" + aFile.getName() + "\"");

byte[] xbuf = new byte[iBufferSize];
DataInputStream in = new DataInputStream(new FileInputStream(aFile));

while ((in != null) && ((iLength = in.read(xbuf)) != -1))
{
  op.write(xbuf, 0, iLength);
}

in.close();
op.flush();
op.close();

但是,总会发生错误。调试之后,我发现在写入响应时会抛出异常。

我不会覆盖doGet和doPost,因为还有其他一些方法,我不希望每个请求都可以调用这段代码。

但是如果我在这个类中创建一个单独的Servlet或覆盖doGet或doPost,它可以正常工作。

有人知道为什么吗?当我们使用getThreadLocalResponse()时,GWT RemoteServiceServlet是否支持在响应中编写Stream?

谢谢!

1 个答案:

答案 0 :(得分:2)

您是否将此代码放在RemoteServiceServlet中的GWT-RPC方法中?

如果是,那么您正在尝试将GWT-RPC与您自己的一些内容混合在一起,而您不允许这样做。你不能只是将任意数据写入http响应,因为这显然会破坏RPC协议。

OTOH,如果你只是将自己的一些方法并排放到GWT-RPC方法中,那么为什么不创建一个新的Servlet呢?

AFAIK,GWT-RPC使用http POST,因此覆盖doGet()应该适用于您的功能并使GWT-RPC正常工作。但是重写doPost()会破坏GWT-RPC。