19 October 2018

Spring Boot Thymeleaf Template Show Data

Tiếp ví dụ trước HelloWord 
Cấu trúc project ở ví dụ này
DemoController.java
Spring Boot 2018
package com.example.demo.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.*;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import com.example.demo.entities.Student;

@Controller
@RequestMapping("demo")
public class DemoController {

   @RequestMapping(method = RequestMethod.GET)
   public String index(ModelMap modelMap) {
      modelMap.put("a", 1231231);
      modelMap.put("photo", "/bitcoinmining.png");
      List < Student > list = new ArrayList < Student > ();
      list.add(new Student(1, "name 01"));
      list.add(new Student(2, "name 02"));
      list.add(new Student(3, "name 03"));
      modelMap.put("students", list);
      return "demo/index";
   }

}
Student.java
Spring Boot 2018
package com.example.demo.entities;

public class Student {

   private int id;
   private String name;
   public Student(int id, String name) {
      super();
      this.id = id;
      this.name = name;
   }
   public Student() {
      super();
   }
   public int getId() {
      return id;
   }
   public void setId(int id) {
      this.id = id;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }

}
index.html
Spring Boot 2018
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
   <head>
      <meta charset="ISO-8859-1" />
      <title>Insert title here</title>
   </head>
   <body>
      Hello World
      <br />
      <p th:text="'Gia tri a la '+${a}">Demo</p>
      <img th:src="@{'/images/'+${photo}}" width="100px" />
      <table border="1">
         <tr th:each="student, iterStat: ${students}">
            <th th:text="${student.id}"></th>
            <th th:text="${student.name}"></th>
         </tr>
      </table>
   </body>
</html>
Run app
Kết quả chạy trên chrome

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang