SpringMVC中的Model和ModelAndView详解

原文链接:

0.前言

1.Model是什么?

model是”模型“的意思,是MVC架构中的”M“部分,是用来传输数据的。

2.ModelAndView是什么?

如果翻译过来就是”模型和视图“,可以理解成MVC架构中的”M“和”V“,其中包含”Model“和”view“两部分,主要功能是:

设置转向地址
将底层获取的数据进行存储(或者封装)
最后将数据传递给View
区别?

1.Model只是用来传输数据的,并不会进行业务的寻址。ModelAndView 却是可以进行业务寻址的,就是设置对应的要请求的静态文件,这里的静态文件指的是类似jsp的文件。Model是每次请求中都存在的默认参数,利用其addAttribute()方法即可将服务器的值传递到jsp页面中;ModelAndView包含model和view两部分,使用时需要自己实例化,利用ModelMap用来传值,也可以设置view的名称。

2.Model是每一次请求可以自动创建,但是ModelAndView 是需要我们自己去new的。

1.model的使用

查看Model的源码发现,里面比较重要的就是前4个。

package org.springframework.ui;import java.util.Collection;
import java.util.Map;import org.springframework.lang.Nullable;/*** Java-5-specific interface that defines a holder for model attributes.* Primarily designed for adding attributes to the model.* Allows for accessing the overall model as a {@code java.util.Map}.** @author Juergen Hoeller* @since 2.5.1*/
public interface Model {/*** Add the supplied attribute under the supplied name.* @param attributeName the name of the model attribute (never {@code null})* @param attributeValue the model attribute value (can be {@code null})*/Model addAttribute(String attributeName, @Nullable Object attributeValue);/*** Add the supplied attribute to this {@code Map} using a* {@link org.springframework.core.Conventions#getVariableName generated name}.* <p><i>Note: Empty {@link java.util.Collection Collections} are not added to* the model when using this method because we cannot correctly determine* the true convention name. View code should check for {@code null} rather* than for empty collections as is already done by JSTL tags.</i>* @param attributeValue the model attribute value (never {@code null})*/Model addAttribute(Object attributeValue);/*** Copy all attributes in the supplied {@code Collection} into this* {@code Map}, using attribute name generation for each element.* @see #addAttribute(Object)*/Model addAllAttributes(Collection<?> attributeValues);/*** Copy all attributes in the supplied {@code Map} into this {@code Map}.* @see #addAttribute(String, Object)*/Model addAllAttributes(Map<String, ?> attributes);/*** Copy all attributes in the supplied {@code Map} into this {@code Map},* with existing objects of the same name taking precedence (i.e. not getting* replaced).*/Model mergeAttributes(Map<String, ?> attributes);/*** Does this model contain an attribute of the given name?* @param attributeName the name of the model attribute (never {@code null})* @return whether this model contains a corresponding attribute*/boolean containsAttribute(String attributeName);/*** Return the attribute value for the given name, if any.* @param attributeName the name of the model attribute (never {@code null})* @return the corresponding attribute value, or {@code null} if none* @since 5.2*/@NullableObject getAttribute(String attributeName);/*** Return the current set of model attributes as a Map.*/Map<String, Object> asMap();}

Model addAttribute(String attributeName, @Nullable Object attributeValue)
Model addAttribute(Object attributeValue);
Model addAllAttributes(Collection<?> attributeValues);
Model addAllAttributes(Map<String, ?> attributes);
具体用法1:返回一个字符

Controller层的写法

package com.cat.controller;import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
/** controller 负责提供访问应用程序的行为,通常通过接口定义或者注解定义两种方法实现。* 控制器负责解析用户的请求并将其转换为一个模型。* */
@Controller  //代表这个类会被spring接管,被这个注解的类中所有方法,如果返回值是string,并且有具体的页面可以跳转,那么就会被视图解析器解析
public class IndexController {@RequestMapping("/hello")   //意为请求 localhost:8080/hello public String hello(Model model){//封装数据(向模型中添加数据,可以jsp页面直接取出并渲染)model.addAttribute("name","张三");model.addAttribute("sex","男");model.addAttribute("age",23);System.out.println(model);//会被视图解析器处理return "hello";   //返回到哪个页面     }
}

jsp写法(注意和路径对应)

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>Title</title>
</head>
<body>
hello.jsp页面
<p>姓名:${name}</p>
<p>性别:${sex}</p>
<p>年龄:${age}</p>
</body>
</html>

