Advertisement
uopspop

Untitled

Oct 6th, 2016
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.86 KB | None | 0 0
  1. package servlet_examples;
  2.  
  3. import java.io.*;
  4. import java.sql.*;
  5.  
  6. import javax.naming.Context;
  7. import javax.naming.NamingException;
  8. import javax.servlet.*;
  9. import javax.servlet.http.*;
  10. import javax.sql.DataSource;
  11. import javax.servlet.annotation.*;
  12.  
  13. @WebServlet("/DBGifReader3")
  14. public class DBGifReader3 extends HttpServlet {
  15.  
  16.     Connection con;
  17.  
  18.     public void doGet(HttpServletRequest req, HttpServletResponse res)
  19.             throws ServletException, IOException {
  20.  
  21.         res.setContentType("image/gif");
  22.         ServletOutputStream out = res.getOutputStream();
  23.        
  24.         String empno = req.getParameter("empno"); // decoded via "USO-8859-1"
  25.         empno = new String(empno.getBytes("ISO-8859-1"),"UTF-8");
  26.         System.out.println("empno: " + empno);
  27.  
  28.         try {
  29.             Statement stmt = con.createStatement();
  30.             ResultSet rs = stmt.executeQuery(
  31.                 "SELECT picture FROM emp_photo WHERE empno = '" + empno + "'");
  32.  
  33.             if (rs.next()) {
  34.                 BufferedInputStream in = new BufferedInputStream(rs.getBinaryStream("picture"));
  35.                 byte[] buf = new byte[4 * 1024]; // 4K buffer
  36.                 int len;
  37.                 while ((len = in.read(buf)) != -1) {
  38.                     out.write(buf, 0, len);
  39.                 }
  40.                 in.close();
  41.             } else {
  42.                 res.sendError(HttpServletResponse.SC_NOT_FOUND);
  43.             }
  44.             rs.close();
  45.             stmt.close();
  46.         } catch (Exception e) {
  47.             System.out.println(e);
  48.         }
  49.     }
  50.  
  51.     public void init() throws ServletException {
  52.         try {
  53.             Context ctx = new javax.naming.InitialContext();
  54.             DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/TestDB");
  55.             con = ds.getConnection();
  56.         } catch (NamingException e) {
  57.             // TODO Auto-generated catch block
  58.             e.printStackTrace();
  59.         } catch (SQLException e) {
  60.             // TODO Auto-generated catch block
  61.             e.printStackTrace();
  62.         }
  63.     }
  64.  
  65.     public void destroy() {
  66.         try {
  67.             if (con != null) con.close();
  68.         } catch (SQLException e) {
  69.             System.out.println(e);
  70.         }
  71.     }
  72.  
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement