codestory

Bild von Datenbank mit Java Servlet anzeigen

  1. Database
  2. Das Foto von Datenbank mit Servlet anzeigen

1. Database

** ORACLE **
create table PERSON
(
 ID              NUMBER(19) not null,
 NAME            VARCHAR2(50) not null,
 IMAGE_DATA      BLOB not null,
 IMAGE_FILE_NAME VARCHAR2(30) not null
) ;

alter table PERSON
 add constraint PERSON_PK primary key (ID);
** SQL SERVER **
create table PERSON
(
ID              NUMERIC(19,0) not null,
NAME            VARCHAR(50) not null,
IMAGE_DATA      IMAGE not null,
IMAGE_FILE_NAME VARCHAR(30) not null
) ;

alter table PERSON
add constraint PERSON_PK primary key (ID);
** MYSQL **
create table PERSON
(
ID              BIGINT not null,
NAME            VARCHAR(50) not null,
IMAGE_DATA      LONGBLOB not null,
IMAGE_FILE_NAME VARCHAR(30) not null
) ;

alter table PERSON
add constraint PERSON_PK primary key (ID);

2. Das Foto von Datenbank mit Servlet anzeigen

Im Dokument gebe ich Ihnen die Hinweise bei der Anzeige von Image aus Database durch die Benutzung vom Servlet. Normalerweise wird die Image Daten in Database in einer DatenSpalte BLOB archiviert. Sie sollen abfragen, die Daten in Format von byte[] abzurufen und in response aufzuschreiben. Oben stelle ich eine kleine Datenbase und sie wird für die Lektion benutzt.
Um eine Image anzuzeigen, brauchen Sie einen Servlet und der Pfad kann ähnlich wie folgend sein
  • http://localhost:8080/ServletExamples/image?id=2
  • http://localhost:8080/ServletExamples/image?id=3
Stellen Sie sicher, dass Sie JDBC und Servlet beherrschen. Wenn nicht, können Sie studieren bei ...
JDBC:
Servlet:
Project:
Person.java
package org.o7planning.servletexamples.model;

public class Person {

    private Long id;
    private String name;
    private byte[] imageData;
    private String imageFileName;

    public Person() {

    }

    public Person(Long id, String name, String imageFileName, byte[] imageData) {
        this.id = id;
        this.name = name;
        this.imageData = imageData;
        this.imageFileName = imageFileName;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public byte[] getImageData() {
        return imageData;
    }

    public void setImageData(byte[] imageData) {
        this.imageData = imageData;
    }

    public String getImageFileName() {
        return imageFileName;
    }

    public void setImageFileName(String imageFileName) {
        this.imageFileName = imageFileName;
    }

}
DisplayImageServlet.java
package org.o7planning.servletexamples;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.o7planning.servletexamples.model.Person;
import org.o7planning.tutorial.jdbc.ConnectionUtils;

// /image?id=123
@WebServlet(urlPatterns = { "/image" })
public class DisplayImageServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;

  public DisplayImageServlet() {
      super();
  }

  private Person getImageInTable(Connection conn, Long id) throws SQLException {
      String sql = "Select p.Id,p.Name,p.Image_Data,p.Image_File_Name "//
              + " from Person p where p.id = ?";
      PreparedStatement pstm = conn.prepareStatement(sql);
      pstm.setLong(1, id);
      ResultSet rs = pstm.executeQuery();
      if (rs.next()) {
          String name = rs.getString("Name");
          byte[] imageData = rs.getBytes("Image_Data");
          String imageFileName = rs.getString("Image_File_Name");
          return new Person(id, name, imageFileName, imageData);
      }
      return null;
  }

  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
      Connection conn = null;
      try {
          // Get Database Connection.
         // (See more in JDBC Tutorial)
          conn = ConnectionUtils.getMyConnection();
          Long id = null;
          try {
              id = Long.parseLong(request.getParameter("id"));
          } catch (Exception e) {

          }
          Person person = getImageInTable(conn, id);

          if (person == null) {
              // No record found, redirect to default image.
              response.sendRedirect(request.getContextPath() + "/images/noimage.jpg");
              return;
          }
       
          // trump.jpg, putin.png
          String imageFileName = person.getImageFileName();
          System.out.println("File Name: "+ imageFileName);
       
          // image/jpg
          // image/png
          String contentType = this.getServletContext().getMimeType(imageFileName);
          System.out.println("Content Type: "+ contentType);
       
          response.setHeader("Content-Type", contentType);
       
          response.setHeader("Content-Length", String.valueOf(person.getImageData().length));
       
          response.setHeader("Content-Disposition", "inline; filename=\"" + person.getImageFileName() + "\"");

          // Write image data to Response.
          response.getOutputStream().write(person.getImageData());

      } catch (Exception e) {
          throw new ServletException(e);
      }
  }

  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
      doGet(request, response);
  }

}
Führen Sie die Appliakation durch