Issue
I am new with JSP and servlets. I have done code for uploading multiple files to MySQL database and it is successful. I have one jsp page("filelist.jsp") which contains all uploaded files by user.
So I want to Search particular file using more filter options in JSP. I also tried using filtering and now it is partially completed. I have one ("Search.jsp") page where user searched data will be displayed. I also have "Download" column in my code so that user can download that file.
But the problem is that I am not able to download particular file from search.jsp page. I am using Netbeans 8, Tomcat 8.
This is my filelist.jsp page:
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.Statement"%>
<%@page import="com.servlet.db.DB"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.sql.Connection"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="bootstrap.css" rel="stylesheet" type="text/css">
<title>file_list Page</title>
<style>
tr,td,th{
padding: 20px;
text-align: center;
}
.container {
position:"absolute";
padding: 16px 0px;
top:0;
right:0;
display: flex;
justify-content: space-between;
align-items: center;
}
form.form-inline{
float: right;
}
#ddl{
width:150px;
}
#ddl2{
width:150px;
}
#cat{
width:175px;
}
</style>
</head>
<body>
<!-- <form action="" method="POST">
<div class="container">
<div class="form-group">
<div class="input-group">
<input type="text" name="search" class="form-control" placeholder="Search here..." autocomplete="off"/>
<button type="submit" value="Search" class="btn btn-primary">Search</button>
</div>
</div>
</div>
</form> -->
<h3>Search here..</h3>
<form action="logout.jsp" align="right">
<input type="submit" value="Logout"/>
</form>
<form name="empForm" action="search.jsp" method="post">
<div>
<table border="1" colspan="2">
<thead>
<tr>
<th style="alignment-adjust: auto">Z ID:</th>
<td><input type="text" name="zid" value="" /></td>
</tr>
<tr>
<th>First Name :</th>
<td><input type="text" name="firstname" value="" /></td>
</tr>
<tr>
<th>Last Name:</th>
<td><input type="text" name="lastname" value=""/></td>
</tr>
<tr style="display:none">
<th>Division:</th>
<td><input type="text" name="division" value=""/></td>
</tr>
<tr style="display:none">
<th>Reporting Unit:</th>
<td><input type="text" name="reportingunit" value=""/></td>
</tr>
<tr style="display:none">
<th>Document No.</th>
<td><input type="text" name="documentnumber" value=""/></td>
</tr>
<tr style="display:none">
<th>Document Name:</th>
<td><input type="text" name="documentname" value=""/></td>
</tr>
<tr style="display:none">
<th>Document Uploader:</th>
<td><input type="text" name="documentuploader" value=""/></td>
</tr>
<tr style="display:none">
<th>Document Owner:</th>
<td><input type="text" name="documentowner" value=""/></td>
</tr>
<tr>
<th>Document Type</th>
<td>
<select name="documenttype">
<option value=""></option>
<option value="Agreement">Agreement</option>
<option value="Contract">Contract</option>
<option value="PO">PO</option>
<option value="Invoice">Invoice</option>
<option value="COA">COA</option>
<option value="Lease Deed">Lease Deed</option>
<option value="AMC">AMC</option>
<option value="Direct Material">Direct Material</option>
<option value="Indirect Material/Services">Indirect Material/Services</option>
</select>
</td>
</tr>
<tr>
<th>Document Category</th>
<td>
<select name="documentcategory" id="cat">
<option value=""></option>
<option value="Customer">Customer</option>
<option value="Vendor">Vendor</option>
<option value="Internal">Internal</option>
</select>
</td>
</tr>
<tr style="display:none">
<th>By Function:</th>
<td><input type="text" name="byfunction" value=""/></td>
</tr>
<tr style="display:none">
<th>Creator:</th>
<td><input type="text" name="creator" value=""/></td>
</tr>
<tr style="display:none">
<th>Modifier:</th>
<td><input type="text" name="modifier" value=""/></td>
</tr>
<tr style="display:none">
<th>Approver:.</th>
<td><input type="text" name="approver" value=""/></td>
</tr>
<tr style="display:none">
<th>Mail Id:</th>
<td><input type="text" name="mailid" value=""/></td>
</tr>
<tr style="display:none">
<th>Added Date:</th>
<td><input type="text" name="added_date" value=""/></td>
</tr>
<tr style="display:none">
<th>Download:</th>
<td><input type="text" name="download" value=""/></td>
</tr>
<tr>
<td colspan="3" >
<center> <input type="submit" value="Get File(s)" /></center>
</td>
</tr>
</thead>
</table>
</div>
</form>
<br><br>
<center>
<table border="2">
<tr>
<th style="width: 20%">ID</th>
<th style="width: 20%">First Name</th>
<th style="width: 20%">Last Name</th>
<th style="width: 20%">File Name</th>
<th style="width: 20%">File Path</th>
<th style="width: 20%">division</th>
<th style="width: 20%">Reporting Unit</th>
<th style="width: 20%">Document No.</th>
<th style="width: 20%">Document Name</th>
<th style="width: 20%">Document Uploader</th>
<th style="width: 20%">Document Owner</th>
<th style="width: 20%">Document Type</th>
<th style="width: 20%">Document Category</th>
<th style="width: 20%">By Function</th>
<th style="width: 20%">Creator</th>
<th style="width: 20%">Modifier</th>
<th style="width: 20%">Approver</th>
<th style="width: 20%">Z ID</th>
<th style="width: 20%">Mail ID</th>
<th style="width: 20%">Added Date</th>
<th style="width: 20%">Download</th>
</tr>
<%
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
%>
<%
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/newfieldsadded","root","");
String sql = "select * from newfiles";
ps = con.prepareStatement(sql);
Statement stmt = con.createStatement();
String query = request.getParameter("search");
String data;
if(query != null){
data = "select * from newfiles where id like'%"+query+"%' or firstname like'%"+query+"%' or lastname like'%"+query+"%' or filename like'%"+query+"%' or division like'%"+query+"%' or reportingunit like'%"+query+"%' or documentnumber like'%"+query+"%' or documentname like'%"+query+"%' or documentuploader like'%"+query+"%' or documentowner like'%"+query+"%' or documenttype like'%"+query+"%' or documentcategory like'%"+query+"%' or byfunction like'%"+query+"%' or creator like'%"+query+"%' or modifier like'%"+query+"%' or approver like'%"+query+"%' or zid like'%"+query+"%' or mailid like'%"+query+"%'";
}
else{
data = "select * from newfiles order by 1 asc";
}
rs = stmt.executeQuery(data);
while(rs.next()){
%>
<tr>
<td><%=rs.getInt("id")%></td>
<td><%=rs.getString("firstname")%></td>
<td><%=rs.getString("lastname")%></td>
<td><%=rs.getString("filename")%></td>
<td><%=rs.getString("path")%></td>
<td><%=rs.getString("division")%></td>
<td><%=rs.getString("reportingunit")%></td>
<td><%=rs.getString("documentnumber")%></td>
<td><%=rs.getString("documentname")%></td>
<td><%=rs.getString("documentuploader")%></td>
<td><%=rs.getString("documentowner")%></td>
<td><%=rs.getString("documenttype")%></td>
<td><%=rs.getString("documentcategory")%></td>
<td><%=rs.getString("byfunction")%></td>
<td><%=rs.getString("creator")%></td>
<td><%=rs.getString("modifier")%></td>
<td><%=rs.getString("approver")%></td>
<td><%=rs.getString("zid")%></td>
<td><%=rs.getString("mailid")%></td>
<td><%=rs.getTimestamp("added_date")%></td>
<td><a href="DownloadServletClass?fileName=<%=rs.getString(4)%>">Download</a></td>
</tr>
<%
}
%>
</table><br>
<a href="index.jsp">Home</a>
</center>
</body>
</html>
This is my Search.jsp page
<%@ page import="java.io.*,java.util.*,java.sql.*"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
<%@ page isELIgnored="false"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<sql:setDataSource var="emp" driver="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/newfieldsadded" user="root" password="" />
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Search Page</title>
</head>
<body>
<h1>Searched Data</h1>
<form name="empForm" action="index.jsp" method="post">
<div>
<table border="2" style="width:100%">
<tr>
<th style="width:70%">Z ID</th>
<th style="width:70%">First Name</th>
<th>Last Name</th>
<th>Division</th>
<th>Reporting Unit</th>
<th>Document No.</th>
<th>Document Name</th>
<th>Document Uploader</th>
<th>Document Owner</th>
<th>Document Type</th>
<th>Document Category</th>
<th>By Function</th>
<th>Creator</th>
<th>Modifier</th>
<th>Approver</th>
<th>Mail Id</th>
<th>Added date</th>
<th>Download</th>
</tr>
<tbody>
<%
// out.println("select * from newfiles emp where emp.zid like '%"+request.getParameter("zid")+"%' and "
// + " emp.firstname like '%"+request.getParameter("firstname")+"%' and" + " emp.lastname like '%"+request.getParameter("lastname")+"%' and" + " emp.documenttype like '%"+request.getParameter("documenttype")+"%' and"
// + " emp.documentcategory like '%"+request.getParameter("documentcategory")+"%' ");
//out.println("select count(*) from newfiles");
%>
<sql:query var="empData" dataSource="${emp}">
select * from newfiles emp where emp.zid like '%
<%=request.getParameter("zid")%>%' and emp.firstname like '%
<%=request.getParameter("firstname")%>%' and emp.lastname like '%
<%=request.getParameter("lastname")%>%' and emp.division like '%
<%=request.getParameter("division")%>%' and emp.reportingunit like '%
<%=request.getParameter("reportingunit")%>%' and emp.documentnumber like '%
<%=request.getParameter("documentnumber")%>%' and emp.documentname like '%
<%=request.getParameter("documentname")%>%' and emp.documentuploader like '%
<%=request.getParameter("documentuploader")%>%' and emp.documentowner like '%
<%=request.getParameter("documentowner")%>%' and emp.documenttype like '%
<%=request.getParameter("documenttype")%>%' and emp.documentcategory like '%
<%=request.getParameter("documentcategory")%>%' and emp.byfunction like '%
<%=request.getParameter("byfunction")%>%' and emp.creator like '%
<%=request.getParameter("creator")%>%' and emp.modifier like '%
<%=request.getParameter("modifier")%>%' and emp.approver like '%
<%=request.getParameter("approver")%>%' and emp.mailid like '%
<%=request.getParameter("mailid")%>%' and emp.added_date like '%
<%=request.getParameter("added_date")%>%'
</sql:query>
<c:forEach var="row" items="${empData.rows}">
<tr>
<td>
<c:out value="${row.zid}" />
</td>
<td>
<c:out value="${row.firstname}" />
</td>
<td>
<c:out value="${row.lastname}" />
</td>
<td>
<c:out value="${row.division}" />
</td>
<td>
<c:out value="${row.reportingunit}" />
</td>
<td>
<c:out value="${row.documentnumber}" />
</td>
<td>
<c:out value="${row.documentname}" />
</td>
<td>
<c:out value="${row.documentuploader}" />
</td>
<td>
<c:out value="${row.documentowner}" />
</td>
<td>
<c:out value="${row.documenttype}" />
</td>
<td>
<c:out value="${row.documentcategory}" />
</td>
<td>
<c:out value="${row.byfunction}" />
</td>
<td>
<c:out value="${row.creator}" />
</td>
<td>
<c:out value="${row.modifier}" />
</td>
<td>
<c:out value="${row.approver}" />
</td>
<td>
<c:out value="${row.mailid}" />
</td>
<td>
<c:out value="${row.added_date}" />
</td>
<td><a href="DownloadServletClass?fileName=<%=request.getParameter(" filename ") %>">Download</a></td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</form>
<br>
<center> <a href="index.jsp">Home</a></center>
</body>
</html>
This is my DownloadServletClass.java file
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.servlets;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name = "DownloadServletClass", urlPatterns = {
"/DownloadServletClass"
})
public class DownloadServletClass extends HttpServlet {
public static int buffer_size = 1024 * 100;
public static final String upload_dir = "resources";
public static String fileName = null;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
fileName = request.getParameter("fileName");
if (fileName == null || fileName.equals("")) {
response.setContentType("text/html");
response.getWriter().println("<h3>File" + fileName + " is not present...!");
} else {
String applicationPath = getServletContext().getRealPath("");
String downloadPath = applicationPath + File.separator + upload_dir;
String filePath = downloadPath + File.separator + fileName;
System.out.println(fileName);
System.out.println(filePath);
System.out.println("fileName:" + fileName);
System.out.println("filePath:" + filePath);
File file = new File(filePath);
OutputStream outstream = null;
FileInputStream instream = null;
if (file.exists()) {
String mimeType = "application/octet-stream";
response.setContentType(mimeType);
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"", file.getName());
response.setHeader(headerKey, headerValue);
try {
outstream = response.getOutputStream();
instream = new FileInputStream(file);
byte[] buffer = new byte[buffer_size];
int bytesRead = -1;
while ((bytesRead = instream.read(buffer)) != -1) {
outstream.write(buffer, 0, bytesRead);
}
} catch (IOException ioe) {
System.out.println("Exception while printing the IO operation?=" + ioe.getMessage());
} finally {
if (instream != null) {
instream.close();
}
outstream.flush();
if (outstream != null) {
outstream.close();
}
}
} else {
response.setContentType("text/html");
response.getWriter().println("<h3>File " + fileName + " is not present ......!</h3>");
}
}
}
}
Solution
First I would not mix the database code with the .jsp code. Read about jstl and try to separate things. Second it would be nice if you post the error, if you are getting any. Where is the code from DownloadServletClass? What happens when you click on Download?
I have a small example to download a file using a servlet called testservlet. The .jsp side:
<form action="testservlet" method="GET">
<input type="text" placeholder="filename" name="filename" />
<input type="submit" value="Download file" />
</form>
And here the servlet part:
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String filename = req.getParameter("filename");
resp.setContentType("APPLICATION/OCTET-STREAM");
resp.setHeader("Content-Disposition", "attachment;filename=\""+filename+"\"");
try(FileInputStream fileInputStream = new FileInputStream("C:/Users/user/Documents/"+filename+"")){
int i;
PrintWriter out = resp.getWriter();
while((i=fileInputStream.read()) != -1) {
out.write(i);
}
}catch(Exception e) {
e.printStackTrace();
}
}
Running this I can download any file with name.extension typed in the text field from my Documents folder.
Answered By - rhenesys
Answer Checked By - Katrina (JavaFixing Volunteer)