我试图从JSF托管bean调用servlet。我尝试了以下代码,但未调用servlet。
托管bean代码
FacesContext fc = FacesContext.getCurrentInstance();
ServletContext sc = (ServletContext) fc.getExternalContext().getContext();
sc.getRequestDispatcher("/download?file=#{attachments.filePath}");
Servlet代码
@WebServlet("/download")
......
ServletOutputStream servletOutputStream = null;
BufferedInputStream bufferedInputStream = null;
BufferedOutputStream bufferedOutputStream = null;
try {
// file to download
String filePath = request.getParameter("file").trim();
// Check also Windows style path (for development)
int index = filePath.lastIndexOf("/") != -1 ? filePath.lastIndexOf("/") : filePath.lastIndexOf("\\");
String fileName = filePath.substring(index + 1);
bufferedInputStream = new BufferedInputStream(new FileInputStream(filePath));
byte[] data = new byte[bufferedInputStream.available()];
bufferedInputStream.read(data);
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
servletOutputStream = response.getOutputStream();
bufferedOutputStream = new BufferedOutputStream(servletOutputStream);
bufferedOutputStream.write(data);
}