Spring - 在jsp文件上显示图像

时间:2012-04-08 20:45:01

标签: java spring jsp spring-mvc jstl

我的模型商店图像用文件名(作为String)和数据(作为字节数组)描述。我使用Hibernate,这是我的模型:

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

但我想在网站上显示我存储的图像,如:

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

我怎么能这样做?

我应该编写为图像请求提供服务的控制器吗?

任何代码示例?


更新

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

6 个答案:

答案 0 :(得分:32)

你不能这样做。您的图片必须通过普通网址以某种方式曝光。在Spring MVC中创建一个控制器,在特定的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();
}

现在在JSP页面中使用。这就是HTTP / HTML的工作方式:

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

在3.1之前的Spring MVC中,您可能需要在控制器端进行更多编码。但原则是一样的。

答案 1 :(得分:17)

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

现在在JSP页面中使用它作为

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

答案 2 :(得分:5)

您可能需要查看此post。我有类似你的问题,解决方案是将字节数组转换为字符串并在img标记中设置,如下所示,

 <img src="data:image/jpg;base64,<c:out value='${bean.imageByteArrayString}'/>" />

答案 3 :(得分:4)

我正在寻找正确答案几天,所以我会为我写好书:

我的图片已保存在数据库中:

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

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

// setters getters etc
}

现在在我的班级中,例如ShowPicture,我必须阅读它:

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

然后是我的jsp页面:

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

简单就是这样! :)

答案 4 :(得分: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();

答案 5 :(得分:0)

也许已经很晚了,但在这里我留下了一些能为我服务的东西,也许有人可以提供帮助。

我也使用Spring MVC和Hibernate

模型(实体类)中创建一个String类型的变量,将类型byte转换为String with Base64。

我这样做了一张我拥有各自国旗的国家的表格,我想要的是在所有国家的一张桌子中列出,并在旁边列出它的旗帜。

模型(实体)

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

}

存储库 - Implements是一个接口 - AbstractDao是一个抽象类     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;
}

}

服务 - 实现是一个界面

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

<强>控制器

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
}

}

查看 - countries / 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>