【发布时间】:2018-06-13 18:11:25
【问题描述】:
在我的项目(JSF+ MAVEN)中,我想使用 servlet 从我的数据库中下载 PDF 文件(即,比我单击按钮,servlet 必须从数据库下载文件)但我在 JSF 'commandButton' 中编写的所有内容都不要' t 工作。CommandButton 看不到 servlet。
这是 content.xhtml 中带有“commandButton”的表单
<h:form>
<h:commandButton action="/DownloadFile" value="#{msg.download}"styleClass="download-Button">
<f:param name="file_id=#{b.id} "/>
</h:commandButton>
</h:form>
这是 'Downloadfile' servlet,它从 DB 下载 PDF 文件。 PDF 文件作为相对路径保存在 DB 的“内容”列中。
public class DownloadFile extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
private String content;
private String name;
private Connection conn;
private PreparedStatement ps;
private ResultSet rs;
private void getFileFromDb(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
try {
Map<String, String> params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
int selectedFileID = Integer.valueOf(params.get("file_id"));
System.out.println("Id====" + selectedFileID);
conn = DataBase.getConnection();
ps = conn.prepareStatement("SELECT content,name FROM book WHERE id= "+ selectedFileID);
rs = ps.executeQuery();
while (rs.next()){
content = rs.getString("content");
name = rs.getString("name");
}
} catch (SQLException e) {
e.printStackTrace();
}
String contextPath = "D:\\IdeaProjects\\Books\\";
File pdfFile = new File(contextPath + content);
response.setContentType("application/pdf");
response.addHeader("Content-Disposition", "attachment; filename=" + name+".pdf");
response.setContentLength((int) pdfFile.length());
FileInputStream fileInputStream = new FileInputStream(pdfFile);
OutputStream responseOutputStream = response.getOutputStream();
int bytes;
while ((bytes = fileInputStream.read()) != -1) {
responseOutputStream.write(bytes);
}
}
}
这是我的项目结构。 Project structure
如何正确地编写导航到这个 servlet?我尝试了很多方法,但它们也不起作用。将感谢所有答案。
【问题讨论】:
-
为什么你认为你需要一个命令按钮呢?或者反过来说,如果你使用commandButton,你为什么要使用servlet?您正在尝试混合不打算一起使用的解决方案(一次通话)。题外话:阅读stackoverflow.com/questions/30639785/… 并将其应用于您的代码。在您阅读“jsf 控制器”的地方,您也可以阅读“servlet”。关注点分离。如果你在服务中“包装”了真正的逻辑,stackoverflow.com/questions/9391838/… 就变得很容易了
-
非常感谢。这个例子stackoverflow.com/questions/9391838/…帮助我解决了我的问题。