SpringBoot对静态资源的支持以及很重要的一个类WebMvcConfigurerAdapter。
正文
前面章节我们也有简单介绍过SpringBoot中对静态资源的默认支持,今天详细的来介绍下默认的支持,以及自定义扩展如何实现。
默认资源映射
Spring Boot 默认为我们提供了静态资源处理,使用 WebMvcAutoConfiguration 中的配置各种属性。
建议大家使用Spring Boot的默认配置方式,提供的静态资源映射如下:
classpath:/META-INF/resources
classpath:/resources
classpath:/static
classpath:/public
静态资源的映射路径,优先级顺序为:META-INF/resources > resources > static > public
# 默认值为
spring.mvc.static-path-pattern=
# 默认值为 classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/
spring.resources.static-locations=这里设置要指向的路径,多个使用英文逗号隔开
我们可以通过修改spring.mvc.static-path-pattern来修改默认的映射,例如我改成/dudu/**,那运行的时候访问 http://lcoalhost:8080/dudu/index.html 才对应到index.html页面。
接管Spring Boot的Web配置
如果Spring Boot提供的Sping MVC不符合要求,则可以通过一个配置类(注解有@Configuration的类)加上@EnableWebMvc注解来实现完全自己控制的MVC配置。
当然,通常情况下,Spring Boot的自动配置是符合我们大多数需求的。在你既需要保留Spring Boot提供的便利,有需要增加自己的额外的配置的时候,可以定义一个配置类并继承WebMvcConfigurerAdapter,无需使用@EnableWebMvc注解。
这里我们提到这个WebMvcConfigurerAdapter这个类,重写这个类中的方法可以让我们增加额外的配置,这里我们就介绍几个常用的。
自定义资源映射addResourceHandlers
比如,我们想自定义静态资源映射目录的话,只需重写addResourceHandlers方法即可。
@Configuration
public class MyWebMvcConfigurerAdapter extends WebMvcConfigurerAdapter {
/**
* 配置静态访问资源
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/my/**").addResourceLocations("classpath:/my/");
super.addResourceHandlers(registry);
}
}
通过addResourceHandler添加映射路径,然后通过addResourceLocations来指定路径。我们访问自定义my文件夹中的elephant.jpg 图片的地址为 http://localhost:8080/my/elephant.jpg
如果你想指定外部的目录也很简单,直接addResourceLocations指定即可,代码如下:
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/my/**").addResourceLocations("file:E:/my/");
super.addResourceHandlers(registry);
}
addResourceLocations指的是文件放置的目录,addResoureHandler指的是对外暴露的访问路径
页面跳转addViewControllers
以前写SpringMVC的时候,如果需要访问一个页面,必须要写Controller类,然后再写一个方法跳转到页面,感觉好麻烦,其实重写WebMvcConfigurerAdapter中的addViewControllers方法即可达到效果了
/**
* 以前要访问一个页面需要先创建个Controller控制类,再写方法跳转到页面
* 在这里配置后就不需要那么麻烦了,直接访问http://localhost:8080/toLogin就跳转到login.jsp页面了
* @param registry
*/
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/toLogin").setViewName("login");
super.addViewControllers(registry);
}
值的指出的是,在这里重写addViewControllers方法,并不会覆盖WebMvcAutoConfiguration中的addViewControllers(在此方法中,Spring Boot将“/”映射至index.html),这也就意味着我们自己的配置和Spring Boot的自动配置同时有效,这也是我们推荐添加自己的MVC配置的方式。