在编写接口中,为了安全起见,会将报文进行加密处理,如果每个返回报文都在controller处进行加密,当加密方式发生变化或多渠道接入返回不同密文时,改动较为繁琐,通过集成FastJsonHttpMessageConverter将返回报文可统一加密处理。
引入fastjson工具包
<!-- fastjson json工具 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.31</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.3</version>
</dependency>
自定义解析类,主要用于对返回的json串进行处理
MyFastJsonHttpMessageConverter
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.converter.HttpMessageNotWritableException;
import java.io.IOException;
/**
*
* 自定义解析类,用于对返回的json串进行处理,
* 加密
*
* @author javiner
* @date 2021/6/21 14:54.
*/
public class MyFastJsonHttpMessageConverter extends FastJsonHttpMessageConverter {
@Override
protected void writeInternal(Object obj, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
String json = JSONObject.toJSONString(obj);
json += "我加密了哦";
outputMessage.getBody().write(json.getBytes());
//super.writeInternal(obj, outputMessage);
}
}
编写MyWebMvcConfigurerAdpter
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author javiner
* @date 2021/6/21 14:43.
*/
@Configuration
@EnableWebMvc
public class MyWebMvcConfigurerAdpter extends WebMvcConfigurerAdapter {
/***
* 设置跨域访问
* @author pjw
* @date 2018/9/28 12:24
* param: [registry]
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
super.addCorsMappings(registry);
}
/**
* 配置fastJson
*
* @param converters
*/
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
MyFastJsonHttpMessageConverter fastConverter = new MyFastJsonHttpMessageConverter();
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
fastConverter.setFastJsonConfig(fastJsonConfig);
//处理中文乱码问题
List<MediaType> fastMediaTypes = new ArrayList<>();
fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
fastConverter.setSupportedMediaTypes(fastMediaTypes);
converters.add(fastConverter);
super.configureMessageConverters(converters);
}
}
在MyFastJsonHttpMessageConverter类中进行json加密处理