在springboot中使用文件,需要让springboot对模板引擎支持。下面是具体创建及显示页面内容步骤:
1.想要使用静态页面,首先要配置支持thymeleaf 模版,具体做法:
在pom.xml文件中添加如下内容:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2.在src/main/resources下创建templates文件夹,注意thymeleaf默认在src/main/resources/templates下寻找文件,所以要使用默认配置,则创建的文件夹需是templates这个名字。
3.在templates文件夹下新建一个html文件,具体做法:new-HTML,在file name项这里把文件名改一下,如index.html,点击finish。
4.在controller类上要使用@Controller注解,不能使用@RestController,否则无法访问到页面。然后在controller类中添加如下内容:
@RequestMapping("/toIndex")
public String toPageIndex(Model model){
return "/index";
}
当发出请求的时候,就会去templates下查找index.html,并把页面内容显示到网页上。
5.浏览器输入http://localhost:8080/hello/index,查看内容正确显示在网页上,则表示使用html文件成功。
注意:期间myeclipse崩溃一次,导致8080端口被占用,解决方案:
1.启动cmd,输入netstat -ano|findstr 8080,查看被占用进程的pid;
2.taskkill -f /pid 进程号,kill掉进程,重新run as即可。