在这里插入图片描述
如果出现上面这种不正常的情况,请点击这里。

正常情况如下所示:
在这里插入图片描述
具体用法2:返回一个对象

model方法是可以返回一个对象的。我们创建一个对象在这里插入图片描述
Person实体类,至少要加上get方法。不然前端取不到数据

package com.cat.domain;public class Person {public  String name;public  String sex;public  int age;public String getName() {return name;}public void setName(String name) {this.name = name;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}@Overridepublic String toString() {return "Person{" +"name='" + name + '\'' +", sex='" + sex + '\'' +", age=" + age +'}';}
}

在这里插入图片描述
IndexController代码改成下面这样。

package com.cat.controller;import com.cat.domain.Person;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;@Controller
@RequestMapping
public class IndexController {@RequestMapping("/hello")public String hello(Model model){Person person =new Person();person.name="张三";person.age=16;person.sex="男";System.out.println(person);model.addAttribute("person",person);return "hello";}}

hello.jsp改成下面这样子。

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>Title</title>
</head>
<body>
hello.jsp页面
<p>姓名:${person.name}</p>
<p>性别:${person.sex}</p>
<p>年龄:${person.age}</p>
</body>
</html>

页面重新请求后变成下面样子说明请求成功

在这里插入图片描述
返回map和collection类型暂时不做演示。

2. ModelAndView

ModelAndView有的方法和Model很类似,一共有下面这些方法。

构造方法:

ModelAndView()  //默认构造函数豆式的用法:填充bean的属性,而不是将在构造函数中的参数。
ModelAndView(String viewName)  //方便的构造时,有没有模型数据暴露。
ModelAndView(String viewName, Map model)  //给出创建一个视图名称和模型新的ModelAndView。
ModelAndView(String viewName, String modelName, Object modelObject)  //方便的构造采取单一的模式对象。
ModelAndView(View view)   //构造方便在没有模型数据暴露。
ModelAndView(View view, Map model)  //创建给定一个视图对象和模型,新的ModelAndView。
ModelAndView(View view, String modelName, Object modelObject)   //方便的构造采取单一的模式对象。

类方法

ModelAndView  addAllObjects(Map modelMap)  //添加包含在所提供的地图模型中的所有条目。
ModelAndView  addObject(Object modelObject)  //添加对象使用的参数名称生成模型。
ModelAndView  addObject(String modelName,ObjectmodelObject)  //对象添加到模型中。
void  clear()  //清除此ModelAndView对象的状态。
Map  getModel()  //返回的模型图。
protectedMap  getModelInternal()  //返回的模型图。
ModelMap  getModelMap()  //返回底层ModelMap实例(从不为null)。
View  getView()  //返回View对象,或者为null,如果我们使用的视图名称由通过一个ViewResolverDispatcherServlet会得到解决。
String  getViewName()  //返回视图名称由DispatcherServlet的解决,通过一个ViewResolver,或空,如果我们使用的视图对象。
boolean  hasView()  //指示此与否的ModelAndView有一个观点,无论是作为一个视图名称或作为直接查看实例。
boolean  isEmpty()  //返回此ModelAndView对象是否为空,即是否不持有任何意见,不包含模型。
boolean  isReference()  //返回,我们是否使用视图的参考,i.e.
void  setView(Viewview)  //设置此ModelAndView的视图对象。
void  setViewName(StringviewName)  //此ModelAndView的设置视图名称,由通过一个ViewResolverDispatcherServlet会得到解决。
String  toString()  //返回这个模型和视图的诊断信息。
boolean  wasCleared()??  //返回此ModelAndView对象是否为空的调用的结果,以清除(),即是否不持有任何意见,不包含模型。

在Controller中添加一个新的方法。

package com.cat.controller;import com.cat.domain.Person;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;@Controller
@RequestMapping
public class IndexController {
//    @RequestMapping("/hello")
//    public String hello(Model model){
//        Person person =new Person();
//        person.name="张三";
//        person.age=16;
//        person.sex="男";
//        System.out.println(person);
//        model.addAttribute("person",person);
//        return "hello";
//    }@RequestMapping("/hello2")public ModelAndView hello(){ModelAndView modelAndView = new ModelAndView();modelAndView.setViewName("hello");  //返回到那个文件modelAndView.addObject("name","派大星");modelAndView.addObject("sex","男");modelAndView.addObject("age",53);System.out.println(modelAndView);return modelAndView;}
}

