簡體   English   中英

using spring boot thymeleaf:在前端用表格顯示圖片等信息

[英]Using spring boot thymeleaf : Display image and other information in a table at front end

我已經創建了廣告表,並在文件系統中插入了廣告的詳細信息和圖像,並在數據庫中插入了其他信息。 圖像的名稱是每個條目的 ID。 現在我必須使用 thymeleaf 在表格中顯示所有信息,但我無法做到這一點。 請檢查以下代碼::--

  1. Model class:
    private String advertisementDesc;
    
    @Column(name = "advertisement_no")
    private String advertisementNo;
    
    @Column(name = "publish_date")
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    @Temporal(TemporalType.DATE)
    private Date publishDate;
        
    @Column(name = "close_date")
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    @Temporal(TemporalType.DATE)
    private Date closeDate;
        
    @Column(name = "apply_multiple_post")
    private Boolean applyMultiplePost;
    
    @Column(name = "is_active")
    private Boolean isActive;
    
    @Column(name = "action_by")
    private long actionBy;
    
    @Column(name = "action_date")
    private Date actionDate;
    
    @Column(name = "action_by_ip", length = 19)
    private String actionByIp;
  1. 存儲庫接口:
@Repository
public interface AdvertisementRepository extends JpaRepository (Advertisement, Integer) {
    
}

  1. 接口存儲服務:

public interface AdvertisementStorageService {
    
    void init();

    void store(MultipartFile file, Integer id);

    Stream<Path> loadAll();

    Path load(String filename);

    Resource loadAsResource(String filename);

    void deleteAll();
    
    Page < Advertisement > findPaginated(int pageNo, int pageSize);
    
}

  1. 存儲服務實現(loadAll方法)

    @Override
    public Stream<Path> loadAll() {
        try {
            return Files.walk(this.rootLocation, 1)
                    .filter(path -> !path.equals(this.rootLocation))
                    .map(path -> this.rootLocation.relativize(path));
        } catch (IOException e) {
            throw new StorageException("Failed to read stored files", e);
        }

    }


  1. 在 Controller 嘗試使用 Index 方法生成列表以顯示在 thymeleaf 模板:


    @GetMapping("index/page/{pageNo}")
    public String findPaginated(@PathVariable(value = "pageNo") int pageNo, Model model) {
        int pageSize = 2;

        Page<Advertisement> page = advertisementStorageService.findPaginated(pageNo, pageSize);
        List<Advertisement> listAdvt = page.getContent();

        model.addAttribute("currentPage", pageNo);
        model.addAttribute("totalPages", page.getTotalPages());
        model.addAttribute("totalItems", page.getTotalElements());
        model.addAttribute("listAdvt", listAdvt);
        
        return "advertisement/index-advertisement";
    }

    @GetMapping("/files/{filename:.+}")
    @ResponseBody
    public ResponseEntity<Resource> serveFile(@PathVariable String filename) {

        Resource file = advertisementStorageService.loadAsResource(filename);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"")
                .body(file);
    }
 @GetMapping("index")       // This is to show index page
            public String showAdvertisementIndex(Model model) {
             
             model.addAttribute("files", advertisementStorageService
                     .loadAll()
                     .map(path -> MvcUriComponentsBuilder.fromMethodName(AdvertisementController.class,
                        "serveFile", path.getFileName().toString()).build().toUri().toString())
                        .collect(Collectors.toList()));
             Iterable<Advertisement> data = advertisementRepository.findAll();
             
             model.addAttribute("advertisements", advertisementRepository.findAll());
             return findPaginated(1, model);  
             
//                  return "advertisement/index-advertisement";
        }

  1. Thymeleaf 索引模板

     <tr th:each="advertisement,iterator: ${advertisements}"> <td th:text="${iterator.count}"></td> <td th:text="${advertisement.id}"></td> <td th:text="${advertisement.advertisementDesc}"></td> <td th:text="${advertisement.advertisementNo}"></td> <td th:text="${advertisement.publishDate}"></td> <td th:text="${advertisement.closeDate}"></td> <:-- <td th.text="${advertisement:advertisementFile}"></td> --> <td th.text="${advertisement:applyMultiplePost}"></td> <td th.text="${advertisement:isActive}"></td> <td><a th.href="@{/advertisement/edit/{id}(id=${advertisement:id})}" class="btn btn-success"> <i class="fas fa-user-edit ml-2"></i></a></td> <td><a th.href="@{/advertisement/delete/{id}(id=${advertisement:id})}" class="btn btn-success"> <i class="fas fa-user-times ml-2"></i></a></td> <td>document</td> </tr> <tr> <td th:text="${localDateTime}"></td> </tr> <tr th:each="file: ${files}"> <td><a th:href="${file}" /> <img th.src="@{/img/pdf:png}" style="width; 50px: height; 60px;"> </td> <td></td> </tr>

您需要將advertisements列表添加到 model 屬性。

另一方面,對於下載文件,您可以在響應中附加InputStream

@GetMapping("/files/{filename:.+}")
public void serveFile(@PathVariable String filename, HttpServletResponse response) {

     // Load the inputStream
     // InputStream = ...


     // Attach in the response
     String contentType = new ConfigurableMimeFileTypeMap().getContentType(fileName);
     res.setContentType(contentType);
     res.addHeader("Content-Disposition", String.format("attachment;filename=\"%s\"", fileName));

     ByteStreams.copy(inputStream, res.getOutputStream());
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM