HandlerInterceptor中的preHandle的参数handler怎么获取到目标方法并做入参的赋值
时间: 2023-06-05 16:05:10 浏览: 613
可以通过HandlerExecutionChain对象获取目标方法的信息,然后使用反射机制对目标方法的入参进行赋值。具体实现可以参考以下代码:
```
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
Method method = handlerMethod.getMethod();
Object[] args = new Object[method.getParameterTypes().length];
Annotation[][] parameterAnnotations = method.getParameterAnnotations();
for (int i = 0; i < parameterAnnotations.length; i++) {
for (Annotation annotation : parameterAnnotations[i]) {
if (annotation.annotationType().equals(RequestBody.class)) {
args[i] = readRequestBody(request, method.getParameterTypes()[i]);
break;
} else if (annotation.annotationType().equals(RequestParam.class)) {
args[i] = readRequestParam(request, method.getParameterTypes()[i], method.getParameters()[i].getName());
break;
} else if (annotation.annotationType().equals(RequestHeader.class)) {
args[i] = readRequestHeader(request, method.getParameterTypes()[i], method.getParameters()[i].getName());
break;
} else if (annotation.annotationType().equals(PathVariable.class)) {
args[i] = readPathVariable(request, method.getParameterTypes()[i], ((PathVariable) annotation).value());
break;
}
}
}
request.setAttribute("args", args);
}
return true;
}
private Object readRequestBody(HttpServletRequest request, Class<?> clazz) throws IOException {
String body = IOUtils.toString(request.getReader());
return objectMapper.readValue(body, clazz);
}
private Object readRequestParam(HttpServletRequest request, Class<?> clazz, String paramName) {
String value = request.getParameter(paramName);
return conversionService.convert(value, clazz);
}
private Object readRequestHeader(HttpServletRequest request, Class<?> clazz, String headerName) {
String value = request.getHeader(headerName);
return conversionService.convert(value, clazz);
}
private Object readPathVariable(HttpServletRequest request, Class<?> clazz, String variableName) {
String value = (String) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE).get(variableName);
return conversionService.convert(value, clazz);
}
```
阅读全文