网上的配置都是xml配置的,这边项目用的是实现WebMvcConfigurationSupport配置类的方法,搞了半天才搞定,记录一下,方便后来人。
本来访问静态资源应该是很容易的,但是由于实现了WebMvcConfigurationSupport类,Spring默认的配置都没了,需要自己手动添加。在WebMvcConfigurationSupport实现类中加入以下代码即可。
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
String staticPath=Constants.getStaticResourcePath();
if (!registry.hasMappingForPattern("/webConsole/**")) {
//url
registry.addResourceHandler("/webConsole/**")
//映射的位置
.addResourceLocations(staticPath);
}
super.addResourceHandlers(registry);
}
如果要访问jar包内的目录,staticPath可以直接写成"classpath:xxxxx"
如果要访问磁盘的文件
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/files/**")
//win环境下参数应该是“file:///C:/opt/files/”这种格式,注意最后的"/"不能少
//Linux下获取路径的斜杠方向和win不一样,需注意
.addResourceLocations("file:/opt/files/");
}
踩坑的地方
用sweager自动生成的代码还有两个类
package io.swagger.configuration;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
public class WebMvcConfiguration extends WebMvcConfigurationSupport {
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
package io.swagger.configuration;
@Configuration
@ComponentScan(basePackages = "com.trs.xcrawler.handler")
@EnableWebMvc
@EnableSwagger2 //Loads the spring beans required by the framework
@PropertySource("classpath:swagger.properties")
@Import(SwaggerDocumentationConfig.class)
public class SwaggerUiConfiguration extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (!registry.hasMappingForPattern("/webjars/**")) {
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
if (!registry.hasMappingForPattern("/**")) {
registry.addResourceHandler("/**").addResourceLocations(RESOURCE_LOCATIONS);
}
}
}
删掉了没用的代码方便阅读。
坑在于,@EnableWebMvc注解也会取消掉SpringMvc的一堆配置,导致request.getAttribute()拿不到值。且WebMvcConfigurationSupport 和WebMvcConfigurerAdapter 会相互冲突,仅会加载一个。