Spring Boot 学习(一)静态资源


静态资源映射

请求进来,先取找Controller看能不能处理,不能处理的所有请求又都交给静态资源处理器,如果静态资源也找不到就会报404

package com.sp.Controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController

public class HelloController {
    @RequestMapping("/1.jpg")
    public String hello() {
        return "aaaa";
    }
}

当存在路径时会先访问Controller里的方法,如果没有此方法就访问静态资源

 静态资源访问前缀,默认是无前缀的

可以通过改变spring.mvc.static-path-pattern=/resources/**     来改变静态资源目录,在yaml中添加如下信息

res前缀下的所有请求是静态资源请求

spring:
  mvc:
    static-path-pattern: "/res/**"

此时再次访问可以得到:

当前项目 + static-path-pattern + 静态资源名 = 静态资源文件夹下找

改变默认的静态资源路径,不在文件夹下的静态资源无法访问,在yaml中配置如下信息

resources:
    static-locations: classpath:/public      这里也可以添加多个静态资源路径用数组表示   [classpath:/public,..........]

 

webjars

进入网址       https://www.webjars.org/

以jQuery为例:在pom.xml中配置如下信息


org.webjars
jquery
3.6.0

在网址输入http://localhost:8080/webjars/jquery/3.6.0/jquery.js    可以访问到jQuery的静态资源

如下地址要按照依赖的包路径

自定义欢迎页,需要在静态资源文件夹下创建一个index.html文件,之后再到浏览器url输入http://localhost:8080/ 会显示欢迎页面的内容

值得注意的是:

如果配置了静态资源访问前缀的前提下,此功能失效

spring:
  mvc:
    static-path-pattern: "/res/**"

  resources:
    static-locations: classpath:/public

静态资源访问前缀与设置欢迎页面存在冲突

 自定义favicon功能

网址的图标功能,将图标放在静态资源的目录下,并且名字为:favicon.ico

其中静态前缀会影响favicon功能

相关