2012-04-08 15 views
14

l'immagine del mio modello di archivio descritta con nome file (come stringa) e dati (come matrice di byte). Io uso Hibernate ed ecco il mio modello:Spring: visualizza l'immagine sul file 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; 
    } 
} 

Ma io voglio mostrare il mio un'immagine memorizzata, sul sito web come:

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

Come potrei farlo?

Devo scrivere controller che serve richieste di immagini?

Qualche esempio di codice?


UPDATE

<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> 

risposta

29

Non si può fare in questo modo. La tua immagine deve essere esposta in qualche modo tramite un normale URL. In Spring MVC creare un controller che restituisce un'immagine (dati grezzi) in particolare URL:

@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(); 
} 

Ora UseIt nella tua pagina JSP. Questo è come HTTP/HTML lavoro:

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

In Spring MVC prima di 3.1 potrebbe essere necessario fare un po 'di più la codifica su lato controllore. Ma il principio è lo stesso.

+0

Ho provato questa soluzione, ma sto ricevendo errore 404. È a causa della mia configurazione di visualizzazione, che uso le piastrelle? Ho messo le configurazioni in aggiornamento – bontade

+0

Quindi, alla fine, l'errore 404 è stato causato dalla mappatura servlet, che serviva le richieste di regex * .htm. La tua soluzione funziona! Grazie! Dzięki: D – bontade

+0

Un esempio pienamente funzionante "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

Potrebbe essere necessario controllare questo post. Ho un problema simile come voi e la soluzione è quella di convertire la matrice di byte in stringa e impostare nel tag img come qui di seguito,

<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); 

Ora lo uso nella tua pagina JSP segue come

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

Il metodo encodeBase64 (byte []) non è definito per il tipo Base64 – Siddharth

4

cercavo fo la risposta giusta per un paio di giorni, così io scriverò quello buono per me:

la mia immagine è già salvato nel database:

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

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

// setters getters etc 
} 

Ora nella mia classe, per esempio ShowPicture devo leggerlo:

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

Poi la mia pagina jsp:

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

semplice! :)

0

Forse è tardi, ma qui lascio qualcosa che mi è servito e forse qualcuno può aiutare.

che sto utilizzando anche Spring MVC e Hibernate

Nel modello (classe di entità) creare una variabile di tipo stringa per eseguire la conversione di tipo byte Stringa con Base64.

Ho fatto questo per una tabella di paesi che ho con la rispettiva bandiera, e quello che volevo era elencare in una tabella nella vista tutti i paesi e al lato la sua bandiera.

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 - Utensili è un'interfaccia - AbstractDao è una classe astratta import org.springframework.stereotype.Repository; import application.model.Country; import application.repository.dao.AbstractDao; import application.repository.dao.CountryDao; import 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; 
} 

} 

servizio - attrezzi è un'interfaccia

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(); 
} 
} 

controller

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 - Paesi/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> 
Problemi correlati