SpringMVC回顾
xml配置
在SpringMVC中,静态资源会被拦截,需要添加额外配置放行。
/** ( Ant风格的路径匹配符 )表示可以匹配任意层级的路径,因此上面的代码也可以像下面这样简写:
java配置
SpringMVC 的配置除了在XML中配置,也可以在 Java 代码中配置 , 在 Java 代码中配置 , 只需要自定义一个继承自 WebMvcConfigurationSupport 的类:
@Configuration
@ComponentScan(basePackages = "com.lh.ssm")
public class SpringMVCConfig extends WebMvcConfigurationSupport {
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations("/");
}
}
在Spring Boot 中的配置
默认配置
在 Spring Boot 中,默认情况下,一共有 5 个位置可以放静态资源, 优先级 自上而下
classpath:/META-INF/resources/
classpath:/resources/
classpath:/static/ (常用)
classpath:/public/
/ 在 Spring Boot 项目中,默认是没有 webapp 这个目录的 ,我们可以自己添加 (例如在需要使用JSP的时候) / 其实就是表示 webapp 目录中的静态资源也不被拦截。
自定义配置
如果不想将资源放在系统默认位置上 ,可以通过 application.properties 来定义,也可以在 Java 代码中来定义 。
application.properties
spring.resources.static-locations=classpath:/ #资源位置
spring.mvc.static-path-pattern=/** #请求 URL 规则
Java 代码定义
方式和 Java 配置的 SSM 类似
@Configuration
public class WebMVCConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations("classpath:/aaa/");
}
}