Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package servlet_examples;
- import java.io.*;
- import java.sql.*;
- import javax.naming.Context;
- import javax.naming.NamingException;
- import javax.servlet.*;
- import javax.servlet.http.*;
- import javax.sql.DataSource;
- import javax.servlet.annotation.*;
- @WebServlet("/DBGifReader3")
- public class DBGifReader3 extends HttpServlet {
- Connection con;
- public void doGet(HttpServletRequest req, HttpServletResponse res)
- throws ServletException, IOException {
- res.setContentType("image/gif");
- ServletOutputStream out = res.getOutputStream();
- String empno = req.getParameter("empno"); // server.xml有設定喔
- //empno = new String(empno.getBytes("ISO-8859-1"),"UTF-8"); // server.xml有設定喔
- System.out.println("empno: " + empno);
- try {
- Statement stmt = con.createStatement();
- ResultSet rs = stmt.executeQuery(
- "SELECT picture FROM emp_photo WHERE empno = '" + empno + "'");
- if (rs.next()) {
- BufferedInputStream in = new BufferedInputStream(rs.getBinaryStream("picture"));
- byte[] buf = new byte[4 * 1024]; // 4K buffer
- int len;
- while ((len = in.read(buf)) != -1) {
- out.write(buf, 0, len);
- }
- in.close();
- } else {
- res.sendError(HttpServletResponse.SC_NOT_FOUND);
- }
- rs.close();
- stmt.close();
- } catch (Exception e) {
- System.out.println(e);
- }
- }
- public void init() throws ServletException {
- try {
- Context ctx = new javax.naming.InitialContext();
- DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/TestDB");
- con = ds.getConnection();
- } catch (NamingException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- public void destroy() {
- try {
- if (con != null) con.close();
- } catch (SQLException e) {
- System.out.println(e);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement