>>分享流行的Java框架以及开源软件,对孙卫琴的《精通Spring》、《Spring Cloud Alibaba微服务开发零基础入门到实操》提供技术支持 书籍支持  卫琴直播  品书摘要  在线测试  资源下载  联系我们
发表一个新主题 开启一个新投票 回复文章 您是本文章第 27688 个阅读者 刷新本主题
 * 贴子主题:  微架构 springcloud-07. springboot-静态资源处理 回复文章 点赞(0)  收藏  
作者:flybird    发表时间:2020-06-29 04:19:28     消息  查看  搜索  好友  邮件  复制  引用

    

静态资源处理

默认静态资源映射

首先看官网解释:
By default Spring Boot will serve static content from a directory called /static (or /public or /resources or /META-INF/resources) in the classpath or from the root of the ServletContext. It uses the ResourceHttpRequestHandler from Spring MVC so you can modify that behavior by adding your own WebMvcConfigurerAdapter and overriding the addResourceHandlers method.

大意是:在默认情况下,springboot 默认映射类路径下 /static、/public、 /resources、 /META-INF/resources 等目录下的资源。

默认映射,在启动服务的时候,控制台有打印以下记录:
[  restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
[  restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]

# 默认配置的 /** 映射到 /static (或/public、/resources、/META-INF/resources)
    其优先级是 META/resources > resources > static > public
# 默认配置的 /webjars/** 映射到 classpath:/META-INF/resources/webjars/

01 在resources下新建目录static/images,任意放一张图片springboot.jpg 到images目录:
└─resources
    │  application.properties
    │
    ├─static
    │  └─images
    │          springboot.jpg
    │
    └─templates
            empList.html
            Error.html
            ok.html

02 在empList.html 添加一个img 标签:
<img src="/images/springboot.jpg" />

# 浏览器访问 http://localhost:8080/emp/empList
打印图片
打印员工信息……

#静态资源访问成功,将static目录重命名为public,重启服务,刷新网页:
打印图片
打印员工信息……

#测试验证通过

03 注意 src="/images/springboot.jpg",资源定位以“/” 开头,也就是说默认以“/” 开始定位,如果我们的应用上下文不是“/” 呢? application.proterties 添加上下文配置:
# application.proterties  添加配置:
server.context-path=/springmybatis

04 重启服务,访问 http://localhost:8080/springmybatis/emp/empList
打印员工信息

# 未显示图片,检查发现图片的定位是:http://localhost:8080/images/springboot.jpg =>缺上下文一级

05 更改图片路径
<img src="/springmybatis/images/springboot.jpg" />

# 重新访问,http://localhost:8080/springmybatis/emp/empList
打印图片
打印员工信息

06 加入context-path发生改变呢?那么如此固定的写法改动起来就显得非常被动了,那么如何处理呢?有以下两种方式:
#方法一:动态获取contextPath添加到路径之前,img 标签重写为:
<img th:src="${#httpServletRequest.getContextPath()+'/images/springboot.jpg'}" />

#重现编译,或者重启服务,刷新页面
打印图片
打印员工信息

#问题解决,如此动态获取contextpath避免了固定写法的被动

  但是这样做也有一个问题,每次在定位静态资源时都要在路径前获取contextpath,代码重复较重!推荐采用base解决:


# 方法二: 在网页head 标签中添加一个base 子标签
<base th:href="${#httpServletRequest.getContextPath()+'/'}"/>

# img 标签重写为:
<img src="images/springboot.jpg" />

# 重现编译,或者重启服务,刷新页面  http://localhost:8080/springmybatis/emp/empList
打印图片
打印员工信息

# 问题解决,如此,类似img标签代码重复问题得以解决

自定义静态资源映射

01 在classpath(即:resources) 下自定义一个资源目录:mysource,添加wu.jpg 到其中:
resources
    mysource
        wu.jpg

02 浏览器访问 http://localhost:8080/springmybatis/wu.gif
# 页面报错404 ,找不到资源

03 新建 person/jack.config/MyConfig:
package person.jack.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class MyConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations("classpath:/mysource/");
        super.addResourceHandlers(registry);
    }
}

04 重启服务,重新访问:http://localhost:8080/springmybatis/wu.gif
打印图片

# 在上述代码调用 addResourceHandler("/**") 方法时,传入的参数时:/** ,这样会破会默认的静态资源配置,
# 重新访问:http://localhost:8080/springmybatis/emp/empList

打印员工信息

# springboot.jpg 图片没有打印该处传参时不宜用 “/**”,改为“/my/*”:
registry.addResourceHandler("/my/*").addResourceLocations("classpath:/mysource/");

05 重启服务,访问:
# 1. http://localhost:8080/springmybatis/emp/empList
打印图片
打印员工信息

# 2. http://localhost:8080/springmybatis/my/wu.gif
打印 “悟”图片

06 成功,完成!

设置默认路径映射

到本章为止,还没有解决默认映射的问题,比如 /、/index、/index.html 默认映射到首页,先看以下步骤:
01 在person/jack.config/MyConfig 重写addViewControllers() 方法:
@Configuration
public class MyConfig extends WebMvcConfigurerAdapter {
    ……
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index");
        registry.addViewController("/index").setViewName("index");
        registry.addViewController("/index.html").setViewName("index");
        super.addViewControllers(registry);
    }
}

02 在 templates 目录下新建index.html 模板:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8"/>
    <title>Title</title>
</head>
<body>
    <h1>首页</h1>
</body>
</html>

03 重启服务,访问:
# 访问:http://localhost:8080/springmybatis/,页面打印
首页

# 访问:http://localhost:8080/springmybatis/index,页面打印
首页

# 访问:http://localhost:8080/springmybatis/index.html,页面打印
首页

# 测试,成功!

04 总结:设置默认映射,即在有@Configuration 注解修饰的继承了WebMvcConfigurerAdapter超类的类中重写addViewControllers() 方法,通过ViewControllerRegistry 对象调用addViewController()方法设置对应的映射即可!

本章,完!

----------------------------
原文链接:https://www.jianshu.com/p/0f681998a2fb

程序猿的技术大观园:www.javathinker.net
  Java面向对象编程-->Java常用类(上)
  JavaWeb开发-->JavaWeb应用入门(Ⅱ)
  JSP与Hibernate开发-->映射一对多关联关系
  Java网络编程-->Java反射机制
  精通Spring-->
  Vue3开发-->Vue组件开发高级技术
  Spring Boot 入门,用 Spring Boot 写第一个 HelloWorld 程序
  MessagePack反序列化使用示例
  Redis 超详细总结笔记
  Spring boot参考指南
  git 仓库常用指令
  99%的人都能看懂的“熔断”以及最佳实践
  springmvc处理异步请求的示例
  Spring配置中bean元素的id和name属性的区别
  Spring数据验证 中@NotNull, @NotEmpty和@NotBlank之间的区别
  Spring Boot和Feign中使用Java 8时间日期API(LocalDate等)...
  RESTful API 设计最佳实践
  中央厨房订单管理系统,引入ActiveMQ消息队列,平滑处理高峰...
  写给新手的Spring Cloud的微服务入门教程
  Spring5新特性之日志体系
  Java核心库实现AOP过程
  更多...
 IPIP: 已设置保密
楼主      
1页 0条记录 当前第1
发表一个新主题 开启一个新投票 回复文章


中文版权所有: JavaThinker技术网站 Copyright 2016-2026 沪ICP备16029593号-2
荟萃Java程序员智慧的结晶,分享交流Java前沿技术。  联系我们
如有技术文章涉及侵权,请与本站管理员联系。