业务场景:客户端把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 inputMessa