static目錄的訪問
情景
- 項目中需要做一個模板文件下載的功能,可以採用將文件流寫入response,然後返回response這種方式。但本次直接使用的a標籤,地址指向目標文件路徑,從而實現文件下載。
問題
- 於是需要訪問靜態文件,springboot中將靜態文件放置在resource下的static中,templates用來存放html頁面文件。但訪問的時候,直接報404。靜態文件訪問不到。
解決方式
需要加一個攔截器,將對應的請求映射到靜態目錄中。
@Configuration
@EnableWebMvc
@ComponentScan
public class InterceptorConfiger implements WebMvcConfigurer {
private ApplicationContext applicationContext;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations(ResourceUtils.CLASSPATH_URL_PREFIX+"/static/");
registry.addResourceHandler("/templates/**").addResourceLocations(ResourceUtils.CLASSPATH_URL_PREFIX+"/templates/");
}
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
這樣靜態目錄下的資源文件就可以直接被瀏覽器訪問到。
引發問題
添加攔截器後,發現後臺傳向前臺的時間類型數據,沒有被json格式化,直接顯示成了毫秒數。而時間格式化,是在application.yml中配置的。
spring:
application:
name: xxx
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
也就是該配置失效了。
解決問題2
雖然不知道具體原理是什麼,但是測試發現就是添加了攔截器所以導致時間格式轉換除了問題。解決方案便是在攔截器中添加對時間格式的處理。
@Configuration
@EnableWebMvc
@ComponentScan
public class InterceptorConfiger implements WebMvcConfigurer {
private ApplicationContext applicationContext;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations(ResourceUtils.CLASSPATH_URL_PREFIX+"/static/");
registry.addResourceHandler("/templates/**").addResourceLocations(ResourceUtils.CLASSPATH_URL_PREFIX+"/templates/");
}
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder()
.indentOutput(true)
.dateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))
.modulesToInstall(new ParameterNamesModule()); //JDK8 新特性,可選擇多個模塊
converters.add(new MappingJackson2HttpMessageConverter(builder.build()));
}
}
如此配置後,返回數據的時間格式以正確的json格式展示。
問題3
然而問題並沒有結束,靜態文件可以正常下載,服務器返回數據格式也正確,但是下載下來的文件打不開。(一臉懵逼)點開下載的excel文件,提示文件破損。原來是maven打包配置出了問題。詳情參見
於是將maven中的filter改爲false即可。
<build>
<finalName>${project.artifactId}</finalName>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
<include>**/*.sql</include>
</includes>
</resource>
<resource>
<directory>src/main/resources/</directory>
<filtering>false</filtering>
<includes>
<include>**/*.yml</include>
<include>**/*.properties</include>
<include>**/*.ftl</include>
<include>**/*.xlsx</include>
<include>**/*.xls</include>
<include>**/*.json</include>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>