2011-06-01 65 views
1

我有一個擴展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?

謝謝!

回答

2

您是否將此代碼放入RemoteServiceServlet中的GWT-RPC方法內部?

如果是,那麼你試圖將GWT-RPC與你自己的一些內容混合在一起,這是你不允許的。你不能只寫任意數據給http響應,因爲這會明顯搞亂RPC協議。

OTOH,如果您只是將一些自己的方法並行放到GWT-RPC方法中,那麼爲什麼不創建新的Servlet呢? AFAIK,GWT-RPC使用http POST,因此覆蓋doGet()應該適用於您的功能,並使GWT-RPC正常工作。但是重寫doPost()會打破GWT-RPC。

相關問題