栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

2021-10-16

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

2021-10-16

**

关于SpringMvc中的ModelAndView 、Model、ModelMap的区别

**
不说废话直接上正文!
一般而言,在处理视图解析器获得前端数据处理业务时候,会用到以上这三个对象,观察源码发现第一个ModelMap继承了linkedMap,丰富了其功能拓展,用的不多。 这些对象主要用于传递控制方法处理数据到结果页面
1.ModelAndView
通常用在实现Controller接口时候,直接创建该对象,返回值也是ModelAndView对象这是与精简版的区别。

package cn.hdu.controller;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//只要实现了controller接口的类说明就是一个控制器了
public class ControllerTest01 implements Controller {
    public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        ModelAndView modelAndView = new ModelAndView();

        //mv做两件事  添加数据  跳转页面   简化版model
        modelAndView.addObject("msg","大傻逼黄秀云");
        modelAndView.setViewName("admin/test");
        return modelAndView;
    }
}

2.Model
该对象用的最多,可用来传参数、传对象,返回值是String类型。

public class ControllerTest03 {
    @RequestMapping("/t1")  //设置请求的接口  写死
    public String test1(Model model){
        model.addAttribute("msg","controllerTest3");
        return "admin/test";
    }

3.ModelMap
用的较少,l和Model用法相同。注意Map对象是MvC内部自己创建的

package cn.hdu.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("map")
public class ModelMapTest {
    @GetMapping("t5")
    public String test01(ModelMap modelMap){
        modelMap.addAttribute("msg","黄秀云是大傻逼吗?");
        return "admin/test";
    }
}

**

总结:

**

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/328465.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号