Spring - 在jsp文件上显示图像 [英] Spring - display image on jsp file
问题描述
我的模型存储图像用文件名(作为字符串)和数据(作为字节数组)描述.我使用 Hibernate,这是我的模型:
my model store image described with file name (as String) and data (as byte array). I use Hibernate and here's my model:
@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;
}
}
但我想在网站上显示我存储的图像:
But I want to display my stored image, on web site like:
<img src="${image.data}" alt="car_image"/>
我怎么能这样做?
我应该编写处理图像请求的控制器吗?
Should I write controller that serve requests for images?
任何代码示例?
更新
<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>
推荐答案
你不能这样做.您的图像必须通过普通 URL 以某种方式公开.在 Spring MVC 中创建一个控制器,在特定 URL 下返回图像(原始数据):
You cannot do it like this. Your image must be exposed somehow via normal URL. In Spring MVC create a controller that returns an image (raw data) under particular 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 的工作方式:
Now useit in your JSP page. This is how HTTP/HTML work:
<img src="/yourApp/imageController/42.png" alt="car_image"/>
在 3.1 之前的 Spring MVC 中,您可能需要在控制器端做更多的编码.但是原理是一样的.
In Spring MVC before 3.1 you might need to do a little bit more coding on controller side. But the principle is the same.
这篇关于Spring - 在jsp文件上显示图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!