springboot搭建web(静态资源访问)(三)

来源:互联网 发布:无法连接到数据库 编辑:程序博客网 时间:2024/05/16 09:24

一、关于静态资源 :
默认情况下,Spring Boot从classpath下的/static(/public,/resources或/META-INF/resources)文件夹,或从ServletContext根目录提供静态内容。这是通过Spring MVC的ResourceHttpRequestHandler实现的,你可以自定义WebMvcConfigurerAdapter并覆写addResourceHandlers方法来改变该行为(加载静态文件)。
二、在之前搭建基础上在classpath下创建文件目录,如下图示
这里写图片描述
通过文件访问地址可以直接访问文件,
这里写图片描述
三、修改index.html页面

<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Insert title here</title></head><body>    Hello world!<br>    <img alt="static下" src="${rc.contextPath}/风景1.jpg"><br>    <img alt="resources下" src="${rc.contextPath}/风景2.jpg"><br>    <img alt="public下" src="${rc.contextPath}/风景3.jpg"><br>    <img alt="META-INF下" src="${rc.contextPath}/风景4.jpg"><br></body></html>

访问index.html页面链接静态资源

在单机web应用中,容器会启动默认的servlet,并用它加载ServletContext根目录下的内容以响应那些Spring不处理的请求。大多数情况下这都不会发生(除非你修改默认的MVC配置),因为Spring总能够通过DispatcherServlet处理这些请求。

四、可以设置spring.resources.staticLocations属性自定义静态资源的位置(配置一系列目录位置代替默认的值),如果你这样做,默认的欢迎页面将从自定义位置加载,所以只要这些路径中的任何地方有一个index.html,它都会成为应用的主页

1)在classpath下创建文件
这里写图片描述
2)在application.properties文件中配置

spring.resources.staticLocations=classpath:/content/

3)在index.html新增图片链接

<img alt="自定义content下" src="${rc.contextPath}/图片5.jpg">```4)![这里写图片描述](http://img.blog.csdn.net/20170218140726839?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdTAxMzUxMjAxNA==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)五、通过自定义WebMvcConfigurerAdapter并覆写addResourceHandlers方法来改变该行为(加载静态文件)1)创建文件MyWebAppConfigurer.java

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 MyWebAppConfigurer extends WebMvcConfigurerAdapter {

@Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry) {    registry.addResourceHandler("/myresources/**").addResourceLocations("classpath:/myresources/");    super.addResourceHandlers(registry);}

}

2)index.html

<img alt="java自定义文件myresources下" src="${rc.contextPath}/myresources/图片6.jpg">

这样配置方式不会覆盖默认加载静态资源文件夹,即默认的加载静态资源目录依然可以使用。

0 0
原创粉丝点击