SpringBoot 實戰 (十二) | 整合 thymeleaf

微信公衆號:一個優秀的廢人 若有問題或建議,請後臺留言,我會盡力解決你的問題。html

前言

如題,今天介紹 Thymeleaf ,並整合 Thymeleaf 開發一個簡陋版的學生信息管理系統。前端

SpringBoot 提供了大量模板引擎,包含 Freemarker、Groovy、Thymeleaf、Velocity 以及 Mustache,SpringBoot 中推薦使用 Thymeleaf 做爲模板引擎,由於 Thymeleaf 提供了完美的 SpringMVC 支持。Thymeleaf 是新一代 Java 模板引擎,在 Spring 4 後推薦使用。html5

什麼是模板引擎?

Thymeleaf 是一種模板語言。那模板語言或模板引擎是什麼?常見的模板語言都包含如下幾個概念:數據(Data)、模板(Template)、模板引擎(Template Engine)和結果文檔(Result Documents)。java

  • 數據 數據是信息的表現形式和載體,能夠是符號、文字、數字、語音、圖像、視頻等。數據和信息是不可分離的,數據是信息的表達,信息是數據的內涵。數據自己沒有意義,數據只有對實體行爲產生影響時才成爲信息。
  • 模板 模板,是一個藍圖,即一個與類型無關的類。編譯器在使用模板時,會根據模板實參對模板進行實例化,獲得一個與類型相關的類。
  • 模板引擎 模板引擎(這裏特指用於Web開發的模板引擎)是爲了使用戶界面與業務數據(內容)分離而產生的,它能夠生成特定格式的文檔,用於網站的模板引擎就會生成一個標準的HTML文檔。
  • 結果文檔 一種特定格式的文檔,好比用於網站的模板引擎就會生成一個標準的HTML文檔。

模板語言用途普遍,常見的用途以下:mysql

  • 頁面渲染
  • 文檔生成
  • 代碼生成
  • 全部 「數據+模板=文本」 的應用場景

Thymeleaf 簡介

Thymeleaf 是一個 Java 類庫,它是一個 xml/xhtml/html5 的模板引擎,能夠做爲 MVC 的 web 應用的 View 層。git

Thymeleaf 還提供了額外的模塊與 SpringMVC 集成,因此咱們能夠使用 Thymeleaf 徹底替代 JSP 。github

Thymeleaf 語法

博客資料:www.cnblogs.com/nuoyiamy/p/… 官方文檔:www.thymeleaf.org/documentati…web

SpringBoot 整合 Thymeleaf

下面使用 SpringBoot 整合 Thymeleaf 開發一個簡陋版的學生信息管理系統。算法

一、準備工做spring

  • IDEA
  • JDK1.8
  • SpringBoot2.1.3

二、pom.xml 主要依賴

<dependencies>
        <!-- JPA 數據訪問 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <!-- thymeleaf 模板引擎 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <!-- web 啓動類 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- mysql 數據庫鏈接類 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
</dependencies>
複製代碼

三、application.yaml 文件配置

spring:
  # 數據庫相關
 datasource:
 driver-class-name: com.mysql.cj.jdbc.Driver
 url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC&useSSL=true
 username: root
 password: 123456
  # jpa 相關
 jpa:
 hibernate:
 ddl-auto: update   # ddl-auto: 第一次啓動項目設爲 create 表示每次都從新建表,以後設置爲 update
 show-sql: true
複製代碼

四、實體類

@Data
@Entity
@AllArgsConstructor
@NoArgsConstructor
public class Student {

    @Id
    @GeneratedValue
    /** * 主鍵 */
    private Long id;

    /** * 主鍵 */
    private Long studentId;

    /** * 姓名 */
    private String name;

    /** * 年齡 */
    private Integer age;

    /** * 專業 */
    private String major;

    /** * 宿舍 */
    private String dormitory;

    /** * 籍貫 */
    private String city;

