问题:如何解决为每个项目显示相同图像的问题?
thymleaf.html
<div th:each="goals : ${goals}">
<div th:text="${goals.getId()}"></div>
<img th:src="@{'image/'+ ${goals.getId()}}" width="100px;"
height="100px;"/>
<div th:text="${goals.title}"></div>
图像控制器
@GetMapping(value = "/image/{id}")
public void showProductImage(@PathVariable String id,
HttpServletResponse response) throws IOException{
Goals goals = goalsRepository.findById(UUID.fromString(id));
logger.info("I got id--"+id);
response.setContentType("image/jpeg, image/jpg, image/png,
image/gif");
response.getOutputStream().write(goals.getImage());
response.getOutputStream().close();
查看页面的控制器
@GetMapping(value = "/goals")
public String read(Model model) {
model.addAttribute("login", new LogIn()); //it for bottom menu
model.addAttribute("currentlyPage","goals"); // it for top menu
model.addAttribute("addNewGoal", new addNewGoal()); //another page
//get all goals
List<Goals> goals = new ArrayList<>();
goalsRepository.findAll().forEach(goals::add);
model.addAttribute("goals",goals);
return "goals";
log4j
I got id--bc8c9820-9500-
I got id--5ba1d0d0-9504-
I got id--bff1d8a0-94ff-
I got id--1f0da4f0-94ff-11e9-970f-0bfed788288d
I got id--d76dd9b0-9500-11e9-81ae-c9c1d3b67a0f
I got id--4aaaac80-9512-11e9-b98b-7deb4e16d250
I got id--608dae20-94ff-11e9-89b4-83a8b92aa5c9
我希望使用不同的图像,但是到处都是相同的图像。enter image description here
答案 0 :(得分:0)
我找到了解决方法。
我将实体的图片类型更改为ByteBuffer
我通过下一个代码更改了控制器:
@GetMapping(value = "/image/{id:.+}")
public @ResponseBody ResponseEntity<byte[]> showProductImage(@PathVariable String id, HttpServletResponse response) throws IOException {
Goals goals = goalsRepository.findById(UUID.fromString(id));
ByteBuffer buffer =goals.getImage();
byte[] bytes = buffer.array();
return ResponseEntity.ok().contentType(MediaType.IMAGE_JPEG).body(bytes);
}
我更改了一些valueOf类型以进行转换。