Hibernate - 如何从数据库中检索图像?

时间:2013-06-29 21:38:07

标签: hibernate

我设法将图像存储在数据库中,但现在我想再次检索/显示图像。我只是不知道如何。基本上我的问题是,如果我在ImageDao中缺少任何进一步的方法或者jsp中的配置应该如何。

有我的图像类:

package de.hdu.pms.model;

import java.sql.Blob;
import java.util.Date;
import java.util.Set;

import javax.persistence.*;


@Entity
@Table(name="tbl_image")
public class Image {
     @Id
     @GeneratedValue
     @Column(name="image_id")
      private Integer id;


        private String name;


        private String description;


        private String filename;

        @Column(name="content", columnDefinition="mediumblob")
        @Lob
        private Blob content;


        private String contentType;

        private Date created;

        public Integer getId() {
            return id;
        }

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

        public String getName() {
            return name;
        }

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

        public String getDescription() {
            return description;
        }

        public void setDescription(String description) {
            this.description = description;
        }

        public String getFilename() {
            return filename;
        }

        public void setFilename(String filename) {
            this.filename = filename;
        }

        public Blob getContent() {
            return content;
        }

        public void setContent(Blob content) {
            this.content = content;
        }

        public String getContentType() {
            return contentType;
        }

        public void setContentType(String contentType) {
            this.contentType = contentType;
        }

        public Date getCreated() {
            return created;
        }

        public void setCreated(Date created) {
            this.created = created;
        }



}

ImageDao

package de.hdu.pms.dao;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;



import de.hdu.pms.model.Image;


public class ImageDao extends HibernateDaoSupport {


        public void save(Image image) {
            HibernateTemplate template = getHibernateTemplate();
            template.saveOrUpdate(image);
        }

        @SuppressWarnings("unchecked")
        public List<Image> list() {
           HibernateTemplate template = getHibernateTemplate();
            //evtl ersetzen durch hibernate template
           @SuppressWarnings("rawtypes")
           List images=template.loadAll(Image.class);
            return images;
        }

        public Image get(Integer id) {
            HibernateTemplate template = getHibernateTemplate();
            return template.get(Image.class, id);
        }



     @Transactional
     //hibernate
        public void remove(Integer id) {
          HibernateTemplate template = getHibernateTemplate();

            Image image = template.get(Image.class, id);
             template.delete(image);
        }

}

ImageController:

package de.hdu.pms.ctrl;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.SQLException;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.hibernate.Hibernate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;



import de.hdu.pms.dao.CocktailDao;
import de.hdu.pms.dao.ImageDao;
import de.hdu.pms.model.Image;

@Controller
public class ImageController {

    @Autowired
    private ImageDao imageDao;

    public ImageDao getImageDao(){
        return imageDao;
    }

    public void setImageDao(ImageDao imageDao){
        this.imageDao = imageDao;
    }
    //aus dem Tutorial

     @RequestMapping("/EditImage.html")
     public String index(Map<String, Object> map) {
            try {
                map.put("image", new Image());
                map.put("imageList", imageDao.list());
            }catch(Exception e) {
                e.printStackTrace();
            }

            return "edit-image";
        }

        //aus dem Tutorial




     @RequestMapping(value = "/SaveImage.html", method = RequestMethod.POST)
        public String save(
                @ModelAttribute("image") Image image,
                @RequestParam("file") MultipartFile file) {


            System.out.println("Name:" + image.getName());
            System.out.println("Desc:" + image.getDescription());
            System.out.println("File:" + file.getName());
            System.out.println("ContentType:" + file.getContentType());

            try {
                Blob blob = Hibernate.createBlob(file.getInputStream());

                image.setFilename(file.getOriginalFilename());
                image.setContent(blob);
                image.setContentType(file.getContentType());
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                imageDao.save(image);
            } catch(Exception e) {
                e.printStackTrace();
            }

            return "redirect:/AlleImages.html";
        }

        @RequestMapping("/download/{imageId}")
        public String download(@PathVariable("imageId")
                Integer imageId, HttpServletResponse response) {

            Image img = imageDao.get(imageId);
            try {
                response.setHeader("Content-Disposition", "inline;filename=\"" +img.getFilename()+ "\"");
                OutputStream out = response.getOutputStream();
                response.setContentType(img.getContentType());
                IOUtils.copy(img.getContent().getBinaryStream(), out);
                out.flush();
                out.close();

            } catch (IOException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            }


            return null;
        }

        @RequestMapping(value="/AlleImages.html", method=RequestMethod.GET)
        public ModelAndView list(){
            ModelAndView mv = new ModelAndView();
            mv.addObject("title", "Images");
            mv.addObject("message", "Alle gespeicherten Images");
            mv.addObject("image", imageDao.list());
            // für die jsp bedingung 
            mv.addObject("edit",true);
            mv.setViewName("list-image");
            return mv;
        }


}

最后是我想要“访问”图像的jsp的代码片段 - 但我失败了:

                                                    <h3>Image List</h3>
                                                    <c:if  test="${!empty imageList}">
                                                    <table class="data">
                                                    <tr>
                                                        <th>Name</th>
                                                        <th>Description</th>
                                                        <th>&nbsp;</th>
                                                    </tr>
                                                    <c:forEach items="${imageList}" var="image">
                                                        <tr>
                                                            <td width="100px">${image.name}</td>
                                                            <td width="250px">${image.description}</td>
                                                            <td width="250px">${image.content}</td>


                                                        </tr>
                                                    </c:forEach>

如果有人能帮助我,我真的很感激。感谢

1 个答案:

答案 0 :(得分:0)

问题在于您对HTTP和HTML如何工作的理解。当网页包含图像时,HTML不包含图像的内容。它包含的所有内容都是img标记,其src属性包含此图像的网址:

<img src="/the/path/of/the/image.jpg"/>

浏览器发送第一个获取HTML页面的请求。然后它解析HTML,查看img标记,并向图像的URL发送第二个请求以获取其内容(字节)并显示它。

您的代码尝试直接在页面中生成包含blob的HTML页面(实际上是在blob上调用toString()的结果):

<td width="250px">${image.content}</td>

这是不正确的。

您需要生成的是一个图像标记,其src属性包含将从数据库中获取图像字节并将其发送到浏览器的操作的URL,即指向下载操作的img标记:

<td width="250px"><img src="<c:url value='/download/${image.id}'/>"/></td>