首页 > 解决方案 > 如何将 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?我尝试了很多方法,但它们也不起作用。将感谢所有答案。

标签: jsfservletsjsf-2

解决方案


要创建一个 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> 

推荐阅读