在传统的 SpringMVC 架构中,我们一般将 JSP、HTML 页面放到 webapps 目录下面,但是 Spring Boot 没有 webapps,更没有 web.xml,如果我们要写界面的话,该如何做呢?
Spring Boot 官方提供了几种模板引擎:FreeMarker、Velocity、Thymeleaf、Groovy、mustache、JSP。
这里以 FreeMarker 为例讲解 Spring Boot 的使用。
首先引入 FreeMarker 依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
在 resources 下面建立两个目录:static 和 templates,如图所示:
这里写图片描述
其中 static 目录用于存放静态资源,譬如:CSS、JS、HTML 等,templates 目录存放模板引擎文件,我们可以在 templates 下面创建一个文件:index.ftl(freemarker 默认后缀为 .ftl),并添加内容:
</head>
<body>
<h1>Hello World!</h1>
</body>
然后创建 PageController 并添加内容:
@Controller
public class PageController {
@RequestMapping("index.html")
public String index(){
return "index";
}
}
启动 Application.java,访问:http://localhost:8080/index.html,就可以看到
注:不需要配置视图解析器,直接return“index”不需要前后缀,就可以了。