欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

在SpringBoot中静态资源访问方法

时间:2022-04-14 09:43:23|栏目:JAVA代码|点击:

一、概述

springboot 默认静态资源访问的路径为:/static 或 /public 或 /resources 或 /META-INF/resources 这样的地址都必须定义在src/main/resources目录文件中,这样可以达到在项目启动时候可以自动加载为项目静态地址目录到classpath下 ,静态访问地址其实是使用 ResourceHttpRequestHandler 核心处理器加载到WebMvcConfigurerAdapter进行对addResourceHandlers方法进行覆盖.将静态访问目录进行重新定义。我们也可以实现其中方法,手动指定静态访问路径通过继承WebMvcConfigurerAdapter重写内部方法addResourceHandlers也可以达到我们想要的效果。

第一种方式 : 放在src/main/webapp目录下

放在webapp目录下的静态资源是可以直接访问的

这里写图片描述

user.html

这里写图片描述

2.png

这里写图片描述

在user.html中引用2.png

这里写图片描述

第二种方式:放在classpath下

ResourceProperties中的说明

org.springframework.boot.autoconfigure.web.ResourceProperties
 private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
   "classpath:/META-INF/resources/", "classpath:/resources/",
   "classpath:/static/", "classpath:/public/" };

静态资源默认放在classpath路径下:Defaults to classpath:[/META-INF/resources/,/resources/, /static/, /public/] plus context:/ (the root of the servlet context).

这里写图片描述

person/index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link href="/css/main.css" rel="external nofollow" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="/js/main.js"></script>
<script type="text/javascript">
 sayHello();
</script>
</head>
<body>
 <h3>person page HTML</h3>
</body>
</html>

这里写图片描述

通过修改配置项,设置静态资源的位置

application.properties
# 修改默认的静态资源存放目录
spring.resources.static-locations=classpath:/web/

这里写图片描述

总结

上一篇:Spring中的PathVariable注释解析

栏    目:JAVA代码

下一篇:详解Spring Boot 添加JSP支持

本文标题:在SpringBoot中静态资源访问方法

本文地址:http://www.codeinn.net/misctech/199160.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有