Reputation: 129
In my project(JSF+ MAVEN) i want to download PDF Files from my DB using servlet,(i.e. than i click the button,servlet must download file from DB) but all what i am writing in JSF 'commandButton' don't work.CommandButton don't see servlet.
This is form with 'commandButton' in content.xhtml
<h:form>
<h:commandButton action="/DownloadFile" value="#{msg.download}"styleClass="download-Button">
<f:param name="file_id=#{b.id} "/>
</h:commandButton>
</h:form>
This is 'Downloadfile' servlet, which download PDF files from DB. PDF files saves in column 'content' in DB as relative path.
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);
}
}
}
This is my project structure. Project structure
How to correctly write navigation to this servlet? I have tried many ways, but they also don't works.Will be gratefull for all answers.
Upvotes: 0
Views: 704
Reputation: 470
For create a servlet you don´t need to implement the Servelet only extend.
public class HelloWorld extends HttpServlet {}
Change your method name to doGet
and change for public
not private.
Then call the Servlet with this simple way, don´t forget to add target="_blank"
<h:outputLink value="/DownloadFile?param=param_value" target="_blank">
<f:param name="param1" value="value1" />
</h:outputLink>
Or pure HTML:
<a href="/DownloadFile?param=" target="_blank">
#{node.reportName}
</a>
Upvotes: 1