业务场景:客户端把json数据进行加密后,编码成Base64字符串,提交给服务器。服务器再进行解密。
使用 @RequestBodyAdvice
,可以在不修改任何Controller
代码的前提下,轻松完成。
之前写过一篇帖子,使用@ResponseBodyAdvice统一对响应的数据进行处理。演示了,使用
ResponseBodyAdvice
统一对响应给客户的json进行AES加密。
RequestBodyAdvice 接口
这个接口定义了一系列的方法,它可以在请求体数据被HttpMessageConverter
转换前,后。执行一些逻辑代码。通常用来做解密。
import java.io.IOException;
import java.lang.reflect.Type;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.lang.Nullable;
public interface RequestBodyAdvice {
/**
* 该方法用于判断当前请求,是否要执行beforeBodyRead方法
* @param handler方法的参数对象
* @param handler方法的参数类型
* @param 将会使用到的Http消息转换器类类型
* @return 返回true则会执行beforeBodyRead
*/
boolean supports(MethodParameter methodParameter, Type targetType,
Class<? extends HttpMessageConverter<?>> converterType);
/**
* 在Http消息转换器执转换,之前执行
* @param 客户端的请求数据
* @param handler方法的参数对象
* @param handler方法的参数类型
* @param 将会使用到的Http消息转换器类类型
* @return 返回 一个自定义的HttpInputMessage
*/
HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter,
Type targetType, Class<? extends HttpMessageConverter<?>> converterType) throws IOException;
/**
* 在Http消息转换器执转换,之后执行
* @param 转换后的对象
* @param 客户端的请求数据
* @param handler方法的参数类型
* @param handler方法的参数类型
* @param 使用的Http消息转换器类类型
* @return 返回一个新的对象
*/
Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter,
Type targetType, Class<? extends HttpMessageConverter<?>> converterType);
/**
* 同上,不过这个方法处理的是,body为空的情况
*/
@Nullable
Object handleEmptyBody(@Nullable Object body, HttpInputMessage inputMessage, MethodParameter parameter,
Type targetType, Class<? extends HttpMessageConverter<?>> converterType);
}
核心的方法就是 supports
,该方法返回的boolean值,决定了是要执行 beforeBodyRead
方法。而我们主要的逻辑就是在beforeBodyRead
方法中,对客户端的请求体进行解密。
RequestBodyAdviceAdapter
实现 RequestBodyAdvice
接口的适配器抽象类
import java.io.IOException