hello.jsp改成

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>Title</title>
</head>
<body>
hello.jsp页面
<p>姓名:${name}</p>
<p>性别:${sex}</p>
<p>年龄:${age}</p>
</body>
</html>

请求新的地址后发现数据没有问题。

在这里插入图片描述
同理,ModelAndView也可以返回一个对象。这里就不做演示了。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://xiahunao.cn/news/350889.html

如若内容造成侵权/违法违规/事实不符,请联系瞎胡闹网进行投诉反馈,一经查实,立即删除!

相关文章

5.1 - Web漏洞 - XSS漏洞详解

「作者简介」&#xff1a;CSDN top100、阿里云博客专家、华为云享专家、网络安全领域优质创作者 「推荐专栏」&#xff1a;对网络安全感兴趣的小伙伴可以关注专栏《网络安全入门到精通》 XSS漏洞 一、什么是XSS&#xff1f;二、XSS概述三、靶场练习四、XSS使用步骤五、XSS攻击类…

影响代理ip纯净度的原因及目标网站如何识别代理ip

网络上代理ip很多&#xff0c;但真正可以为我们所用的大部分都是付费ip&#xff0c;那为什么免费ip不能为我们所用呢&#xff1f;下面我们就纯净度和目标网站是如何识别代理ip来分析一下。 一、纯净度 ip纯净度是什么意思呢&#xff1f;简单一点开始就是指使用这个ip的人少&…

如果你当架构师,从0开始,如何做一个后台项目的架构?

前言 在40岁老架构师 尼恩的读者社群(50)中&#xff0c;很多小伙伴要拿高薪&#xff0c;这就要面试架构师&#xff0c;要完成架构的升级&#xff0c;进入架构赛道。 在架构师的面试过程中&#xff0c;常常会遇到下面的问题&#xff1a; 如果给你一个项目要你从0到1做架构&…

数字化艺术时代的新趋势:虚拟数字展厅的崛起

引言&#xff1a; 艺术与技术的融合正带领我们进入一个全新的数字化艺术时代。在这个时代中&#xff0c;虚拟数字展厅正在以惊人的速度崛起&#xff0c;并引领着展览的新趋势。 一&#xff0e;虚拟数字展厅的定义和特点 虚拟数字展厅是一种基于虚拟现实和全景技术的数字化艺术…

pycharm2018如何关闭自动更新提示

1.点击左上角File,如图进入Settings(或者按CtrlAlts) 2.搜索到updates选项,把Automatically check updates for(自动检查更新以…规则) 前面够选去掉即可.

两天搞定计算机专业毕业设计,附源码

两天搞定计算机专业毕业设计&#xff0c;附源码 适用者毕设专业 使用要求具备基本Unity 基本操作小白即可&#xff0c;无需编码 博主诉求快乐毕业 点赞 关注 收藏 资源说明Free资源太多了&#xff0c;看截图目录就知道了 适用者 毕设专业 鄙人也是计算机狗一只&#xff0c;会…

电脑关闭自动更新

1.winr 打开运行窗口输出services.msc,点击确定 2.在服务窗口中&#xff0c;我们找到Windows update选项,双击打开 3.在启动类型选择禁用 4.点击上面的恢复&#xff0c;在恢复选项里面&#xff0c;我们把第一、第二、后续失败&#xff0c;都改为无操作&#xff0c;后点击应用…

ubuntu20关闭自动更新

1、在GUI上关闭自动更新。设置-关于-软件更新-更新&#xff0c;能关的关&#xff0c;不能关的改成最低频率。 2、阻止软件更新弹窗&#xff08;眼不见为净~&#xff09; 打开终端执行命令&#xff1a; sudo chmod a-x /usr/bin/update-notifier 如果想恢复弹窗执行下面的命令…

vscode配置html页面自动刷新,Vscode关闭自动更新设置

如何关闭Vscode自动更新&#xff1f; 有时侯在使用Vscode时会发现自己都不知道它就自已更新了&#xff0c;如何关闭Vscode的自动更新呢&#xff1f;下面介绍一下关闭Vscode自动更新的方法步骤&#xff1a; 打开Vscode&#xff0c;点击文件》首选项》设置&#xff0c;在打开的设…