    /*@Temporal(TemporalType.TIMESTAMP)//將時間戳,轉換成年月日時分秒的日期格式 @Column(name = "create_time",insertable = false, updatable=false, columnDefinition = "timestamp default current_timestamp comment '註冊時間'") private Date createDate; @Temporal(TemporalType.TIMESTAMP)//將時間戳,轉換成年月日時分秒的日期格式 @Column(name = "update_time",insertable = false, updatable=true, columnDefinition = "timestamp default current_timestamp comment '修改時間'") private Date updateDate;*/

}
複製代碼

五、dao 層

@Repository
public interface StudentRepository extends JpaRepository<Student, Long> {
}
複製代碼

六、service 層

public interface StudentService {

    List<Student> findStudentList();

    Student findStudentById(Long id);

    Student saveStudent(Student student);

    Student updateStudent(Student student);

    void deleteStudentById(Long id);

}
複製代碼

實現類:

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentRepository studentRepository;

    /** * 查詢全部學生信息列表 * @return */
    @Override
    public List<Student> findStudentList() {
        Sort sort = new Sort(Direction.ASC,"id");
        return studentRepository.findAll(sort);
    }

    /** * 根據 id 查詢單個學生信息 * @param id * @return */
    @Override
    public Student findStudentById(Long id) {
        return studentRepository.findById(id).get();
    }

    /** * 保存學生信息 * @param student * @return */
    @Override
    public Student saveStudent(Student student) {
        return studentRepository.save(student);
    }

    /** * 更新學生信息 * @param student * @return */
    @Override
    public Student updateStudent(Student student) {
        return studentRepository.save(student);
    }

    /** * 根據 id 刪除學生信息 * @param id * @return */
    @Override
    public void deleteStudentById(Long id) {
        studentRepository.deleteById(id);
    }
}
複製代碼

七、controller 層 (Thymeleaf) 使用

controller 層將 view 指向 Thymeleaf:

@Controller
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private StudentService studentService;

    /** * 獲取學生信息列表 * @param map * @return */
    @GetMapping("/list")
    public String findStudentList(ModelMap map) {
        map.addAttribute("studentList",studentService.findStudentList());
        return "studentList";
    }

    /** * 獲取保存 student 表單 */
    @GetMapping(value = "/create")
    public String createStudentForm(ModelMap map) {
        map.addAttribute("student", new Student());
        map.addAttribute("action", "create");
        return "studentForm";
    }

    /** * 保存學生信息 * @param student * @return */
    @PostMapping(value = "/create")
    public String saveStudent(@ModelAttribute Student student) {
        studentService.saveStudent(student);
        return "redirect:/student/list";
    }

    /** * 根據 id 獲取 student 表單,編輯後提交更新 * @param id * @param map * @return */
    @GetMapping(value = "/update/{id}")
    public String edit(@PathVariable Long id, ModelMap map) {
        map.addAttribute("student", studentService.findStudentById(id));
        map.addAttribute("action", "update");
        return "studentForm";
    }

    /** * 更新學生信息 * @param student * @return */
    @PostMapping(value = "/update")
    public String updateStudent(@ModelAttribute Student student) {
        studentService.updateStudent(student);
        return "redirect:/student/list";
    }

    /** * 刪除學生信息 * @param id * @return */
    @GetMapping(value = "/delete/{id}")
    public String deleteStudentById(@PathVariable Long id) {
        studentService.deleteStudentById(id);
        return "redirect:/student/list";
    }
}
複製代碼

簡單說下,ModelMap 對象來進行數據綁定到視圖。return 字符串,該字符串對應的目錄在 resources/templates 下的模板名字。 @ModelAttribute 註解是用來獲取頁面 Form 表單提交的數據,並綁定到 Student 數據對象。

八、studentForm 表單

定義了一個 Form 表單用於註冊或修改學生信息。

