ResponseBodyAdvice 接口概述
1、ResponseBodyAdvice 接口允许在执行 @ResponseBody 或 ResponseEntity 控制器方法之后,但在使用 HttpMessageConverter 写入响应体之前自定义响应,进行功能增强。通常用于 加密,签名,统一数据格式等。
2、ResponseBodyAdvice 接口一共有两个方法:
public interface ResponseBodyAdvice<T> {
/**
* 1、选择是否执行 beforeBodyWrite 方法,返回 true 执行,false 不执行.
* 2、通过 supports 方法,可以选择对哪些类或方法的 Response 进行处理,其余的
则不处理。
* @param returnType:返回类型
* @param converterType:转换器
* @return :返回 true 则下面的 beforeBodyWrite 执行,否则不执行
* /
boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType);
/**
* 对 Response 处理的具体执行方法
* @param body:响应对象(response)中的响应体
* @param returnType:控制器方法的返回类型
* @param selectedContentType:通过内容协商选择的内容类型
* @param selectedConverterType:选择写入响应的转换器类型
* @param request:当前请求
* @param response:当前响应
* @return :返回传入的主体或修改过的(可能是新的)主体
* /
@Nullable
T beforeBodyWrite(@Nullable T body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response);
}
ResponseBodyAdvice 快速使用
1、使用方式:自定义类实现 ResponseBodyAdvice 接口,然后在类上标记 @ControllerAdvice 或@RestControllerAdvice 注解即可自动识别并进行功能增强。
2、下面以对返回数据封装统一格式为例进行演示(注意仅对返回值为 ResponseEntity 或者是有@ResponseBody 注解的控制器方法进行拦截,@RestController 相当于是类中的所有方法上都加了 @ResponseBody)。
3、注意如果控制层目标方法往外抛出了异常,则不再进入 ResponseBodyAdvice
package com.gaoshan.handler.response;
import com.gaoshan.axe.Result;
import org.nutz.lang.Lang;
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;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
@RestControllerAdvice(basePackages = "com.gaoshan")
public class GlobalResponseHandler implements ResponseBodyAdvice<Object> {
List<String> ignorePaths = new ArrayList<>();
static final List<String> DEFAULT_IGNORED_PATH = Lang.list("/swagger-resources.*", "/v2/api-docs", "/actuator.*", "/testStr2");
public GlobalResponseHandler() {
if (ignorePaths == null || ignorePaths.isEmpty()) {
ignorePaths = DEFAULT_IGNORED_PATH;
}
ignorePaths.addAll(DEFAULT_IGNORED_PATH);
this.ignorePaths = ignorePaths;
}
@Override
public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
return true;
}
@Override
public Object beforeBodyWrite(Object body,
MethodParameter returnType,
MediaType selectedContentType,
Class<? extends HttpMessageConverter<?>> selectedConverterType,
ServerHttpRequest request,
ServerHttpResponse response) {
if (body instanceof Result || ignored(request.getURI().getRawPath())) {
return body;
}
// else if(body instanceof String){
// return JSON.toJSONString(Result.success(body));
// }
return Result.success(body);
}
/**
* @param path
* @return
*/
private boolean ignored(String path) {
return ignorePaths.stream().anyMatch(item -> Pattern.matches(item, path));
}
}
package com.gaoshan.verification.controller;
import com.gaoshan.verification.entity.ShowBarcode;
import com.gaoshan.verification.service.ITestService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
public class TestController{
private static final Logger LOGGER = LoggerFactory.getLogger(TestController.class);
@Autowired
private ITestService testService;
@RequestMapping(value = "/selectAll")
public List<ShowBarcode> selectAll() {
System.out.println("testService isAopProxy = " + AopUtils.isAopProxy(testService));
return testService.selectAll();
}
@GetMapping(value = "/testStr")
public String testStr() {
return "testService1";
}
@GetMapping(value = "/testStr2")
public String testStr2() {
return "testService2";
}
@RequestMapping(value = "/insert")
public int insert() {
return testService.insert(new ShowBarcode());
}
}
但是当返回值是一个String时,会报错com.gaoshan.axe.Result cannot be cast to java.lang.String。
原因是返回值是String,Spring会使用StringHttpMessageConverter来处理返回体,但是我们定义的统一返回处理类将返回值String,变成了Result.success((String)),是一个对象。导致类型转换失败了。具体的代码是:
父类AbstractHttpMessageConverter write时,会调子类StringHttpMessageConverter的addDefaultHeaders方法,注意父类处理的是一个泛型
而子类StringHttpMessageConverter接收的是String。就会报错了(此时,接收的是Result,是一个对象)。
原因就是原来返回值是一个String,统一处理后变为了一个对象Result。导致类型转换失败了。
解决方案有多种
1、使用fastjson序列化来处理,具体配置方式有2种,参考http://t.csdn.cn/hA1dn
2、在beforeBodyWrite方法中添加类型的判断,如果是String类型,就再对returnValue进行一次序列号。
package com.gaoshan.handler.response;
import com.alibaba.fastjson.JSON;
import com.gaoshan.axe.Result;
import org.nutz.lang.Lang;
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;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
@RestControllerAdvice(basePackages = "com.gaoshan")
public class GlobalResponseHandler implements ResponseBodyAdvice<Object> {
List<String> ignorePaths = new ArrayList<>();
static final List<String> DEFAULT_IGNORED_PATH = Lang.list("/swagger-resources.*", "/v2/api-docs", "/actuator.*", "/testStr2");
public GlobalResponseHandler() {
if (ignorePaths == null || ignorePaths.isEmpty()) {
ignorePaths = DEFAULT_IGNORED_PATH;
}
ignorePaths.addAll(DEFAULT_IGNORED_PATH);
this.ignorePaths = ignorePaths;
}
@Override
public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
return true;
}
@Override
public Object beforeBodyWrite(Object body,
MethodParameter returnType,
MediaType selectedContentType,
Class<? extends HttpMessageConverter<?>> selectedConverterType,
ServerHttpRequest request,
ServerHttpResponse response) {
if (body instanceof Result || ignored(request.getURI().getRawPath())) {
return body;
}else if(body instanceof String){
return JSON.toJSONString(Result.success(body));
}
return Result.success(body);
}
/**
* @param path
* @return
*/
private boolean ignored(String path) {
return ignorePaths.stream().anyMatch(item -> Pattern.matches(item, path));
}
}