【问题标题】:How to connect JSF(h:commandButton) with Servlet如何将 JSF(h:commandButton) 与 Servlet 连接
【发布时间】: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?我尝试了很多方法,但它们也不起作用。将感谢所有答案。

【问题讨论】:

标签: jsf servlets jsf-2


【解决方案1】:

要创建一个 servlet,您不需要只实现 Servlet 扩展。

public class HelloWorld extends HttpServlet {}

将您的方法名称更改为 doGet 并更改为 public not private。

然后用这种简单的方式调用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> 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-21
    • 1970-01-01
    • 2011-08-20
    • 2017-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多