功能:仅仅是静态资源访问 和 Controller 转发访问
(springboot 中 application.properties 与application.yml 作用相同 只是赋值方式不一样,下面就用 application.properties)
流程==>
1.创建一个 springboot 项目 打jar 包.
项目命名:sb-web-2020-static
主包路径:com.per
2.至少需要的依赖有:1. Spring web 2. thymeleaf(用于页面访问)
提示:springboot 会自动有以下四个部分(1个继承 2个依赖 1个插件 1个服务器)
1)继承:自动继承 继承父类集成jar 包
2)依赖 1.springboot starter 启动依赖 2.springboot starter test 测试启动依赖
3)插件:maven-plugin maven插件
4)自带tomcat
检验:创建完了后,查看一下pom.xml文件,是否包含提示中1-3的项目.
3.在还需要在配置文件 .properties 中配置 端口号
server.port=8080
4.静态访问
1) 在资源目录~~ src/main/resources 中的新建文件夹 static(如果static本身存在就不需要另外创建),然后在static里面新建一个文件 hello.html,最终目录如下src\main\resources\static\hello.html
2)点击项目右键 springboot App 启动
3)浏览器访问:http://localhost:8080/hello.html
4)出现了hello.html 里面的内容,访问成功!
5.Controller 转发访问
1)添加Controller类
在主启动类下面子包中新建 controller包 Controller类,访问方法.
package com.per.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/")
public class HelloController {
@RequestMapping("good")
public String doGood() {
return "good";
}
// http://localhost:8080/good
}
2)在src\main\resources\templates 中新建访问页面 good.html
提示:SpringBoot项目中使用templates页面模板时候,会默认访问src\main\resources\templates路径下的页面资源,同时添加默认后缀 .html
3)重新启动 项目.
4)浏览器输入:http://localhost:8080/hello
出现good.html页面说明访问成功!
注意:这时候就不是直接访问项目中的静态资源了,静态资源是需要后缀名的,这是通过Controller 转发访问过来的.
思考:在good.html右键 Show in - System Explorer 可以复制该文件在电脑中的绝对路径,把绝对路径放入浏览器也是可以访问的,这是属于绝对路径下的访问,是浏览器访问本机资源.而关闭项目后,http://localhost:8080/hello.html 和 http://localhost:8080/good 在浏览器是不能访问访问的,说明我们是通过项目中TomCat来访问.
附加:
1.springboot 是默认项目名为 / ,需要设置
#server
server.servlet.context-path=/name
2.静态资源默认访问 /,默认跳转页面 index.html
3.默认访问资源的优先级
~~ src/main/resources 中的下列文件夹
META-INF/resources文件夹 > resources文件夹 > static文件夹 > public文件夹
4.Controller转发资源访问优先级 和静态资源一样
META-INF/resources文件夹 > resources文件夹 > static文件夹 > public文件夹
5.一般会对 Controller 访问跳转页面 进行设置
#spring web
spring.thymeleaf.prefix=classpath:/templates/pages/
spring.thymeleaf.suffix=.html