Can GWT's RemoteServiceServlet write a file stream in HttpServletResponse?
I have a class that extends RemoteServiceServlet. This class has several methods, in one method, I use getThreadLocalResponse() to get the HttpServletResponse for the current call, and then write a File in the response. Here is the code:
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();
However, an error always occurs. After debugging, I find out that an Exception is thrown when it writes the response.
I don't override doGet and doPost, because there are some other methods, I don't want every request to the class can invoke this piece of code.
But if I create a separate Servlet or override doGet or doPost in this class, it works fine.
Does anybody know why? Does GWT RemoteServiceServlet support writing a Stream in the response when we use getThreadLocalResponse() ?
Thanks!
Are you putting this code inside of a GWT-RPC method in your RemoteServiceServlet?
If yes, then you are trying to mix GWT-RPC with some of your own content, which you are not allowed to do. You can't just write arbitrary data to http response as this will clearly mess up the RPC protocol.
OTOH, if your just putting some of your own methods side-by-side to GWT-RPC methods, then why not creating a new Servlet?
AFAIK, GWT-RPC uses http POST, so overriding doGet() should work for your functionality and leave GWT-RPC working. But overriding doPost() will break GWT-RPC.
精彩评论