2012-04-08 72 views
14

hình ảnh cửa hàng mô hình của tôi được mô tả bằng tên tệp (dưới dạng Chuỗi) và dữ liệu (dưới dạng mảng byte). Tôi sử dụng Hibernate và đây là mô hình của tôi:Mùa xuân - hình ảnh hiển thị trên tệp jsp

@Entity 
public class Image { 

    private Long id; 
    private String name; 
    private byte[] data; 

    @Id 
    @GeneratedValue 
    @Column(name = "IMAGE_ID") 
    public Long getId() { 
     return id; 
    } 

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

    @Column(nullable = false, length = 100) 
    public String getName() { 
     return name; 
    } 

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

    @Lob 
    @Column(nullable = false) 
    public byte[] getData() { 
     return data; 
    } 

    public void setData(byte[] data) { 
     this.data = data; 
    } 
} 

Nhưng tôi muốn để hiển thị hình ảnh được lưu trữ của tôi, trên trang web như:

<img src="${image.data}" alt="car_image"/> 

Làm thế nào tôi có thể làm điều đó?

Tôi có nên viết bộ điều khiển phục vụ các yêu cầu cho hình ảnh không?

Bất kỳ ví dụ mã nào?


CẬP NHẬT

<bean id="viewResolver" 
    class="org.springframework.web.servlet.view.UrlBasedViewResolver"> 
    <property name="viewClass" 
     value="org.springframework.web.servlet.view.tiles2.TilesView" /> 
</bean> 

<bean id="tilesConfigurer" 
    class="org.springframework.web.servlet.view.tiles2.TilesConfigurer"> 
    <property name="definitions"> 
     <list> 
      <value>/WEB-INF/configs/tiles.xml</value> 
     </list> 
    </property> 
</bean> 

Trả lời

29

Bạn không thể làm điều đó như thế này. Hình ảnh của bạn phải được hiển thị bằng cách nào đó thông qua URL thông thường. Trong Spring MVC, tạo bộ điều khiển trả về hình ảnh (dữ liệu thô) theo URL cụ thể:

@RequestMapping(value = "/imageController/{imageId}") 
@ResponseBody 
public byte[] helloWorld(@PathVariable long imageId) { 
    Image image = //obtain Image instance by id somehow from DAO/Hibernate 
    return image.getData(); 
} 

Bây giờ sử dụng trong trang JSP của bạn. Đây là cách hoạt động của HTTP/HTML:

<img src="/yourApp/imageController/42.png" alt="car_image"/> 

Trong Spring MVC trước 3.1 bạn có thể cần mã hóa nhiều hơn một chút về phía bộ điều khiển. Nhưng nguyên tắc thì giống nhau.

+0

Tôi đã thử giải pháp này nhưng tôi gặp phải lỗi 404. Có phải vì cấu hình chế độ xem của tôi, sử dụng Gạch không? Tôi đã đặt cấu hình trong bản cập nhật – bontade

+0

Vì vậy, cuối cùng, lỗi 404 được gây ra bởi bản đồ servlet, phục vụ các yêu cầu cho regex * .htm. Giải pháp của bạn hoạt động! Cảm ơn! Dzięki: D – bontade

+0

Ví dụ hoạt động đầy đủ "Spring MVC + Hibernate + Maven": https://sites.google.com/site/adrienitnotes/java/web-apps---spring-mvc-hibernate/spring-form-image -upload-display-from-database-hibernate-simple-mapping –

0
byte[] img = yourImgEntity.getData(); 
response.setContentType("image/*"); 
response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache"); 
//spring-core's FileCopyUtils 
FileCopyUtils.copy(img, response.getOutputStream()); 

// or just use codes below instead of FileCopyUtils 
//response.getOutputStream().write(img); 
//response.getOutputStream().flush(); 
//response.getOutputStream().close(); 
4

Bạn có thể cần phải kiểm tra điều này post. Tôi có một vấn đề tương tự như bạn và giải pháp là để chuyển đổi mảng byte thành chuỗi và thiết lập trong thẻ img như dưới đây,

<img src="data:image/jpg;base64,<c:out value='${bean.imageByteArrayString}'/>" /> 
15
File file = new File("home/user/test.jpg"); 
FileInputStream fis=new FileInputStream(file); 
ByteArrayOutputStream bos=new ByteArrayOutputStream(); 
int b; 
byte[] buffer = new byte[1024]; 
while((b=fis.read(buffer))!=-1){ 
    bos.write(buffer,0,b); 
} 
byte[] fileBytes=bos.toByteArray(); 
fis.close(); 
bos.close(); 


byte[] encoded=Base64.encodeBase64(fileBytes); 
String encodedString = new String(encoded); 

ModelMap map = new ModelMap(); 
map.put("image", encodedString); 

Bây giờ sử dụng nó trong trang JSP của bạn sau khi

