SpringBoot访问外部文件及默认路由问题

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

SpringBoot访问外部文件及默认路由问题

跟派大星学编程   2022-11-19 我要评论

SpringBoot访问外部文件及默认路由

1 新增配置类

package com.pibigstar.common.config;

import org.springframework.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 addResourceHandlers(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(registry);
    }
}

地址:http://localhost:8080/appFile/D:/tmp/app/1.txt

访问的时候把 http://localhost:8080/appFile/ 替换成 file:///

也就是file:///D:/tmp/app/1.txt

下面是访问结果(请忽略掉乱码问题)

但是不知道为什么配置类继承WebMvcConfigurerAdapter和实现WebMvcConfigurer 接口都没有用,继承 WebMvcConfigurationSupport类才生效

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们