/* * ShowPhotoServlet.java * * Created on July 12, 2006, 2:35 PM */ import java.io.*; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.naming.NamingException; import javax.servlet.*; import javax.servlet.http.*; /** * * @author jungi * @version */ public class ShowPhotoServlet extends HttpServlet { /** Processes requests for both HTTP GET and POST methods. * @param request servlet request * @param response servlet response */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { int id = Integer.parseInt(request.getParameter("id")); byte[] img = readPhoto(id); // write output ServletOutputStream out = response.getOutputStream(); response.setContentType("image/png"); out.write(img); out.close(); } catch (NumberFormatException ex) { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); out.println(""); out.println(""); out.println("Servlet ShowPhotoServlet"); out.println(""); out.println(""); out.println("use id parameter that could be converted in int"); out.println(""); out.println(""); out.close(); } catch (SQLException sqlE) { throw new ServletException(sqlE.getMessage()); } catch (NamingException ne) { throw new ServletException(ne.getMessage()); } } // /** Handles the HTTP GET method. * @param request servlet request * @param response servlet response */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** Handles the HTTP POST method. * @param request servlet request * @param response servlet response */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** Returns a short description of the servlet. */ public String getServletInfo() { return "Short description"; } // private javax.sql.DataSource getPhotoAlbumDB() throws javax.naming.NamingException { javax.naming.Context c = new javax.naming.InitialContext(); return (javax.sql.DataSource) c.lookup("java:comp/env/jdbc/PhotoAlbumDB"); } private byte[] readPhoto(int id) throws SQLException, NamingException{ byte[] img = null; String sql = "SELECT img FROM photo WHERE id = ?"; Connection conn = getPhotoAlbumDB().getConnection(); PreparedStatement prepStmt = conn.prepareStatement(sql); prepStmt.setInt(1, id); ResultSet rs = prepStmt.executeQuery(); if (rs.next()) { img = rs.getBytes(1); } conn.close(); return img; } }