springboot踩坑三:配置静态资源访问与本地路径的映射

1.首先,用@value取properties中的中文数据时,会出现乱码问题

解决办法:

在application主类中增加这个:

@PropertySource(value="classpath:application.properties",encoding = "UTF-8") //需要单独指定这个,不然取出值会中文乱码

 2.项目中上传文件保存后返回一个相对路径,用户用ip+端口+路径访问程序时需要将 这个路径映射到文件实际的物理路径上,才能取到这个文件,以前在tomcat中可以配置这个,但springboot中只能通过config配置了

解决办法:

配置一下路径

        registry.addResourceHandler("/attachments/**").addResourceLocations("file:E:/东信svn项目/enterprise/code/attachments/");

这样就可以把url路径有/attachments/的内容映射到  file:E:/东信svn项目/enterprise/code/attachments/ 文件夹下

访问路径:http://localhost:8084/Enterprise/attachments/chatImg/7129735.jpg

文件目录:

需要注意的是:我的项目上下文虽然起名为enterprise 了,但是 

registry.addResourceHandler("/attachments/**")

这里不要写上下文,从上下文后面开始,否则会报404

这个配置类全部内容:

package com.bomc.enterprise.config;

import com.bomc.enterprise.interceptor.LoginInterceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Value("${server.servlet.context-path}")
    private String contextPath;
    //不注册这个在过滤器中 service将报空
    @Bean
    public LoginInterceptor loginInterceptor(){
        return new LoginInterceptor();
    }

    //添加拦截器方法
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //添加拦截路径
        String[] addPathPatters={
                "/**"
        };
        //添加不拦截路径
        String[] excludePathPatters={
                "/", "/login/login", "/login/loginPage","/login/register",
                "/**/*.css", "/**/*.js", "/**/*.png", "/**/*.jpg",
                "/**/*.jpeg", "/**/*.gif", "/**/fonts/*", "/**/*.svg",
                "/**/*.ttf","/**/*.woff","/**/*.eot","/**/*.otf","/**/*.woff2"
        };
        //注册登录拦截器
        registry.addInterceptor(loginInterceptor()).addPathPatterns(addPathPatters).excludePathPatterns(excludePathPatters);
        //如果多条拦截器则增加多条
    }

    //添加放行静态资源
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        //文件磁盘图片url 映射
        //配置server虚拟路径,handler为前台访问的目录,locations为files相对应的本地路径
        registry.addResourceHandler("/attachments/**").addResourceLocations("file:E:/东信svn项目/enterprise/code/attachments/");
        //配置静态文件路径,与上面并不冲突
        registry.addResourceHandler("/**").addResourceLocations("classpath:/META-INF/resources/");


    }


}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

豆趣编程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值