Spring Boot整合FreeMarker模板引擎


POM

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

項目結構

src/
 +- main/
     +- java/
     |   +- com
     |       +- controller/
     |       |   +- IndexController.class
     |       +- Application.class
     +- resources/
         +- templates/
             +- index.ftlh
  • Application為應用程序啟動類
  • IndexController為控制器,里面含有一個index請求處理方法,它返回index字符串,表示渲染模板文件index.ftlh。
  • index.ftlh為freemarker模板文件

Applciation.class

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

IndexController.class

@Controller
public class IndexController {

    @GetMapping("/index")
    public String index(Model model) {
        model.addAttribute("name", "Alice");
        return "index";
    }
}

注意@ResponseBody注解不能和freemarker一起使用,所以此處不能標注@RestController注解。

index.ftlh

<!DOCTYPE html>
<html>
<head>
    <title>test</title>
</head>
<body>
hello ${name}!
</body>
</html>

運行

運行Application類里的main方法。

然后訪問localhost:8080/index,結果展示為:

hello Alice!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM