需求: 前端请求,传入一个图片名称,后端springboot根据传入的图片名称进行读取,再传入到Thymeleaf。
在web开发中,前后端分离是非常重要的,因此也产生了一系列问题,这个案例不使用数据库,只是简单演示,如何由发起请求,再由后端读取数据,传入动态页面进行显示。
如果要使用动态页面需要在pom中配置thymeleaf依赖
org.springframework.boot
spring-boot-starter-thymeleaf
后端contoller
@EnableAutoConfiguration
@ComponentScan
@Controller
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
@RequestMapping(value = "/home")
public ModelAndView home(@RequestParam("name") String name ) throws IOException {
ModelAndView view = new ModelAndView("index");
view.addObject("image_name", name);
return view;
}
@RequestMapping(value = "/image/{image_name}", produces = MediaType.IMAGE_PNG_VALUE)
public ResponseEntity getImage(@PathVariable("image_name") String image_name) throws Exception{
byte[] imageContent ;
String path = "your image path with image_name";
imageContent = fileToByte(new File(path));
final HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_PNG);
return new ResponseEntity<>(imageContent, headers, HttpStatus.OK);
}
public static byte[] fileToByte(File img) throws Exception {
byte[] bytes = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
BufferedImage bi;
bi = ImageIO.read(img);
ImageIO.write(bi, "png", baos);
bytes = baos.toByteArray();
} catch (Exception e) {
e.printStackTrace();
} finally {
baos.close();
}
return bytes;
}
}
先看第二个controller方法,这里的@RequestMapping(value = "/image/{image_name}", produces = MediaType.IMAGE_PNG_VALUE)value绑定了请求的url,同时{image_name}会传入方法内部,produces设置了产生的数据类型。因为这里使用的数据是PNG格式,如果是其他image格式,需要修改方法内部的ContentType。这个controller其实是设置为Thymeleaf调用的。
再看看动态页面的代码 index.html
You can find your inlined image just below this text.
这里的 @后面的url指向了绑定为/image/{image_name}的Contoller。
再回过头看第一个"/home" controller,设置寻址为"index",即templates/index.html,再将数据传入到Thymeleaf中,由Thymeleaf调用第二个Controller即getImage方法,最终得到img数据。
image.png