目录
- SpringBoot访问外部文件及默认路由
- 1 新增配置类
- 2 访问
- springboot访问项目外部文件配置及失效问题
- springboot映射项目外部资源
- 下面是访问结果(请忽略掉乱码问题)
SpringBoot访问外部文件及默认路由
1 新增配置类
package com.pibigstar.common.config;
import org.springframe编程客栈work.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import com.pibigstar.common.Constant;
@Configuration
public class WebConfig implements WebMvcConfigurer{
/**
* 访问外部文件配置,访问D盘下文件
*/
@Override
public void addResourceHandjavascriptlers(ResourceHandlerRegistry registry) {
//配置server虚拟路径,handler为JSP中访问的目录,locations为files相对应的本地路径
registry.addResourceHandler("/files/**").addResourceLocations("file:///D:upload/");
}
/**
* 配置默认路由
*/
@Override
public void addViewControllers(ViewControllerRegistry registry) {
//将浏览器的默认行为重定向到主页
registry.addViewController("/").setViewName("redirect:/index.htm");
//测试页面
registry.addViewController("/test.htm").setViewName("/test.jsp");
}
}
2 访问
我们将test.jpg文件上传到D盘的upload文件夹后,那么在页面端访问则通过:localhost:8080/files/test.jpg
springboot访问项目外部文件配置及失效问题
springboot映射项目外部资源
配置文件:
cbs: filePath: file:///
配置类:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
/**
* @description:配置访问外部文件
* @author: Administrator
* @date: 2019-07-10 16:17
*/
@Configuration
public class WebConfig extends WebMvcConfigurationSupport {
@Value("${cbs.filePath}")
private String filePath;//文件地址
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
编程客栈 System.out.println("文件路径=="+filePath);
registry.addResourceHandler("/appFile/**").addResourceLocations(filePath);
super.addResourceHandlers开发者_Go入门(registry);
}
}
地址:http://localhost:8080/appFile/D:/tmp/app/1.txt

访问的时候把 http://localhost:javascript8080/appFile/ 替换成 file:///
也就是file:///D:/tmp/http://www.devze.comapp/1.txt
下面是访问结果(请忽略掉乱码问题)

但是不知道为什么配置类继承WebMvcConfigurerAdapter和实现WebMvcConfigurer 接口都没有用,继承 WebMvcConfigurationSupport类才生效
以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。
加载中,请稍侯......
精彩评论