zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Spring学习笔记(三十五)——小技巧:配置全局跨域、全局⽇期格式化、读取本地json

2023-06-13 09:11:07 时间

SpringBoot 设置全局跨域

编写一个config:GlobalCorsConfig.java

package cn.kt.springbootuploadmaster.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * Created by tao.
 * Date: 2022/6/29 13:18
 * 描述:
 */
@Configuration
public class GlobalCorsConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowCredentials(true)
                .allowedHeaders("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("Authorization", "Cache-Control", "Content-Type")
                .maxAge(3600);
    }
}

SpringBoot全局⽇期格式化

根据官⽅⽂档 Custom JSON Serializers and Deserializers ,想要接管Jackson的JSON的序列化和反序列化,只需通过注解 @JsonComponent 来声明其静态内部类即可。

⾸先根据项⽬要求提供⾃定义的⽇期序列化器和反序列化器,其中包括:

  • DateJsonSerializer extends JsonSerializer 表⽰将Date格式化为⽇期字符串。
  • DateJsonDeserializer extends JsonDeserializer 表⽰将⽇期字符串解析为Date⽇期。

在config中配置DateFormatConfig.java,代码如下:

package cn.kt.config;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.springframework.boot.jackson.JsonComponent;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 全局日期格式化
 */
@JsonComponent
public class DateFormatConfig {

    private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 日期格式化
     */
    public static class DateJsonSerializer extends JsonSerializer<Date> {
        @Override
        public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
            jsonGenerator.writeString(dateFormat.format(date));
        }
    }

    /**
     * 解析日期字符串
     */
    public static class DateJsonDeserializer extends JsonDeserializer<Date> {
        @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

SpringBoot 读取本地json

在SrpingBoot中读取文件的方法一般可以使用文件流,直接逐行读取,然而这种方法使用的路径是相对路径或者绝对路径,在SpringBoot项目打包后,该相对路径或者绝对路径就会失效,导致找不到对应的文件,这种情况可以使用ClassPathResource进行流处理。

  1. 第一种直接流逐行读取(项目打包后路径会失效)
    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);

 

  1. 使用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);