SpringMVC之ModelAndView

一、SpringMVC输出模型数据的几种常见途径

  1、ModelAndView

@Controller
public class SpringmvcDemo {

    @RequestMapping(value = "/testModelAndView", method = RequestMethod.GET)
    public ModelAndView testSpringMVC() {
        // 使用ModelAndView的方式
        ModelAndView mav = new ModelAndView();
        mav.addObject("username", "damaomao");
        mav.setViewName("testModelAndView");
        System.out.println("测试ModelAndView");
        return mav;
    }
}

  2、Map<Object,Object>集合

@Controller
public class SpringmvcDemo {

    @RequestMapping(value = "/testModelAndView", method = RequestMethod.GET)
    // 使用返回值是String类型,参数为map
    public String testSpringMVC01(Map<String,Object> map) {
        map.put("user01","xiaomao");
        map.put("user02","xiaomaomao");
        map.put("user03","xiaoxiaomaomao");
        return "testModelAndView";
    }
}

  3、Model对象

@Controller
public class SpringmvcDemo {

    @RequestMapping(value = "/testModelAndView", method = RequestMethod.GET)
    // 使用返回值是String类型,参数为Model
    public String testSpringMVC01(Model model) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("user01","haha");
        hashMap.put("user02","hehe");
        hashMap.put("user03","heihei");
        model.addAllAttributes(hashMap);
        return "testModelAndView";
    }
}

  

二、处理Model源码参考

  通过上面源码看出使用上述几种输出模型本质上都是Servlet中的request.getDispatcher.forward(request,response)的方式往域对象中存储值.

三、处理View源码参考

  1、一般情况下,控制器方法返回字符串类型的值会被当成逻辑视图名处理

  2、如果返回的字符串中带forward:或redirect:前缀时,SpringMVC 会对他们进行特殊处理:将 forward: 和redirect: 当成指示符,其后的字符串作为URL来处理

    例如:

      redirect:success.jsp:会完成一个到 success.jsp 的重定向的操作

      forward:success.jsp:会完成一个到 success.jsp 的转发操作

原文地址:https://www.cnblogs.com/xiaomaomao/p/13599535.html