Spring - 在jsp文件上显示图像 [英] Spring - display image on jsp file
问题描述
我的模型商店图像用文件名(作为String)和数据(作为字节数组)描述。我使用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?
任何代码示例?
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>
推荐答案
你不能这样做。您的图片必须通过普通网址以某种方式曝光。在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屋!