jsf - 如何将 JSF(h:commandButton) 与 Servlet 连接
问题描述
在我的项目(JSF+ MAVEN)中,我想使用 servlet 从我的数据库中下载 PDF 文件(即,比我单击按钮,servlet 必须从数据库下载文件)但是我在 JSF 'commandButton' 中编写的所有内容都不起作用。 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);
}
}
}
这是我的项目结构。 项目结构
如何正确编写导航到这个 servlet?我尝试了很多方法,但它们也不起作用。将感谢所有答案。
解决方案
要创建一个 servlet,您不需要只实现 Servlet 扩展。
public class HelloWorld extends HttpServlet {}
将您的方法名称doGet
更改public
为非私有。
然后用这种简单的方式调用Servlet,别忘了加上target="_blank"
<h:outputLink value="/DownloadFile?param=param_value" target="_blank">
<f:param name="param1" value="value1" />
</h:outputLink>
或纯 HTML:
<a href="/DownloadFile?param=" target="_blank">
#{node.reportName}
</a>
推荐阅读
- c++ - 如果一个对象是在本地创建的并在 C++ 中作为异常抛出,那么本地对象如何在其范围之外有效。即在 catch 块中?
- swift - 如何在 Swift 中使用字典初始化结构
- python-3.x - 使用 .splitlines() 时如何删除特殊字符
- c# - 如何从视图中获取输入列表?
- javascript - 填充轮盘的内容
- ckeditor5 - 如何向 Ckeditor5 添加 Font Awesome 支持?
- javascript - 异步函数返回承诺,但调用函数未解析
- javascript - npm 漏洞对前端很重要吗?
- pentaho - 如何在 Pentaho 仪表板上插入有条件的图像?
- visual-studio - VS 2017 在调试期间显示不正确的 C++ Unicode 文字