項目地址:https://github.com/zhaopeng01/springboot-study/tree/master/study8
Spring Boot提供了多種模板引擎的默認配置支持,但嵌入式容器JSP有限制,2010年後Velocity停止更新,所以這JSP與Velocity兩個不建議使用,然實際在企業中,還是有很多在使用
那麼這裏主要是
springboot
整合Thymeleaf
模板。
在SpringBoot
使用上述模板,默認從src/main/resources/templates
下加載。
Thymeleaf
是現代化服務器端的Java模板引擎,不同與其它幾種模板的是Thymeleaf的語法更加接近HTML,並且具有很高的擴展性,其他詳細可移步官網
依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
先創建一個實體類
entity
package com.zyc.entity;
public class Person {
private String name;
private String gender;
private String email;
//get set 方法
}
創建一個controller 用來映射HTTP請求與頁面的跳轉
controller
package com.zyc.controller;
import com.zyc.entity.Person;
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;
import javax.servlet.http.HttpServletRequest;
/**
* @Description: Thymeleaf
* @author zhaopeng
* @email [email protected]
*/
@Controller
@RequestMapping
public class ThyController {
@GetMapping("/index")
public ModelAndView index() {
ModelAndView view = new ModelAndView();
view.setViewName("index");
// 設置屬性
view.addObject("title", "Thymeleaf頁面");
view.addObject("desc", "Welcome to Thymeleaf");
Person person = new Person();
person.setGender("男娃子");
person.setEmail("[email protected]");
person.setName("趙鵬");
view.addObject("person", person);
return view;
}
@GetMapping("/index1")
public String index1(HttpServletRequest request) {
// 設置屬性
request.setAttribute("title", "Thymeleaf頁面");
request.setAttribute("desc", "Welcome to Thymeleaf");
Person person = new Person();
person.setGender("難道到這裏就能變成個女娃子?");
person.setEmail("[email protected]");
person.setName("趙鵬");
request.setAttribute("person", person);
return "index";
}
}
兩個方法的寫法不同,但是結果一致。
在第一個方法中設置的跳轉到index,默認映射到 src/main/resources/templates/{viewName}.html
在第一個方法中設置的跳轉到index,默認映射到 src/main/resources/templates/xxxx.html
這樣就基本ok了,可以先直接將這個index.html打開看一下,這是靜態效果
然後運行我們的項目,訪問 http://localhost:8080/index 然後可以看到我們的動態效果
了
SpringBoot
默認情況下爲我們做了如下的默認配置工作,當然我們也可以在自己需要的情況下去修改這些配置,實現自己的需求
好的到這裏本篇文章就先到此了,創作不易,如果那裏有不合適的地方還請大家多多指教,寫這篇博的目的主要就是爲了方便自己以後的一個回憶和朋友學習時的一個參考,希望爲大家可以帶來幫助 ~ ~&
虛心的去學習,自信的去工作~