1. 程式人生 > >SpringBoot入門 - 使用Freemaker模板跳轉頁面

SpringBoot入門 - 使用Freemaker模板跳轉頁面

1.專案匯入FreeeMarker模板引擎所需依賴  (springboot所需依賴以及其他的web支援等依賴就根據自己的專案來匯入即可)

<!-- FreeeMarker模板引擎所需依賴 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

2.配置 application.properties

# FreeeMarker 模板引擎配置
spring.freemarker.allow-request-override=false
spring.freemarker.cache=false
spring.freemarker.check-template-location=true
spring.freemarker.charset=UTF-8
spring.freemarker.content-type=text/html
spring.freemarker.expose-request-attributes=false
spring.freemarker.expose-session-attributes=false
spring.freemarker.expose-spring-macro-helpers=false
#spring.freemarker.prefix=
#spring.freemarker.request-context-attribute=
#spring.freemarker.settings.*=
#spring.freemarker.suffix=.ftl
#spring.freemarker.template-loader-path=classpath:/templates/ #comma-separated list
#spring.freemarker.view-names= # whitelist of view names that can be resolved

3.模板頁面 

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
             xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
    <title>Hello World!</title>
</head>
<body>
    Hello : ${msg}
</body>
</html>

4.編寫controller類,跳轉頁面

@Controller
public class WebController {
    @RequestMapping("/index")
    public String index(Model model){
        model.addAttribute("msg", "後臺傳的資料...");
        return "index";
    }
}  

 或

@RestController //@[email protected][email protected] 官方推薦使用
public class WebController2 {

    @RequestMapping("/index2")
    public ModelAndView index(Model model){
        model.addAttribute("msg", "後臺傳的資料...");
        return new ModelAndView("index");
    }

}              

5.編寫啟動類

@SpringBootApplication
public class WebApplication {
    public static void main(String[] args) {
        SpringApplication.run(WebApplication.class);
    }
}

 6.執行測試

<--最後附上專案結構-->