Spring MVC 关键点 理解

来源:互联网 发布:安卓手机网络修复工具 编辑:程序博客网 时间:2024/06/06 03:13

学习 Spring MVC 源码 理解

1.工作流程了解

跟踪了一下dispatch servlet的源码,结合这张图以及这篇博客分析了一下
http://www.cnblogs.com/davidwang456/p/4096530.html

这里写图片描述

了解了 springMVC的整个工作流程

2.参数传递

还有一点就是记不住 关于springMVC 的返回值类型,String,ModelAndView;

跟踪了一下源码

2.1 dispatch servlet类的 doDispatch 方法里面,调用适配器进行处理后,一定会返回一个 modelandview,跟踪进去

mv = ha.handle(processedRequest, response, mappedHandler.getHandler());

2.2 org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter这个类里面进行handle处理,即返回这个modelandview,继续跟踪;

return invokeHandlerMethod(request, response, handler);

2.3 org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter这个类里面最关键的地方,创建了一个 modelandview,也就是说,返回的东西在这里一定会被包装,同样,modelMap也会被 塞进去参数

protected ModelAndView invokeHandlerMethod(HttpServletRequest request, HttpServletResponse response, Object handler)            throws Exception {        ServletHandlerMethodResolver methodResolver = getMethodResolver(handler);        Method handlerMethod = methodResolver.resolveHandlerMethod(request);        ServletHandlerMethodInvoker methodInvoker = new ServletHandlerMethodInvoker(methodResolver);        ServletWebRequest webRequest = new ServletWebRequest(request, response);        ExtendedModelMap implicitModel = new BindingAwareModelMap();        Object result = methodInvoker.invokeHandlerMethod(handlerMethod, handler, webRequest, implicitModel);        ModelAndView mav =                methodInvoker.getModelAndView(handlerMethod, handler.getClass(), result, implicitModel, webRequest);        methodInvoker.updateModelAttributes(handler, (mav != null ? mav.getModel() : null), implicitModel, webRequest);        return mav;    }

2.4换句话说,返回前台的参数都在 modelMap 里面,返回的 ModelAndView一定要携带modelMap,所以就有以下三种方式来传递参数回去,恩这样就理解了吧

   @RequestMapping("/testIn")    public String testIn( ModelMap model,@RequestParam(value = "templateId") Long templateId){        System.out.println("---------------testIn");        model.addAttribute("para01","para01");        return "test";    }    @RequestMapping("/testIn2")    public ModelAndView testIn2(@RequestParam(value = "templateId") Long templateId){        System.out.println("---------------testIn2");        ModelAndView mv = new ModelAndView("/test");        mv.addObject("para01","para002");        return mv;    }    @RequestMapping("/testIn3")    public ModelAndView testIn3(@RequestParam(value = "templateId") Long templateId){        System.out.println("---------------testIn3");        ModelMap map = new ModelMap();        map.put("para01","para003");        ModelAndView mv = new ModelAndView("/test");        mv.addObject(map);        return mv;    }
0 0
原创粉丝点击