栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

目录
  • SpringBoot 设置全局跨域
  • SpringBoot全局⽇期格式化
  • SpringBoot 读取本地json

SpringBoot 设置全局跨域

编写一个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

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);
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/878430.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号