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/");


    }


}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章