SpringMvc 访问静态资源

网上的配置都是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 会相互冲突,仅会加载一个。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值