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("/**") //表示允许那些原始域进行跨域访问,这里"*"表示允许任意网站,实际开发建议修改为配置项。 .allowedOrigins("*") //表示是否允许客户端发送Cookie等凭证信息,这里"true"表示支持发送,涉及登陆此处必须开启。 .allowCredentials(true) //表示允许原始域发起哪些请求方式,这里"*"表示支持GET/POST等全部提交方式。 .allowedMethods("*") //表示允许原始域携带哪些请求头 这里"*"表示支持全部请求头 .allowedHeaders("*") //表示允许暴露哪些响应头,这里特指那些非简单的头部信息,所以用"*"无效。 .exposedHeaders(HttpHeaders.AUTHORIZATION); } }; } }
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进行流处理。
-
第一种直接流逐行读取(项目打包后路径会失效)
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);