本篇我们将分享,springboot中配置html页面,平时开发需要一些简单的小项目,我们采取这种方式非常方便。
但是springboot是不允许直接访问template下的文件的,是受保护的,想访问template下的html页面,我们可以配置视图解析器,间接去访问。
一、我们先创建一个springboot项目
二、引入thymeleaf依赖
<!--thymeleaf模板引擎配置-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
三、配置application.yml
spring:
thymeleaf:
prefix: classpath:/templates/ # 访问template下的html文件需要配置模板,映射,路径指向
suffix: .html
cache: false # 开发时关闭缓存,不然没法看到实时页面
四、我们弄个测试的controller进行访问下
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class TestController {
@RequestMapping("/index")
public String show(){
return "index";
}
}
注意:@Controller注解不能换成RestController注解或者在方法上加@ResponseBody注解,否则视图解析器InternalResourceViewResolver会失效,无法解析html、jsp页面进而跳转到指定的页面,而是返回return的内容,在上面就是字符串了。
五、我们在templates目录下弄个html页面
一切配好,我们测下试试,结果如图
至此,我们简单的springboot配置html就好了,以上均是个人日常开发用到的,如果有什么不对的地方,欢迎指正,非常感谢!