- SpringBoot 设置全局跨域
- SpringBoot全局⽇期格式化
- SpringBoot 读取本地json
编写一个config:GlobalCorsConfig.java
package cn.kt.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class GlobalCorsConfig {
@Order(Ordered.HIGHEST_PRECEDENCE)
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
//默认拦截路径
registry.addMapping("
@JsonComponent
public class DateFormatConfig {
private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static class DateJsonSerializer extends JsonSerializer {
@Override
public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
jsonGenerator.writeString(dateFormat.format(date));
}
}
public static class DateJsonDeserializer extends JsonDeserializer {
@Override
public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
try {
return dateFormat.parse(jsonParser.getText());
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
}
}
配置完,在返回接口给前端时,所有的时间都会被Jackson接管,然后实现序列化和反序列化格式化时间。
效果如下:
请求后,时间被格式化
参考:https://wenku.baidu.com/view/b50330fc53e2524de518964bcf84b9d528ea2c15.html
在SrpingBoot中读取文件的方法一般可以使用文件流,直接逐行读取,然而这种方法使用的路径是相对路径或者绝对路径,在SpringBoot项目打包后,该相对路径或者绝对路径就会失效,导致找不到对应的文件,这种情况可以使用ClassPathResource进行流处理。
- 第一种直接流逐行读取(项目打包后路径会失效)
File file = null;
StringBuilder sb = new StringBuilder();
// 读取json文件
try {
file = ResourceUtils.getFile("classpath:static/InstructDetail.json");
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8));
String readLine = null;
while ((readLine = br.readLine()) != null) {
sb.append(readLine);
}
} catch (IOException e) {
e.printStackTrace();
}
JSONObject result = JSONObject.parseObject(sb.toString(), Feature.OrderedField);
- 使用ClassPathResource对文件进行流处理后读取(项目打包后路径不会失效)
ClassPathResource resource = new ClassPathResource("static/InstructDetail.json");
String jsonStr = "";
try {
InputStream inputStream = resource.getInputStream();
Reader reader = new InputStreamReader(inputStream, "utf-8");
int ch = 0;
StringBuffer sb = new StringBuffer();
while ((ch = reader.read()) != -1) {
sb.append((char) ch);
}
reader.close();
jsonStr = sb.toString();
} catch (IOException e) {
e.printStackTrace();
}
JSONObject result = JSONObject.parseObject(jsonStr, Feature.OrderedField);



