关于RequestBody注解的一些想法
如发现本文存在的问题,恳请帮忙指出,感谢。
最近在看基于SpringBoot的登录逻辑,项目测试时使用Postman模拟表单登录请求,发现,程序总是报415,也就是不支持的类型。网上查了一圈,猜测可能是前后端参数不匹配导致的问题。排查后发现@RequestBody
有个坑:无法接收表单登录请求。
问题
基于SpringBoot,准备一个路径跳转Controller:
@RequestMapping
@Controller
public class IndexController {
@RequestMapping
public String index(){
return "login";
}
}
登录界面如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<form action="/user/login" method="post">
username:<input type="text" name="username"/><br/>
password:<input type="password" name="password"/><br/>
<input type="submit" value="submit">
</form>
</body>
</html>
登录请求处理:
@RestController
@RequestMapping("/user")
public class UserController {
@PostMapping("/login")
public Result login(@RequestBody User user){
System.out.println(user);
return Result.successResult();
}
}
User
类以及Result
不重要,这里就不写出来了,User
类只包含username
和password
属性。
登录测试:
但是,如果发送的是"application/json"的话:
分析
通过不断debug,可以得到最后路径和方法的映射关系被保存在了AbstractHandlerMethodMapping
的mappingLookup
属性中,可以看到映射方法被封装成了HandlerMethod
类
登录请求发出后会由DispatcherServlet
类分配进行后续处理的方法:
DispatcherServlet
的doDispatch
中的
// Determine handler for the current request.
mappedHandler = getHandler(processedRequest);
分配处理器。不断debug,最后在AbstractHandlerMethodMapping
类中的getHandlerInternal
中看到了分配结果:
最后又回到了Dispatch
:
mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
正式进入处理流程。
getHandler
方法会返回之前getHandler
方法返回的处理器。
执行到RequestMappingHandlerAdapter#invokeHandlerMethod
做一些准备,比如将HandlerMethod
封装成ServletInvocableHandlerMethod
:
ServletInvocableHandlerMethod invocableMethod = createInvocableHandlerMethod(handlerMethod);
设置参数、返回值解析器:
invocableMethod.setHandlerMethodArgumentResolvers(this.argumentResolvers);
...
invocableMethod.setHandlerMethodReturnValueHandlers(this.returnValueHandlers);
调用invokeAndHandlerMethod
进行处理:
invocableMethod.invokeAndHandle(webRequest, mavContainer);
public void invokeAndHandle(ServletWebRequest webRequest, ModelAndViewContainer mavContainer,
Object... providedArgs) throws Exception {
Object returnValue = invokeForRequest(webRequest, mavContainer, providedArgs);
setResponseStatus(webRequest);
if (returnValue == null) {
if (isRequestNotModified(webRequest) || getResponseStatus() != null || mavContainer.isRequestHandled()) {
disableContentCachingIfNecessary(webRequest);
mavContainer.setRequestHandled(true);
return;
}
}
else if (StringUtils.hasText(getResponseStatusReason())) {
mavContainer.setRequestHandled(true);
return;
}
mavContainer.setRequestHandled(false);
Assert.state(this.returnValueHandlers != null, "No return value handlers");
try {
this.returnValueHandlers.handleReturnValue(
returnValue, getReturnValueType(returnValue), mavContainer, webRequest);
}
catch (Exception ex) {
if (logger.isTraceEnabled()) {
logger.trace(formatErrorForReturnValue(returnValue), ex);
}
throw ex;
}
}
毫无疑问,invokeForRequest
用于执行请求:
@Nullable
public Object invokeForRequest(NativeWebRequest request, @Nullable ModelAndViewContainer mavContainer,
Object... providedArgs) throws Exception {
Object[] args = getMethodArgumentValues(request, mavContainer, providedArgs);
if (logger.isTraceEnabled()) {
logger.trace("Arguments: " + Arrays.toString(args));
}
return doInvoke(args);
}
先获取并解析参数,再通过doInvoke
方法执行Controller的自定义逻辑。
@RequestBody
的问题就在解析参数上。
针对请求参数的格式化,Spring准备了
HttpMessageConverter
。The
spring-web
module contains theHttpMessageConverter
contract for reading and writing the body of HTTP requests and responses throughInputStream
andOutputStream
.HttpMessageConverter
instances are used on the client side (for example, in theRestTemplate
) and on the server side (for example, in Spring MVC REST controllers).You can customize
HttpMessageConverter
in Java configuration by overridingconfigureMessageConverters()
(to replace the default converters created by Spring MVC) or by overridingextendMessageConverters()
(to customize the default converters or add additional converters to the default ones).
接着,不断debug直到进入HandlerMethodArgumentResolverComposite
的getArgumentResolver
,事情逐渐明朗:
参数解析类出现了RequestResponseBodyMethodProcessor
,而这个类正是用来处理@RequestBody
和@ResponseBody
注解的。
RequestResponseBodyMethodProcessor
Resolves method arguments annotated with @RequestBody and handles return values from methods annotated with @ResponseBody by reading and writing to the body of the request or response with an HttpMessageConverter.
下面是RequestResponseBodyMethodProcessor
抽象父类AbstractMessageConverterMethodProcessor
的参数处理逻辑。
protected <T> Object readWithMessageConverters(HttpInputMessage inputMessage, MethodParameter parameter,
Type targetType) throws IOException, HttpMediaTypeNotSupportedException, HttpMessageNotReadableException {
// 存放请求中的Content-Type
MediaType contentType;
boolean noContentType = false;
try {
contentType = inputMessage.getHeaders().getContentType();
}
catch (InvalidMediaTypeException ex) {
throw new HttpMediaTypeNotSupportedException(ex.getMessage());
}
if (contentType == null) {
noContentType = true;
contentType = MediaType.APPLICATION_OCTET_STREAM;
}
// 下面两行代码针对的是Controller
Class<?> contextClass = parameter.getContainingClass();
// 获得方法参数Class类
Class<T> targetClass = (targetType instanceof Class ? (Class<T>) targetType : null);
if (targetClass == null) {
ResolvableType resolvableType = ResolvableType.forMethodParameter(parameter);
targetClass = (Class<T>) resolvableType.resolve();
}
HttpMethod httpMethod = (inputMessage instanceof HttpRequest ? ((HttpRequest) inputMessage).getMethod() : null);
Object body = NO_VALUE;
EmptyBodyCheckingHttpInputMessage message;
try {
message = new EmptyBodyCheckingHttpInputMessage(inputMessage);
// 轮询所有HttpMessageConverter,碰到能够处理当前请求的就进行处理
for (HttpMessageConverter<?> converter : this.messageConverters) {
Class<HttpMessageConverter<?>> converterType = (Class<HttpMessageConverter<?>>) converter.getClass();
GenericHttpMessageConverter<?> genericConverter =
(converter instanceof GenericHttpMessageConverter ? (GenericHttpMessageConverter<?>) converter : null);
if (genericConverter != null ? genericConverter.canRead(targetType, contextClass, contentType) :
(targetClass != null && converter.canRead(targetClass, contentType))) {
if (message.hasBody()) {
HttpInputMessage msgToUse =
getAdvice().beforeBodyRead(message, parameter, targetType, converterType);
body = (genericConverter != null ? genericConverter.read(targetType, contextClass, msgToUse) :
((HttpMessageConverter<T>) converter).read(targetClass, msgToUse));
body = getAdvice().afterBodyRead(body, msgToUse, parameter, targetType, converterType);
}
else {
body = getAdvice().handleEmptyBody(null, message, parameter, targetType, converterType);
}
break;
}
}
}
catch (IOException ex) {
throw new HttpMessageNotReadableException("I/O error while reading input message", ex, inputMessage);
}
// 如果没有HttpMessageConverter能够处理,则抛出异常
if (body == NO_VALUE) {
if (httpMethod == null || !SUPPORTED_METHODS.contains(httpMethod) ||
(noContentType && !message.hasBody())) {
return null;
}
throw new HttpMediaTypeNotSupportedException(contentType, this.allSupportedMediaTypes);
}
MediaType selectedContentType = contentType;
Object theBody = body;
LogFormatUtils.traceDebug(logger, traceOn -> {
String formatted = LogFormatUtils.formatValue(theBody, !traceOn);
return "Read \"" + selectedContentType + "\" to [" + formatted + "]";
});
return body;
}
判断能否进行处理的逻辑(AbstractHttpMessageConverter
),其中supports
方法和canRead
方法均由具体的实现类提供:
@Override
public boolean canRead(Class<?> clazz, @Nullable MediaType mediaType) {
return supports(clazz) && canRead(mediaType);
}
可以看到,发送的JSON字符串可以由MappingJackson2HttpMessageConverter进行处理:
返回值的处理由AbstractMessageConverterMethodProcessor
的writeWithMessageConverters
进行,具体就不说了。
解决
用JSON字符作为前后端数据交换的方式;
-
将
@PostMapping("/login") public Result login(@RequestBody User user) {}
只能接收JSON数据。
改为
@PostMapping("/login") public Result login(String username, String password) {}
只能接收表单数据。
结论
没啥结论,要有就是用@RequestBody
和@ResponseBody
的时候小心尽量避免表单提交,转而用Ajax或其他传送JSON数据的方式。
这篇文章很不错:Spring MVC源码(三) ----- @RequestBody和@ResponseBody原理解析