Spring - display image on jsp file

java, jsp, jstl, spring, spring-mvc

Solution

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

Now useit in your JSP page. This is how HTTP/HTML work:

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

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.

Problem

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"/> ``` How could I do that? Should I write controller that serve requests for images? Any code examples? 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> ```

Original source

Related problems