关闭Postman v5.0自动更新

Postman大约每1个月&#xff0c;就会在后台更新一次&#xff0c;这种更新是可以屏蔽的。 在Postman的[设置]页面 --> Update —> Disable 即可&#xff0c;如图(1)所示。 图(1) 设置自动更新为Disabled 需要说明的是&#xff0c;此操作只对Postman v5.0以下的版本有效&am…

Chrome浏览器如何关闭自动更新

首先是【右键计算机->管理】&#xff0c;在【计算机管理(本地)->系统工具->任务计划程序->任务计划程序库】中找到两个和Google自动更新相关的任务计划【GoogleUpdateTaskMachineCore】与【GoogleUpdateTaskMachineUA】&#xff0c;并把它俩禁用掉。印象中介绍这方…

Windows Server 2016关闭自动更新

场景描述 平时使用系统时总提示需要更新系统&#xff0c;而更新系统后发现有些功能会出现新的异常&#xff0c;故而关闭自动更新的需求产生&#xff0c;这里介绍如何再Windos server 2016中关闭自动更新~ 解决方法 Step 1&#xff1a;进入cmd&#xff0c;之后输入sconfig St…

eclipse如何关闭自动更新

一、问题描述 eclipse如何关闭自动更新 二、解决方法 1. Window --> Preferences --> General --> Startup and Shutdown -->在列表项里面找到"Automatic Updates Scheduler " 项去掉前面的勾 2. Window --> Preferences --> Myeclips…

windows10 关闭自动更新

暂停自动更新 打开Windows更新的高级选项 win10专业版即以上关闭自动更新 Windows10专业版及其以上版本的操作系统可以使用组策略编辑器&#xff0c;可以在组策略编辑器中配置Windows更新。首先按下winR&#xff0c;在命令窗口中输入“gpedit.msc”&#xff0c;打开组策略编辑…

Chrome浏览器关闭自动更新

背景是&#xff1a; 在用Python抓取的时候&#xff0c;经常会遇到Chrome浏览器版本和Chromedriver版本不一致的情况&#xff0c;为此有必要关闭Chrome的自动更新功能。 1、在Windows电脑桌面上&#xff0c;右键点击“此电脑” -》选择“管理”&#xff0c;弹出下面&#xff1a;…

Intellig idea关闭自动更新

idea关闭自动更新 idea是java编程语言开发的集成环境。IntelliJ在业界被公认为最好的java开发工具&#xff0c;尤其在智能代码助手、代码自动提示、重构、JavaEE支持、各类版本工具(git、svn等)、JUnit、CVS整合、代码分析、 创新的GUI设计等方面的功能可以说是超常的。 IDEA是…

如何关闭电脑自动更新?

方法一 步骤1.电脑左下角有一个【开始】图标&#xff0c;右键它后点击“运行”&#xff1b; 步骤2.在弹出的运行界面里的框内输入services.msc后点击确定或者抨击键盘的回车键&#xff0c;随后在弹出的界面我们需要找到并双击“Windows Update”&#xff1b; 步骤3.在弹出的界…

怎么关闭服务器系统自动更新,自动更新怎么关闭 如何关闭window自动更新提高运行速度...

我们知道安装的系统默认是开启系统自动更新的。对于绝多数个人用户甚至企业用户来说windows自带的自动更新功能并不实用&#xff0c;经常会自动下载系统内部一些补丁程序并安装&#xff0c;造成过多系统垃圾&#xff0c;甚至造成系统出错&#xff0c;影响系统稳定与速度。因此我…

腾讯会议关闭自动更新

20221009 可以用 转载于PC端腾讯会议怎么关闭自动更新&#xff1f; - 知乎用户的回答 - 知乎&#xff0c;如有侵权可联系删除 需要下载火绒&#xff0c;此方法仅限于Windows., 不想安装或者没有可以跳过 首先, 新建一个文本文档, 扩展名重命名为.json, 将代码段的内容粘贴进去…

Ubuntu关闭自动更新

文章目录 前言一、基本概念二、操作步骤1.打开软件与更新2.修改配置2.注意事项 总结 前言 Ubuntu自动更新会使现有开发环境受到影响&#xff0c;甚至找不到显卡驱动。 一、基本概念 Ubuntu基于Debian发行版和GNOME桌面环境&#xff0c;与Debian的不同在于它每6个月会发布一个…