我有一個擴展RemoteServiceServlet的類。這個類有幾種方法,在一種方法中,我使用getThreadLocalResponse()獲取當前調用的HttpServletResponse,然後在響應中寫入一個File。以下是代碼:GWT的RemoteServiceServlet可以在HttpServletResponse中寫入文件流嗎?
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?
謝謝!