Java Servlet for displaying an image Atom Feed 0

In Brief A rather old and possibly baddly implemented servlet for fetching an image out of a database and sending it to the client. You will need to put some code for initializing the database connection in the init method. And obviously create the table:... more
# 's
 1import javax.servlet.ServletConfig;
2import javax.servlet.ServletException;
3import javax.servlet.ServletOutputStream;
4import javax.servlet.http.HttpServlet;
5import javax.servlet.http.HttpServletRequest;
6import javax.servlet.http.HttpServletResponse;
7import java.io.PrintWriter;
8import java.sql.Connection;
9import java.sql.ResultSet;
10import java.sql.Statement;
11
12
13/**
14 * @author Stou
15 * Date: July 27, 2003
16 * Time: 4:18 PM
17 */
18public class ViewPix extends HttpServlet
19{
20 Connection m_dbCon = null;
21
22 public void init(ServletConfig config) throws ServletException
23 {
24 super.init(config);
25
26 m_dbCon = // TODO: Init database connection here... I've left invalid syntax so you remember ;-)
27 }
28
29 //Process the HTTP Get request
30 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException
31 {
32 try
33 {
34
35 Statement statement = m_dbCon.createStatement();
36 PrintWriter out = new PrintWriter(response.getOutputStream());
37
38 if(request.getParameter("pix_id") != null)
39 {
40 // WARNING: This statement will allow SQL injection.
41 ResultSet rs = statement.executeQuery("select mime, image from pix where id = " + request.getParameter("pix_id"));
42
43 if((rs != null) && (rs.next()))
44 {
45 ServletOutputStream binout = response.getOutputStream();
46 response.setContentType(rs.getString("mime"));
47 byte[] imgBytes = rs.getBytes("image");
48 binout.write(imgBytes);
49 }
50 else
51 {
52 response.setContentType("text/html");
53 out.println("Nothing to display");
54 }
55 }
56 else
57 {
58 ResultSet rs = statement.executeQuery("select id, mime from pix");
59 while(rs.next())
60 {
61 out.println("<p><a href=\"ViewPix?pix_id=" + rs.getString(1) +"\">Picture with ID of " + rs.getString(1) + " and type of " + rs.getString(2) + "</a></p>");
62 }
63
64 out.close();
65 rs.close();
66 }
67 }
68 catch(Exception e)
69 {
70 throw new ServletException(e.getMessage());
71 }
72 }
73
74}

A rather old and possibly baddly implemented servlet for fetching an image out of a database and sending it to the client. You will need to put some code for initializing the database connection in the init method. And obviously create the table:

The postgresql table definition for storing the images is as follows:

# 's
1CREATE TABLE pix (
2 id SERIAL NOT NULL,
3 mime varchar(250) NOT NULL,
4 image bytea NOT NULL,
5 CONSTRAINT pix_id_PK primary key (id)
6);