Controller handler method supported return types

前端 未结 3 1344
醉酒成梦
醉酒成梦 2021-01-24 06:46

While learning the Spring framework, I notice in the book Spring in Action, the author doesn\'t use ModelandView method return type in controllers. The aut

3条回答
  •  青春惊慌失措
    2021-01-24 07:38

    In spring source code, you can see this class org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter. In the method public ModelAndView getModelAndView(...), you can get how sping-mvc generate ModelAandView object.

    if (returnValue instanceof HttpEntity) { // returnValue is returned Value of Handler method
                handleHttpEntityResponse((HttpEntity) returnValue, webRequest);
                return null;
            }
            else if (AnnotationUtils.findAnnotation(handlerMethod, ResponseBody.class) != null) {
                handleResponseBody(returnValue, webRequest);
                return null;
            }
            else if (returnValue instanceof ModelAndView) {
                ModelAndView mav = (ModelAndView) returnValue;
                mav.getModelMap().mergeAttributes(implicitModel);
                return mav;
            }
            else if (returnValue instanceof Model) {
                return new ModelAndView().addAllObjects(implicitModel).addAllObjects(((Model) returnValue).asMap());
            }
            else if (returnValue instanceof View) {
                return new ModelAndView((View) returnValue).addAllObjects(implicitModel);
            }
            else if (AnnotationUtils.findAnnotation(handlerMethod, ModelAttribute.class) != null) {
                addReturnValueAsModelAttribute(handlerMethod, handlerType, returnValue, implicitModel);
                return new ModelAndView().addAllObjects(implicitModel);
            }
            else if (returnValue instanceof Map) {
                return new ModelAndView().addAllObjects(implicitModel).addAllObjects((Map) returnValue);
            }
            else if (returnValue instanceof String) { // String is here, return new ModelAndView
                return new ModelAndView((String) returnValue).addAllObjects(implicitModel);
            }
    

    So in this method you can learn that spring-mvc can handle many returned types of handler method to build ModleAndView object.

提交回复
热议问题