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!