是的,今天继续聊@RequestBody和@ResponseBody。
上次通过@RequestMapping注解了解到了RequestMappingHandlerMapping和RequestMappingHandlerAdaptor。
这两兄弟在处理请求的过程中,RequestMappingHandlerMapping帮忙做了url与方法的具体映射,RequestMappingHandlerAdaptor帮忙做了查找具体的处理程序和查找具体的将返回值处理为一个ModelAndView实例的程序。
今天主要来聊他们两兄弟的其他功能。
写一个简单的接口,用@RequestBody修饰方法参数,然后打断点看调用链。
还是在上篇文章中关注的这一行,现在需要关注的是变量ha,发现他的类型是RequestMappingHandlerAdapter。
发现这个处理器也是通过mappedHandler确定的。
现在看一下具体逻辑。
其中的handlerAdapters,则是在Spring容器初始化的过程中填充的。
以上是RequestMappingHandlerAdapter的加载过程,现在找它的应用代码。
在invokeHandlerMethod中,会设置两个参数,argumentResolvers和returnValueHandlers,如同变量名,一个负责解析参数,一个负责处理返回值。
解析参数的过程中,第一次进入的请求将会进入if代码块,其余请求将直接从缓存获取参数解析器。
这里的解析器,在现在的程序中,就是指将请求参数反序列化为对象的请求参数处理程序和将对象序列化为流的返回参数处理程序。
这里可以看到,Spring自带了27种解析器,而@RequestBody和@ResponseBody的解析器就是图中标出的RequestResponseBodyMethodProcessor。
在图中可以看到,判断的依据就是是否使用@RequestBody和@ResponseBody修饰过。
在程序启动后的第一个@RequestBody的请求进入时,将缓存处理程序。
如图所示,下一次进入时就不需要轮训程序列表了,可以直接从Map中读取,效率有保障。
resolveArgument方法是处理参数的方法,如图所示,这是一个反序列化的方法,将流转换为对象。
转换完成后,将进入我们程序中的@Controller类,然后再经过RequestResponseBodyMethodProcessor的handleReturnValue方法将对象序列化为流,返回给浏览器。
以上是@RequestBody和@ResponseBody的处理流程。那么我们写的程序可以利用这一点做什么呢?
在RequestResponseBodyMethodProcessor的父类AbstractMessageConverterMethodArgumentResolver中,Spring贴心的保留了一个供开发者利用的窗口。
通过使用@RestControllerAdvice注解可以在请求参数的进出处改写它,这种操作在处理大量参数的校验时挺好用。
以下代码是个人在处理大量参数的合法校验时使用的处理程序,如果有帮助就点个赞吧
@RestControllerAdvice
@Slf4j
public class RequestResponseBodyAdvice implements RequestBodyAdvice, ResponseBodyAdvice<Object> {
@Override
public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
return methodParameter.hasParameterAnnotation(RequestBody.class);
}
@Override
public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
return inputMessage;
}
@Override
public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
try {
return handlerRequestBody(body);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | InstantiationException e) {
log.error("afterBodyRead", e);
}
return body;
}
@Override
public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
return body;
}
@Override
public boolean supports(MethodParameter returnType, Class converterType) {
return returnType.hasMethodAnnotation(ApiOperation.class);
}
@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
try {
return handlerResponseBody(body);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | InstantiationException e) {
log.error("beforeBodyWrite", e);
}
return body;
}
private Object handlerRequestBody(Object argument) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException, InstantiationException {
// 新增
Class<?> argumentClass = argument.getClass();
Field[] fields = argumentClass.getDeclaredFields();
handlerRequestDefaultValue(fields, argument, argumentClass);
Class<?> superclass = argumentClass.getSuperclass();
while (null != superclass) {
Field[] superFields = superclass.getDeclaredFields();
handlerRequestDefaultValue(superFields, argument, superclass);
superclass = superclass.getSuperclass();
}
return argument;
}
private void handlerRequestDefaultValue(Field[] fields, Object argument, Class<?> argClass) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException, InstantiationException {
for (Field field : fields) {
field.setAccessible(true);
if (null != field.getAnnotation(ApiModelProperty.class)) {
String fieldName = toUpperFirstOne(field.getName());
Method getMethod = argClass.getDeclaredMethod("get" + fieldName);
getMethod.setAccessible(true);
Object o = getMethod.invoke(argument);
Class<?> type = field.getType();
if (null == o) {
String value = field.getAnnotation(ApiModelProperty.class).defaultValue();
String[] dict = field.getAnnotation(ApiModelProperty.class).dict();
boolean isEnums = dict.length > 1;
boolean isContains = Arrays.asList(dict).contains(value);
Method setMethod = argClass.getDeclaredMethod("set" + fieldName, type);
setMethod.setAccessible(true);
if (type.equals(String.class)) {
if (isEnums && isContains) {
setMethod.invoke(argument, value);
}else if(isEnums && StringUtils.hasText(value)){
setMethod.invoke(argument, dict[0].split(":")[0]);
}else
if (StringUtils.hasText(value)) {
setMethod.invoke(argument, value);
}
} else if (type.equals(Integer.class)) {
/*if (isEnums && isContains) {
setMethod.invoke(argument, Integer.valueOf(value));
}else if(isEnums && StringUtils.isNotBlank(value)){
setMethod.invoke(argument, Integer.valueOf(dict[0].split(":")[0]));
}else*/
if (StringUtils.hasText(value)) {
setMethod.invoke(argument, Integer.valueOf(value));
}
} else if (type.equals(Boolean.class)) {
/*if (isEnums && isContains) {
setMethod.invoke(argument, "1".equals(value));
}else if(isEnums && StringUtils.isNotBlank(value)){
setMethod.invoke(argument, "1".equals(dict[0].split(":")[0]));
}else*/
if (StringUtils.hasText(value)) {
setMethod.invoke(argument, "1".equals(value));
}
}
}
}
}
}
private Object handlerResponseBody(Object argument) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException, InstantiationException {
// 新增
Class<?> argumentClass = argument.getClass();
Field[] fields = argumentClass.getDeclaredFields();
handlerResponseDefaultValue(fields, argument, argumentClass);
Class<?> superclass = argumentClass.getSuperclass();
while (null != superclass) {
Field[] superFields = superclass.getDeclaredFields();
handlerResponseDefaultValue(superFields, argument, superclass);
superclass = superclass.getSuperclass();
}
return argument;
}
private void handlerResponseDefaultValue(Field[] fields, Object argument, Class<?> argClass) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException, InstantiationException {
for (Field field : fields) {
field.setAccessible(true);
if (null != field.getAnnotation(ApiModelProperty.class)) {
String fieldName = toUpperFirstOne(field.getName());
Method getMethod = argClass.getDeclaredMethod("get" + fieldName);
getMethod.setAccessible(true);
Object o = getMethod.invoke(argument);
Class<?> type = field.getType();
if (null == o) {
String value = field.getAnnotation(ApiModelProperty.class).defaultValue();
Method setMethod = argClass.getDeclaredMethod("set" + fieldName, type);
setMethod.setAccessible(true);
if (type.equals(String.class) && StringUtils.hasText(value)) {
setMethod.invoke(argument, value);
} else if (type.equals(Integer.class) && StringUtils.hasText(value)) {
if (StringUtils.hasText(value)) {
setMethod.invoke(argument, Integer.valueOf(value));
}
} else if (type.equals(Boolean.class) && StringUtils.hasText(value)) {
setMethod.invoke(argument, "1".equals(value));
} else if (type.equals(List.class)) {
// Type genericType = field.getGenericType();
// if (genericType instanceof ParameterizedType) {
// ParameterizedType pt = (ParameterizedType) genericType;
// Class<?> genericClazz = (Class<?>) pt.getActualTypeArguments()[0];
// if (isPrimitive(genericClazz)) {
// setMethod.invoke(argument, new ArrayList<>());
// continue;
// }
// Object o1 = genericClazz.newInstance();
// Field[] argufields = genericClazz.getDeclaredFields();
// handlerResponseDefaultValue(argufields, o1, genericClazz);
// setMethod.invoke(argument, Collections.singletonList(o1));
// } else {
setMethod.invoke(argument, new ArrayList<>());
// }
} else if (!isPrimitive(type)) {
Field[] argufields = type.getDeclaredFields();
Object o1 = type.newInstance();
handlerResponseDefaultValue(argufields, o1, type);
setMethod.invoke(argument, o1);
//setMethod.invoke(argument, new Object());
}
}
}
}
}
private String toUpperFirstOne(String s) {
if (Character.isUpperCase(s.charAt(0))) {
return s;
} else {
return Character.toUpperCase(s.charAt(0)) +
s.substring(1);
}
}
private boolean isPrimitive(Class<?> clazz) {
return clazz.equals(Integer.class) ||
clazz.equals(Byte.class) ||
clazz.equals(Long.class) ||
clazz.equals(Double.class) ||
clazz.equals(Float.class) ||
clazz.equals(Character.class) ||
clazz.equals(Short.class) ||
clazz.equals(Boolean.class);
}
}