ResponseBodyAdvice 对服务器返回值进行封装

本文详细介绍了Spring WebFlux中ResponseBodyAdvice接口的使用方法,包括如何通过supports方法筛选响应及beforeBodyWrite方法对响应体进行处理。

1.实现接口中的方法

 *
 * @author Rossen Stoyanchev
 * @since 4.1
 */
public interface ResponseBodyAdvice<T> {

	/**
	 * Whether this component supports the given controller method return type
	 * and the selected {@code HttpMessageConverter} type.
	 * @param returnType the return type
	 * @param converterType the selected converter type
	 * @return {@code true} if {@link #beforeBodyWrite} should be invoked;
	 * {@code false} otherwise
	 */
	boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType);

	/**
	 * Invoked after an {@code HttpMessageConverter} is selected and just before
	 * its write method is invoked.
	 * @param body the body to be written
	 * @param returnType the return type of the controller method
	 * @param selectedContentType the content type selected through content negotiation
	 * @param selectedConverterType the converter type selected to write to the response
	 * @param request the current request
	 * @param response the current response
	 * @return the body that was passed in or a modified (possibly new) instance
	 */
	@Nullable
	T beforeBodyWrite(@Nullable T body, MethodParameter returnType, MediaType selectedContentType,
			Class<? extends HttpMessageConverter<?>> selectedConverterType,
			ServerHttpRequest request, ServerHttpResponse response);

}

2.方法讲解
supports对你需要进行拦截的response进行判断筛选,返回true则进行拦截反之放行,
beforeBodyWrite对supports进行拦截的response进行处理,封装你需要的类型参数,加密等等。

private static Class<?>[] responseType = { Collection.class, String.class, Integer.class, Date.class };

	@Override
	public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
		if (!returnType.getContainingClass().getPackage().getName().startsWith(ProjectConstant.API_PACKAGE))
			return false;
		for (int i = 0; i < responseType.length; i++) {
			if (responseType[i].isAssignableFrom(returnType.getMethod().getReturnType())
					|| returnType.getMethod().getReturnType().isArray()) {
				return true;
			}
		}
		return false;
	}

	@Override
	public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
			Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
			ServerHttpResponse response) {

		if (Collection.class.isAssignableFrom(returnType.getMethod().getReturnType())
				|| returnType.getMethod().getReturnType().isArray()) {
			// 数组
			if (MediaType.TEXT_HTML.equals(selectedContentType) || MediaType.TEXT_PLAIN.equals(selectedContentType))
				if (!Stream.of(returnType.getMethod().getAnnotations()).anyMatch(a -> {
					if (a instanceof RequestMapping) {
						return !Objs.isEmpty(((RequestMapping) a).produces());
					}
					return false;
				})) {
					response.getHeaders()
							.setContentType(MediaType.parseMediaType(MediaType.APPLICATION_JSON_UTF8_VALUE));
					return JSONObject.toJSONString(Pages.builder((Collection<?>) body));
				}
			return Pages.builder((Collection<?>) body);
		}

		JSONObject js = new JSONObject();
		js.put(AppEnum.status.getValue(), true);
		js.put(AppEnum.message.getValue(), body);
		if (MediaType.TEXT_HTML.equals(selectedContentType) || MediaType.TEXT_PLAIN.equals(selectedContentType)) {
			if (!Stream.of(returnType.getMethod().getAnnotations()).anyMatch(a -> {
				if (a instanceof RequestMapping) {
					return !Objs.isEmpty(((RequestMapping) a).produces());
				}
				return false;
			}))
				response.getHeaders().setContentType(MediaType.parseMediaType(MediaType.APPLICATION_JSON_UTF8_VALUE));
			return js.toString();
		}
		return js;
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值