<img src="data:image/jpeg;base64,${image}" alt="..." width="200" height="200">` 
+0

Phương thức encodeBase64 (byte []) không xác định cho kiểu Base64 – Siddharth

4

tôi đang tìm kiếm fo câu trả lời đúng cho một vài ngày, vì vậy tôi sẽ viết một trong những tốt cho tôi:

hình ảnh của tôi đã được lưu trong cơ sở dữ liệu:

01.
@Entity 
@Table(name="PRODUCT") 
public class Product { 

@Lob 
@Column(name="IMG") 
private byte[] img; 

// setters getters etc 
} 

Bây giờ trong lớp học của tôi ví dụ tôi ShowPicture phải đọc nó:

String encodedImage = Base64.encode(product.getImg()); 
//setters and getters encodedImage 

Sau đó trang jsp của tôi:

<img src='data:image/jpg;base64,<s:property value='encodedImage'/>' alt="my image" /> 

đơn giản như thế! :)

0

Có thể đã muộn, nhưng ở đây tôi để lại thứ gì đó phục vụ tôi và có thể ai đó có thể giúp đỡ.

Tôi cũng đang sử dụng Spring MVC và Hibernate

Trong mô hình (lớp thực thể) tạo một biến kiểu String để làm việc chuyển đổi kiểu byte để String với Base64.

Tôi đã làm điều này cho một bảng các quốc gia mà tôi có với lá cờ tương ứng của nó, và những gì tôi muốn là liệt kê trong một bảng trong quan điểm tất cả các quốc gia và bên cạnh lá cờ của nó.

Model (Entity)

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64; 
import javax.persistence.Column; 
import javax.persistence.Entity; 
import javax.persistence.GeneratedValue; 
import javax.persistence.GenerationType; 
import javax.persistence.Id; 
import javax.persistence.Table; 
import javax.persistence.Transient; 

@Entity 
@Table(name = "country") 
public class Country implements java.io.Serializable { 

private int id; 
private String name; 
private byte[] flag; 
private String base64; //Variable to store the conversion of a data byte type to String 

@Transient //Annotation so it does not persist in the database 
public String getBase64() { 
    //Convert the data type byte to String, store it in the variable and return it 
    return this.base64 = Base64.encode(this.flag); 
} 

public void setBase64(String base64) { 
    this.base64 = base64; 
} 

public Country() { 
} 

public Country(int id, String name, byte[] flag, String base64) { 
    this.id = id; 
    this.name = name; 
    this.flag = this.flag 
    this.base64 = this.base64; 
} 

@Id 
@GeneratedValue(strategy = GenerationType.IDENTITY) 
@Column(name = "id", unique = true, nullable = false) 
public int getId() { 
    return this.id; 
} 

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

@Column(name = "name") 
public String getName() { 
    return this.name; 
} 

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

@Column(name = "flag") 
public byte[] getFlag() { 
    return this.flag; 
} 

public void setFlag(byte[] flag) { 
    this.flag = flag; 
} 

} 

Repository - Dụng cụ là một giao diện - AbstractDao là một lớp trừu tượng nhập khẩu org.springframework.stereotype.Repository; nhập application.model.Country; nhập application.repository.dao.AbstractDao; nhập application.repository.dao.CountryDao; nhập org.hibernate.Criteria;

@Repository("countryDao") 
public class CountryDaoImpl extends AbstractDao<Integer, Country> implements CountryDao { 

@Override 
@SuppressWarnings("unchecked") 
public List<Country> listCountries() { 
    Criteria criteria = createEntityCriteria(); //Country.class 
    criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); 
    List<Country> listCountries = criteria.list(); 
    return listCountries; 
} 

} 

Dịch vụ - dụng cụ là một giao diện

import application.model.Country; 
import application.repository.dao.CountryDao; 
import application.service.dao.CountryService; 
import java.util.List; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.stereotype.Service; 
import org.springframework.transaction.annotation.Transactional; 

@Service("countryService") 
public class CountryServiceImpl implements CountryService { 

@Autowired 
private CountryDao countryDao; 

@Override 
@Transactional(readOnly = true) 
public List<Country> listCountries() { 
    return countryDao.listCountries(); 
} 
} 

khiển

import application.model.Country; 
import application.service.dao.CountryService; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.stereotype.Controller; 
import org.springframework.ui.Model; 
import org.springframework.web.bind.annotation.RequestMapping; 

@Controller 
@RequestMapping(value = "/countries") 
public class CountryController { 

@Autowired 
private CountryService countryService; 

@RequestMapping(value = "/list", method = RequestMethod.GET) 
public String ListCountries(Model model) { 
    model.addAttribute("listcont", countryService.listCountry()); 
    return "countries/countries"; //view 
} 

} 

View - quốc gia/countries.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%> 
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 
<!DOCTYPE html> 
<html> 
    <head> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
    </head> 
    <body> 
    <h3>List Countries</h3> 
    <table> 
     <thead> 
     <tr> 
      <th>Name</th> 
      <th>Flag</th> 
     </tr> 
     </thead> 
     <tbody> 
     <c:forEach items="${listcont}" var="country"> 
     <tr> 
      <td>${country.name}</td> 
      <td><img src="data:image/png;base64,${country.base64}" /></ 
     </tr> 
     </c:forEach> 
     </tbody> 
    </table> 
    </body> 
</html> 
Các vấn đề liên quan