美文网首页
源码导读:深入理解SpringMVC报400时的流程

源码导读:深入理解SpringMVC报400时的流程

作者: Michael孟良 | 来源:发表于2019-05-05 14:29 被阅读0次

    相信很多同学都了解过(或者面试前都会复习过)springMVC的执行流程,如下图:

    网图
    转载请注明出处:Michael孟良

    这里我想细节地理解下springMVC报400(也就是上图第5步拿到HandlerAdapter后,前往handler时出的错)的执行流程,希望对读者之后的工作或面试有帮助。
    我们举个简单的例子(因时间关系, 我用springboot的2.1.3.RELEASE版本作为这个springMVC的实验载体):


    springboot demo

    这里什么都不传,就传一个userId并指明是一个int类型


    postman
    在postman将userId赋值为6e,然后看他的报错流程。
    第一步常规操作,用户请求首先去到SpringMVC的DispatcherServlet类里面的doDispatch方法
    doDispatch

    用户现在拿到了HandlerAdapter,正准备去拿Resolver解析器。这时会跳到HandlerMethodArgumentResolverComposite类的resolveArgument方法里面


    HandlerMethodArgumentResolverComposite.resolveArgument

    这里我补充一下,参数前的注解如:@RequestPart @RequestParam @RequestBody @ModelAttribute ... 每个注解有不同的resolver解析器,例如@RequestPart的参数, 就会调用RequestPartMethodArgumentResolver这个class去解析参数,如果参数前面没有注解,这时springMVC 会默认为@RequestParam,并且跳到RequestParamMethodArgumentResolver这个解析器。

    RequestParamMethodArgumentResolver中的resolveName方法

    这里会看到首先判断请求进来的是不是MultipartFile , 如果不是就会直接以String格式拿到参数。 所以为什么如果要上传文件, controller的file一定要选MultipartFile,不然就会以String形式送到下面的逻辑代码,最后match不到而报错。
    ok, 拿到用户错误的‘6e’的userId后,请求就会跳到AbstractNamedValueMethodArgumentResolver的resolveArgument方法:


    AbstractNamedValueMethodArgumentResolver

    这里到最关键的一步了:
    arg = binder.convertIfNecessary(arg, parameter.getParameterType(), parameter);
    这里arg是‘6e’ (不是int类型的参数), parameter.getParameterType()为int,左跳右跳,跳到GenericConversionService的covert


    GenericConversionService的covert
    拿到StringToNumberConverter的覆盖器,最后在StringToNumberConverterFactory这个工厂类里:
    StringToNumberConverterFactory
    用NumberUtils去parseNumber这个不是int的‘6e’,最后爆400:
    {
      "timestamp": "2019-05-05T04:26:05.337+0000",
      "status": 400,
      "error": "Bad Request",
      "message": "Failed to convert value of type 'java.lang.String' to required type 'int'; nested exception is     java.lang.NumberFormatException: For input string: \"6e\"",
      "path": "/hello"
    }
    

    这里总结一下:


    String转int报400流程

    至此,我们都大概了解了springMVC的报错流程。这时我们玩深入点:



    我们依然用回@RequestParam,这次我们传实体UserEntity


    UserEntity
    UserEntity里面再包一个PetEntity的实体,准备好了json的string:
      {   "id": 0,   "petEntity": {     "id": 19,     "name": "string" ,   "sex": 6   },   "name": "doggie" }
    

    然后我们读它的流程。
    它的流程大致上和上面string转int例子一样,但去到拿ConverterFactory时,而继续往下走:



    当到了TypeConverterDelegate的大概148行左右



    但找不到对应的editor和转换策略时, 就会:
    throw new IllegalStateException(msg.toString());
    

    然后不断往外抛,直至抛到用户手上:

    {
        "timestamp": "2019-05-05T05:40:20.581+0000",
        "status": 500,
        "error": "Internal Server Error",
        "message": "Failed to convert value of type 'java.lang.String' to required type 'com.example.demo.UserEentity'; nested     exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type     'com.example.demo.UserEentity': no matching editors or conversion strategy found",
        "path": "/hello"
     }
    

    这里其实我觉得应该是一个400的bad request . 但springMVC定义成了500。

    到这里我有疑惑了,那像其他@RequestBdoy @RequestPart ..是怎么将String转实体的呢?带着疑惑我又做了个实验:



    这次用@RequestPart 做实验,发现在去到RequestPartMethodArgumentResolver时



    会跳到AbstractMessageConverterMethodArgumentResolver,这个class里面有个messageConverters的list:

        List<HttpMessageConverter<?>> messageConverters;
    

    这里就包含12个converter, 最后一个就是FastJsonHttpMessageConverter , 经过两层if if 过滤后得到当前converter为FastJsonHttpMessageConverter ,当到了

        body = (genericConverter != null ? genericConverter.read(targetType, contextClass, msgToUse) :
                                ((HttpMessageConverter<T>) converter).read(targetClass, msgToUse));
    

    springMVC 就会将参数交给第三方插件,也就是将FastJsonHttpMessageConverter 赋给了genericConverter,进行后续操作:



    到这里可以看出,最后会交由阿里插件fastjson去完成String 转 实体对象。

    总结:其实springMVC从用户request进来再解析成controller需要的parameter参数,并没有那么玄乎,不同annotation注释对应不同的Resolver解析器, 我们甚至可以写一个自己的解析器,再调用一下第三方的插件,例如阿里的fastJson去完成项目需要的功能。

    SpringMVC是个庞大的项目,如有读者觉得上述实验有所欠缺或不对,欢迎前来斧正!

    相关文章

      网友评论

          本文标题:源码导读:深入理解SpringMVC报400时的流程

          本文链接:https://www.haomeiwen.com/subject/aoqfmqtx.html