萌新学习SpringMVC (4)

再进去readWithMessageConverters里边看看:

protected <T> Object readWithMessageConverters(HttpInputMessage inputMessage, MethodParameter param, Type targetType) throws IOException, HttpMediaTypeNotSupportedException, HttpMessageNotReadableException { // ...处理请求头 try { inputMessage = new EmptyBodyCheckingHttpInputMessage(inputMessage); // HttpMessageConverter实例去对参数转换 for (HttpMessageConverter<?> converter : this.messageConverters) { Class<HttpMessageConverter<?>> converterType = (Class<HttpMessageConverter<?>>) converter.getClass(); if (converter instanceof GenericHttpMessageConverter) { GenericHttpMessageConverter<?> genericConverter = (GenericHttpMessageConverter<?>) converter; if (genericConverter.canRead(targetType, contextClass, contentType)) { if (logger.isDebugEnabled()) { logger.debug("Read [" + targetType + "] as \"" + contentType + "\" with [" + converter + "]"); } if (inputMessage.getBody() != null) { inputMessage = getAdvice().beforeBodyRead(inputMessage, param, targetType, converterType); body = genericConverter.read(targetType, contextClass, inputMessage); body = getAdvice().afterBodyRead(body, inputMessage, param, targetType, converterType); } else { body = null; body = getAdvice().handleEmptyBody(body, inputMessage, param, targetType, converterType); } break; } } //...各种判断 return body; }

看到这里,有没有看不懂,想要退出的感觉了??别慌,三歪带你们看看这份熟悉的配置:

<!-- 启动JSON返回格式 --> <bean> <property> <list> <ref bean="jacksonMessageConverter" /> </list> </property> </bean> <bean> <property> <list> <value>text/html;charset=UTF-8</value> <value>application/json;charset=UTF-8</value> <value>application/x-www-form-urlencoded;charset=UTF-8</value> </list> </property> <property ref="jacksonObjectMapper" /> </bean> <bean />

我们在SpringMVC想要使用@ResponseBody返回JSON格式都会在配置文件上配置上面的配置,RequestMappingHandlerAdapter这个适配器就是上面所说的那个,内置了RequestResponseBodyMethodProcessor解析器,然后MappingJackson2HttpMessageConverter实际上就是HttpMessageConverter接口的实例

萌新学习SpringMVC

然后在返回的时候也经过HttpMessageConverter去将参数转换后,写给HTTP响应报文。转换的流程大致如图所示:

img

视图解析器后面就不贴了,大概的流程就如上面的源码,我再画个图来加深一下理解吧:

萌新学习SpringMVC

最后

SpringMVC我们使用的时候非常简便,在内部实际上帮我们做了很多(有各种的HandlerAdaptor),SpringMVC的请求流程面试的时候还是面得很多的,还是可以看看源码它帮我们做了什么,过一遍可能会发现自己能看懂以前的配置了。

参考资料:

https://www.cnblogs.com/java-chen-hao/category/1503579.html

https://www.jianshu.com/p/1bff57c74037

https://stackoverflow.com/questions/18682486/why-does-spring-mvc-need-at-least-two-contexts

各类知识点总结

92页的Mybatis

129页的多线程

Hibernate

AJAX

Redis

......

涵盖Java后端所有知识点的开源项目(已有8K+ star):

GitHub

Gitee访问更快

如果大家想要实时关注我更新的文章以及分享的干货的话,微信搜索Java3y

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zyjszg.html