先查看springboot的工厂类里的默认视图解析器
WebMvcAutoConfiguration
InternalResourceViewResolver
可以看到这个是可以通过yml配置的
html的视图解析器
要把视图解析器改成html的咋改呢,很简单,在yml中配置后,spring会自动注入配置属性
后端的controller只能用@Controller注解,不能使用@RestController。因为后者会把内容转成字符串
demo如下
SpringBoot中使用Thymeleaf
SpringBoot官方是推荐使用thymeleaf作为优选的视图解析器,所以SpringBoot对Thymeleaf的支持非常好,这里仅仅演示SpringBoot如何选用Thymeleaf作用默认视图解析器。
第一步:导入Thymeleaf的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
第二步:创建存放Thymeleaf模板文件夹,在Resources目录下创建templates目录
这个文件夹的名字可不是我么随便命名的啊,是SpringBoot在自动装配Thymeleaf视图解析器的时候就已经预定义好了,我们看一下它的定义源码。
也是从springboot的工厂类中查看
ThymeleafAutoConfiguration