转:https://www.cnblogs.com/gllegolas/p/12452841.html
ResponseBodyAdvice是spring4.1的新特性,其作用是在响应体写出之前做一些处理,比如,修改返回值、加密等。
ResponseBodyAdvice接口是在Controller执行return之后,在response返回给浏览器或者APP客户端之前,执行的对response的一些处理。可以实现对response数据的一些统一封装或者加密等操作。
该接口一共有两个方法:
@Override
//判断是否要执行beforeBodyWrite方法,true为执行,false不执行
public boolean supports(MethodParameter returnType, Class converterType) {
return false;
}
@Override
//对response处理的执行方法
public Object beforeBodyWrite(Object body, MethodParameter returnType,
MediaType selectedContentType, Class selectedConverterType,
ServerHttpRequest request, ServerHttpResponse response) {
return null;
}
通过supports方法,我们可以选择哪些类,或者哪些方法要对response进行处理,其余的则不处理。
beforeBdoyWrite方法中,为对response处理的具体代码。
ResponseBodyAdvice 接口源码:
package org.springframework.web.servlet.mvc.method.annotation;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
/**
* Allows customizing the response after the execution of an {@code @ResponseBody}
* or an {@code ResponseEntity} controller method but before the body is written
* with an {@code HttpMessageConverter}.
Implementations may be may be registered directly with
* {@code RequestMappingHandlerAdapter} and {@code ExceptionHandlerExceptionResolver}
* or more likely annotated with {@code @ControllerAdvice} in which case they
* will be auto-detected by both.
*
* @author Rossen Stoyanchev
* @since 4.1
*/
public interface ResponseBodyAdvice {
/**
* 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> 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
*/
T beforeBodyWrite(T body, MethodParameter returnType, MediaType selectedContentType,
Class> selectedConverterType,
ServerHttpRequest request, ServerHttpResponse response);
}
实例:有一个工程,这个工程中的一个Controller类,返回参数为OutputObject(一个自定义的javaBean),我们要通过ResponseBodyAdvice,对该类的所有方法返回的OutputObject中的部分数据进行统一加密处理。
package com.cmos.edcreg.web.intercepter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import com.alibaba.fastjson.JSON;
import com.cmos.edcreg.beans.common.OutputObject;
import com.cmos.edcreg.utils.StringUtil;
import com.cmos.edcreg.utils.des.DesSpecial;
import com.cmos.edcreg.utils.enums.ReturnInfoEnums;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* 对响应报文统一处理,对bean内容进行加密
* @author qiaozhong
*/
@Component
//声明该类要处理的包路径
@ControllerAdvice("com.cmos.edcreg.web.controller")
public class ResponseAdvice implements ResponseBodyAdvice {
private final Logger logger = LoggerFactory.getLogger(ResponseAdvice.class);
/*
* 对response处理的具体方法
* arg0为返回的报文体,arg0为org.json.jsonObject,使用alibaba.json方法转换时候报错了
*/
@Override
public Object beforeBodyWrite(Object arg0, MethodParameter arg1,
MediaType arg2, Class arg3, ServerHttpRequest arg4,
ServerHttpResponse arg5) {
OutputObject out = new OutputObject();
try {
//arg0转换为OutputObject类型
ObjectMapper objectMapper=new ObjectMapper();
out = objectMapper.readValue(org.json.JSONObject.valueToString(arg0), OutputObject.class);
//获取加密密钥
String oldEncryptKey = out.getBean().get("oldEncryptKey");
//获取加密字符串
DesSpecial des = new DesSpecial();
String encryptData = des.strEnc(JSON.toJSONString(out.getBean()), oldEncryptKey, null, null);
//封装数据(清除原来数据,放入加密数据)
out.getBean().clear();
out.getBean().put("data", encryptData);
return out;
} catch (Exception e) {
logger.error("返回报文处理出错", e);
out.setReturnCode(ReturnInfoEnums.PROCESS_ERROR.getCode());
out.setReturnMessage(ReturnInfoEnums.PROCESS_ERROR.getMessage());
return out;
}
}
/*
* 选择哪些类,或哪些方法需要走beforeBodyWrite
* 从arg0中可以获取方法名和类名
* arg0.getMethod().getDeclaringClass().getName()为获取方法名
*/
@Override
public boolean supports(MethodParameter arg0, Class arg1) {
if("com.cmos.edcreg.web.controller.GdH5AppointmentActiveVideoNewController".equals(arg0.getMethod().getDeclaringClass().getName())){
return true;
}else{
return false;
}
}
}