柚子快報邀請碼778899分享:
柚子快報邀請碼778899分享:
《一線大廠Java面試題解析+核心總結(jié)學(xué)習(xí)筆記+最新講解視頻+實戰(zhàn)項目源碼》,點擊傳送門,即可獲取!
spring-boot-starter-thymeleaf
編寫實體類和 Controller
新建實體類 User
這里因為使用 Lombok,所以省去了各種 setter、getter,同時還省去了各種構(gòu)造方法和重寫 toString() 等方法,大大簡化了代碼。而我們所要做的,僅僅是在 pom.xml 中添加 Lombok 的依賴,然后在我們的實體類中加入對應(yīng)的注解即可。
以下是在 pom.xml 中插入 Lombok 依賴的對應(yīng)代碼。
org.projectlombok
lombok
true
然后我們就可以編寫我們的實體類,這里主要用到了 @Data、@Component、@AllArgsConstructor 、NoArgsConstructor 四個注解,其中各個注解的含義如下:
@Component:把類實例化到 Spring 容器,相當(dāng)于在配置文件中配置; @Data :給類的所有屬性提供 get 和 set 方法,此外還有 equals、canEqual、hashCode、toString 方法以及 默認參數(shù)為空的構(gòu)造方法; @AllArgsConstructor:為類提供一個 全參構(gòu)造方法,但此時不再提供默認構(gòu)造方法; @NoArgsConstructor:因為使用了 AllArgsConstructor 會導(dǎo)致類沒有默認空參構(gòu)造方法,所以此時需要它為類提供一個 無參構(gòu)造方法;
package com.cunyu.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Component;
/**
@author : cunyu @version : 1.0 @className : User @date : 2020/7/29 16:20 @description : User 實體類
*/
@Component
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int age;
private String name;
private String email;
}
編寫 Controller
此時主要需要注意的是 setViewName() 和 addObject(),前者表示方法對應(yīng)的前端頁面,也就是我們模板中對應(yīng)文件名的 .html 文件,而后者則主要給屬性注入值,然后將屬性傳遞到前端模板。
package com.cunyu.controller;
import com.cunyu.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
/**
@author : cunyu @version : 1.0 @className : UserController @date : 2020/7/29 16:22 @description : UserController
*/
@Controller
public class UserController {
// 訪問 ip:port/index
@GetMapping(“/index”)
public ModelAndView index() {
ModelAndView modelAndView = new ModelAndView();
// 設(shè)置跳轉(zhuǎn)的視圖,即位于 templates/index.html
modelAndView.setViewName(“index”);
modelAndView.addObject(“title”, “Thymeleaf 使用”);
modelAndView.addObject(“desc”, “Spring Boot 整合 Thymeleaf”);
User author = new User(25, “村雨遙”, “747731461@qq.com”);
modelAndView.addObject(“author”, author);
return modelAndView;
}
}
創(chuàng)建Thymeleaf 模板
第上面的代碼中,我們設(shè)置了跳轉(zhuǎn)的視圖為 index,所以我們需要在 src/main/resources/templates 中創(chuàng)建 index.html。
xmlns:th=“http://www.thymeleaf.org”>
=====作者信息=====
測試
線程、數(shù)據(jù)庫、算法、JVM、分布式、微服務(wù)、框架、Spring相關(guān)知識
一線互聯(lián)網(wǎng)P7面試集錦+各種大廠面試集錦
學(xué)習(xí)筆記以及面試真題解析
《一線大廠Java面試題解析+核心總結(jié)學(xué)習(xí)筆記+最新講解視頻+實戰(zhàn)項目源碼》,點擊傳送門,即可獲??! 識
[外鏈圖片轉(zhuǎn)存中…(img-BbarR1Ps-1714656197189)]
一線互聯(lián)網(wǎng)P7面試集錦+各種大廠面試集錦
[外鏈圖片轉(zhuǎn)存中…(img-fHMuMdvh-1714656197189)]
學(xué)習(xí)筆記以及面試真題解析
[外鏈圖片轉(zhuǎn)存中…(img-ZVCpWqEW-1714656197190)]
《一線大廠Java面試題解析+核心總結(jié)學(xué)習(xí)筆記+最新講解視頻+實戰(zhàn)項目源碼》,點擊傳送門,即可獲??!
柚子快報邀請碼778899分享:
文章鏈接
本文內(nèi)容根據(jù)網(wǎng)絡(luò)資料整理,出于傳遞更多信息之目的,不代表金鑰匙跨境贊同其觀點和立場。
轉(zhuǎn)載請注明,如有侵權(quán),聯(lián)系刪除。