I try to make servlet which take file from my DB(PostgreSQL) and send it to cliet. I says:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
try
{
Connection ce = ConnectionManager.createConnection();
} catch (ClassNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
Statement sta = null;
sta = ce.createStatement();
String fileName="";
byte[] file=null;
int bufferSize = 8192;
String sql=("SELECT files,filename FROM filestock WHERE num =(SELECT filestock_id FROM parcels_temp WHERE num="+num+")");
ResultSet rs=sta.executeQuery(sql);
while(rs.next()){
file = rs.getBytes("files");
fileName=rs.getString("filename");
}
}
So i just create connection and eclipse says me that i gonna surround each line in Try/catch. Whats wrong? Its bad idea usind JDBC in servlet and i have to make any deals with data base in another class?
In this case how to send file to servlet? I gonna send it as File or something else i want use this for send file to cliet from servlet.
Doing everything in the servlet is not a good programming practice. Try to use a 3 tier architecture..
Create another DAO(DatabaseAccessObject). Its nothing but another class which does only database operations. All these code which you have written in this servlet will go to a function in that class.
Next step is to create a Bean in which you will store the results.
Now return the bean from The DAO to this servlet.
Now the question comes? What are you going to do with the file and fileName?
If you want to download the file, just push it into the output stream. Make sure that you set the contentType.
EDIT:
Sample file download