Friday, August 8, 2008
JSP: Save As Pop Up in JSP Another way
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition","attachment; filename=abc.xls");
ServletOutputStream so = response.getOutputStream();
String filename = "c:\\reports\myreport.xls";
String mimetype = "application/vnd.ms-excel";
ByteArrayOutputStream output = new ByteArrayOutputStream();
InputStream in = new BufferedInputStream(new FileInputStream(filename));
byte bytebuff[] = new byte[500];
for(int lengthread = 0; (lengthread = in.read(bytebuff)) != -1;){
output.write(bytebuff, 0, lengthread);
}
byte data[] = output.toByteArray();
response.setContentType(mimetype);
so.write(data);
in.close();
so.close();
WHERE:
abc.xls
is the file name that will automatically appear in the file Name box of SaveAs Pop Up.
and
filename
is the actual file path on your server machine. It may be outside of your WEB-INF directory.
JSP: Save As Pop Up in JSP
Add the following method in the declaration tag of your JSP page.
<%!
void returnFile(String filename, OutputStream out)throws Exception
{
// open file here using File object
File inputFile =new File(filename);
// open stream from that file
FileReader in = new FileReader(inputFile);
int c;
while ((c = in.read()) != -1)
out.write(c);
// close the stream
in.close();
// close the file
}
%>
Step Two:
Add the following code segment in scriptlet tag.
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=ASPTransBreakOut.txt");
// Send the file.
OutputStream outstr = response.getOutputStream( );
returnFile(fileLocation, outstr); // Method implemented in declarative tag in step first
outstr.flush();
WHERE:
ASPTransBreakOut.txt
is the name that will automatically show you up in SaveAs Popup menu
and
fileLocation
is the location of the actual fine on your server.
Monday, October 29, 2007
JSP: sendRedirect() vs. getRequestDispatcher()
Today my other team member was facing a problem and the request objects were destroed when he was using request.sendRedirect(). He was struggling with it and came to me. Actually there is other method to use when you want to pass the origional request objects, that is getRequestDispatcher();
When you want to preserve the current request/response objects and transfer them to another resource WITHIN the context, you must use getRequestDispatcher or getNamedDispatcher.
If you want to dispatch to resources OUTSIDE the context, then you must use sendRedirect. In this case you won't be sending the original request/response objects, but you will be sending a header asking to the browser to issue a request to the new URL.
NOTE: If you don't need to preserve the request/response objects, you can use either.