使用@RequestBodyAdvice处理客户端的加密请求体

业务场景:客户端把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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值