首先我们来了解下template 文件夹在springboot中的作用
SpringBoot里面没有我们之前常规web开发的WebContent(WebApp),它只有src目录
在src/main/resources下面有两个文件夹,static和templates springboot默认 static中放静态页面,而templates中放动态页面
templates文件夹,是放置模板文件的,因此需要视图解析器来解析它。所以必须通过服务器内部进行访问,也就是要走控制器--服务--视图解析器这个流程才行。
static文件夹,既不能直接访问,也不能通过服务器访问到。因此,这个文件夹,可能是放一些css、图片这样的文件供服务器内部引用。
所以要想访问 templates下的html页面,必须需要视图解析器。
spring boot在springmvc的视图解析器方面就默认集成了ContentNegotiatingViewResolver和BeanNameViewResolver,在视图引擎上就已经集成自动配置的模版引擎,如下:
1. FreeMarker
2. Groovy
3. Thymeleaf
4. Velocity (deprecated in 1.4)
6. Mustache
这里使用Thymeleaf,在application.yml配置文件做一下配置
spring:
thymeleaf:
mode: HTML # Template mode to be applied to templates. See also Thymeleaf's TemplateMode enum.
prefix: classpath:/templates/ # Prefix that gets prepended to view names when building a URL.
suffix: .html # Suffix that gets appended to view names when building a URL.
pom.xml加入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
公用控制层,伪造是页面直接访问的样子
package com.hsit.lsj.config;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class WebController {
@RequestMapping(value="/{module}/{module2}/{name}")
public String commonController(@PathVariable String module,@PathVariable String module2, @PathVariable String name) {
return module+"/"+module2+"/"+name;
}
@RequestMapping(value="/{module}/{name}")
public String commonController2(@PathVariable String module, @PathVariable String name) {
return module+"/"+name;
}
@RequestMapping(value="/{name}")
public String commonController(@PathVariable String name) {
return name;
}
}
这里配置了三层/1/2/3. 也就是最多templates下建立三层子文件。如需更多自己配置