springboot Web实战
静态资源放在那里:通过源码了解
SpringBoot中的SpringMVC配置功能都是在WebMvcAutoConfiguration
类中
在idea中按住==ctrl+N键,在弹出的输出框中输入WebMvcAutoConfiguration.class==
然后找到==addResourceHandlers==函数
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
super.addResourceHandlers(registry);
if (!this.resourceProperties.isAddMappings()) {
logger.debug("Default resource handling disabled");
} else {
this.addResourceHandler(registry, "/webjars/**", "classpath:/META-INF/resources/webjars/");
this.addResourceHandler(registry, this.mvcProperties.getStaticPathPattern(), this.resourceProperties.getStaticLocations());
}
}
第一种方式:webjars
webjars:以jar包的方式引入静态资源,静态资源存放路径为resources下的自己新建的webjars文件下
然后复制相应的maven坐标到pom.xml文件中就可以了
第二种方式:/**
然后按住ctrl键,鼠标左键getStaticPathPattern() 会跳转到WebMvcProperties.class类下的 getStaticPathPattern()方法
public String getStaticPathPattern() {
return this.staticPathPattern;
}
然后按住ctrl键,鼠标左键staticPathPattern会跳转到另一个界面,如图发现路径可为:/**
第三种方式:resources文件夹下的static,resources文件夹下的public,resources文件夹下的resources
然后按住ctrl键,鼠标左键resourceProperties会跳转到EnableWebMvcConfiguration类,按住ctrl键鼠标左键点击ResourceProperties
会跳转到:ResourceProperties类
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = new String[]{"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"};
private String[] staticLocations;
private boolean addMappings;
private final ResourceProperties.Chain chain;
private final ResourceProperties.Cache cache;
........
}
部分源码截图:
通过源码查看可以存放静态资源的演示:
访问优先级
resource>static>public
演示:
定制首页和图标
新版本springboot不需要关闭默认图标,只需要把图标名称和格式写为:favicon.ico,放到静态资源目录下就可以了,不必像在老版本中配置文件中关闭默认图标
图标的访问文件优先级resource>static>public
演示动图:
通过源码看首页
在idea中按住ctrl+N键,在弹出的输出框中输入WebMvcAutoConfiguration.class
找到如图所示文件
我们可以将index.html首页放在resources下的static、public、resources内都可以被识别。以及Templates目录下
在Templates目录下的所有页面,只能通过Controller来跳转,Templates这个目录就相当于SSM中的WEB-INF目录。
前提是要引入模板引擎——Thymeleaf
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
常见的模板引擎 JSP、Velocity、Freemarker、Thymeleaf Spring Boot推荐使用Thymeleaf,语法简单、强大。 模板引擎的作用:把数据和静态模板进行绑定,生成我们想要的HTML
项目结构:
HelloController类:
package com.zsq.Controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/hello")
public class HelloController {
@GetMapping("/hi")
// @ResponseBody不需要加上,加上就不会跳到index.html,而是直接显示index字符串
//return写index不能写其他的,其他的会报错,index指的就是index.html
public String hello(){
return "index";
}
}
演示视频:
springboot2.3.11.RELEASE-首页,图标定制演示视频