Hello!
I have a problem reading/presenting HTML files from a database. I have tried it in many different ways but I can't get it to work. Here is my latest try:
import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ImageServlet extends HttpServlet
{
private Connection conn = null;
private
String database = "xxx";
private String path = "xxx";
private String user = "xxx";
private String passWd = "xxx";
private String dbDriver = "org.gjt.mm.mysql.Driver";
private String dbUrl = "jdbc:mysql://xxx";
public void init() {
try {
Class.forName(dbDriver);
conn = DriverManager.getConnection(dbUrl, user, passWd);
}catch(Exception ex) {
System.out.println("Database connection could not be established!");
System.out.println("reason:"+ex.getMessage());
//throw new ServletException("Database connection could not be established!");
}
}
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException
{
processRequest(req, res);
}
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException
{
processRequest(req, res);
}
private void processRequest(HttpServletRequest req, HttpServletResponse res)
throws ServletException
{
//dbConnect();
System.out.println("Processing request");
// get id from request
String tmp = req.getParameter("id");
int id = Integer.parseInt(tmp);
System.out.println("ID:"+id);
// get the blob from database
// FIXME: name of the table ???
String SQL = "select materiaalitiedosto, mtiedostonimi from materiaali "
+ "where id = ?";
try {
PreparedStatement ps = conn.prepareStatement(SQL);
ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
Blob blob = null;
String filename = "";
// get the data from query
while(rs.next()) {
blob = rs.getBlob(1);
filename = rs.getString(2);
}
// get the actual data as bytes from blob
byte [] data = blob.getBytes(1l,(int) blob.length());
// send the data to client
sendData(data, res);
}catch(SQLException ex) {
System.out.println("Database select operation failed:"+ex.getMessage());
throw new ServletException("Database select operation failed");
}
}
private void sendData(byte[] data, HttpServletResponse res) {
// set responses buffer size to 1kB
// so clients can handle the files more easily
res.setBufferSize(1024);
try {
// get the binary output stream
BufferedOutputStream out = new
BufferedOutputStream(res.getOutputStream());
// write the data
out.write(data, 0, data.length);
}
catch(IOException ex) {
System.out.println("Data send failed:"+ex.getMessage());
}
}
}