<form th:action="@{/student/{action}(action=${action})}" method="post" class="form-horizontal">

        <div class="form-group">
            <label for="student_Id" class="col-sm-2 control-label">學號:</label>
            <div class="col-xs-4">
                <input type="text" class="form-control" id="student_Id" name="name" th:value="${student.studentId}" th:field="*{student.studentId}"/>
            </div>
        </div>

        <div class="form-group">
            <label for="student_name" class="col-sm-2 control-label">姓名:</label>
            <div class="col-xs-4">
                <input type="text" class="form-control" id="student_name" name="name" th:value="${student.name}" th:field="*{student.name}"/>
            </div>
        </div>

        <div class="form-group">
            <label for="student_age" class="col-sm-2 control-label">年齡:</label>
            <div class="col-xs-4">
                <input type="text" class="form-control" id="student_age" name="name" th:value="${student.age}" th:field="*{student.age}"/>
            </div>
        </div>

        <div class="form-group">
            <label for="student_major" class="col-sm-2 control-label">專業:</label>
            <div class="col-xs-4">
                <input type="text" class="form-control" id="student_major" name="name" th:value="${student.major}" th:field="*{student.major}"/>
            </div>
        </div>

        <div class="form-group">
            <label for="student_dormitory" class="col-sm-2 control-label">宿舍:</label>
            <div class="col-xs-4">
                <input type="text" class="form-control" id="student_dormitory" name="name" th:value="${student.dormitory}" th:field="*{student.dormitory}"/>
            </div>
        </div>

        <div class="form-group">
            <label for="student_city" class="col-sm-2 control-label">籍貫:</label>
            <div class="col-xs-4">
                <input type="text" class="form-control" id="student_city" name="writer" th:value="${student.city}" th:field="*{student.city}"/>
            </div>
        </div>

        <div class="form-group">
            <div class="col-sm-offset-3 col-sm-10">
                <input class="btn btn-primary" type="submit" value="提交"/>&nbsp;&nbsp;
                <input class="btn" type="button" value="返回" onclick="history.back()"/>
            </div>
        </div>
    </form>
複製代碼

九、studentList 學生列表

用於展現學生信息:

<table class="table table-hover table-condensed">
        <legend>
            <strong>學生信息列表</strong>
        </legend>
        <thead>
        <tr>
            <th>學號</th>
            <th>姓名</th>
            <th>年齡</th>
            <th>專業</th>
            <th>宿舍</th>
            <th>籍貫</th>
            <th>管理</th>
        </tr>
        </thead>
        <tbody>
        <tr th:each="student : ${studentList}">
            <th scope="row" th:text="${student.studentId}"></th>
            <td><a th:href="@{/student/update/{studentId}(studentId=${student.id})}" th:text="${student.name}"></a></td>
            <td th:text="${student.age}"></td>
            <td th:text="${student.major}"></td>
            <td th:text="${student.dormitory}"></td>
            <td th:text="${student.city}"></td>
            <td><a class="btn btn-danger" th:href="@{/student/delete/{studentId}(studentId=${student.id})}">刪除</a></td>
        </tr>
        </tbody>
    </table>
複製代碼

頁面效果

列表頁面:點擊按鈕可註冊學生信息

初始頁面

註冊/修改學生信息頁面:點提交保存學生信息到數據庫並返回列表頁面

註冊/修改學生信息頁面

有數據的列表頁面:點擊名字跳到註冊/修改頁面可修改學生信息,點擊刪除可刪除學生信息

列表頁面

源碼下載

github 地址 :github.com/turoDog/Dem…

後語

若是本文對你哪怕有一丁點幫助,請幫忙點好看。你的好看是我堅持寫做的動力。

另外,關注以後在發送 1024 可領取免費學習資料。資料內容詳情請看這篇舊文:Python、C++、Java、Linux、Go、前端、算法資料分享

一個優秀的廢人
相關文章
相關標籤/搜索