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


    }


}

 

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