springMVC中Model,ModelAndView,ModelMap的区别

前言

springMVC 请求处理方法返回的参数类型中,最重要就是 ModelModelAndView了。使用 ModelModelAndView 这两者之间有着很大的区别

  • Model 只是用来传输数据的,并不会进行业务的寻址
  • ModelAndView 却是可以进行业务寻址的,就是设置对应的要请求的静态文件,这里的静态文件指的是类似 jsp 的文件

Model

Model 是一个接口,实现类为 ExtendedModelMapModelMapModel 本身不能设置页面跳转的 url 地址别名或者物理跳转地址,我们可以通过控制器方法的返回值 renturn 来设置跳转 urlModel 是用 addAttribute() 方法设置返回的值的

Model 源码

public interface Model {
    
    
    Model addAttribute(String var1, @Nullable Object var2);

    Model addAttribute(Object var1);

    Model addAllAttributes(Collection<?> var1);

    Model addAllAttributes(Map<String, ?> var1);

    Model mergeAttributes(Map<String, ?> var1);

    boolean containsAttribute(String var1);

    Map<String, Object> asMap();
}


public class ExtendedModelMap extends ModelMap implements Model {
    
    
	// ......
}

使用示例

Controller 控制器层

@RequestMapping(path = "/home", method = RequestMethod.GET)
public String index(@NotNull Model model) {
    
    

	/* ------------置顶数据查询(只展示 4 条数据)------------*/
	PagingParameterPostVO topping = new PagingParameterPostVO();
	topping.setPageNum(0);
	topping.setPageSize(pagingProperties.getTopPageNum());
	List<PostVO> postVOS = postService.selectPostVOTop(topping);
	model.addAttribute("postVOS", postVOS);
}

页面渲染

<ul class="fly-list">
	<!-- thymeleaf模板引擎:使用 th:each 遍历 -->
    <li th:each="postVOS,postVOSStatus:${postVOS}">
    	<a th:href="'/user/home?userId='+ ${postVOS.userId}" class="fly-avatar">
        	<img th:src="${postVOS.avatar}" alt="贤心">
        </a>
        <h2>
        	<a class="layui-badge" th:text="${postVOS.categoryName}"></a>
            <a th:href="'/post/detail?id='+ ${postVOS.id}" th:text="${postVOS.title}"></a>
        </h2>
        <div class="fly-list-info">
        	<a th:href="'/user/home?userId='+ ${postVOS.userId}" link>
            	<cite th:text="${postVOS.username}"></cite>
            	<i class="iconfont icon-renzheng" title="认证信息:XXX"
            		th:unless="${postVOSStatus.last}"></i>
            	<i class="layui-badge fly-badge-vip" th:unless="${postVOSStatus.last}">VIP3</i>
            </a>
            <!-- thymeleaf模板引擎:日期的格式化 -->
            <span th:text="${#dates.format(postVOS.created,'yyyy-MM-dd HH:mm:ss')}"></span>
            <span class="fly-list-kiss layui-hide-xs" title="悬赏飞吻"><i class="iconfont icon-kiss"></i> 60</span>
            <span class="layui-badge fly-badge-accept layui-hide-xs">已结</span>
            <span class="fly-list-nums" th:inline="text">
            	<i class="iconfont icon-pinglun1" title="回答"></i>
                	[[${postVOS.commentCount}]]
           	</span>
         </div>
         <div class="fly-list-badge">
         	<span class="layui-badge layui-bg-red"
            	style="margin-right: 5px;top: 2.5px;height: 21px;line-height: 21px"
               	th:if="${postVOS.recommend}">精帖</span>
            <span class="layui-btn layui-btn-xs jie-admin" type="set" field="stick" rank="1"
                                  th:if="${postVOS.level} gt '0'">置顶</span>
         </div>
	</li>
</ul>

ModelAndView

ModelAndView 主要有两个作用:设置转向地址和传递控制器方法处理结果数据到前端页面

设置转向地址

  • 通过 ModelAndView 构造方法可以指定返回的页面名称(逻辑视图名)
ModelAndView mav = new ModelAndView("/demo2/show"); 
  • 初始化之后再通过 setViewName() 方法跳转到指定的页面
ModelAndView mav= new ModelAndView();
mav.setViewName(String viewName);

传递数据

Controller 控制器方法中处理的结果数据传递到前端页面,也就是把在页面上需要的数据放到 ModelAndView 对象中即可,使用 ModelAndView 对象调用如下方法即可。其作用类似于 request 对象的 setAttribute() 方法的作用,用来在一个请求过程中传递处理的数据

public ModelAndView addObject(String attributeName, @Nullable Object attributeValue) {
    
    
	getModelMap().addAttribute(attributeName, attributeValue);
	return this;
}

public ModelAndView addObject(Object attributeValue) {
    
    
	getModelMap().addAttribute(attributeValue);
	return this;
}

public ModelAndView addAllObjects(@Nullable Map<String, ?> modelMap) {
    
    
	getModelMap().addAllAttributes(modelMap);
	return this;
}

使用示例

@RequestMapping("listCategory")
public ModelAndView listCategory() {
    
    

	ModelAndView mav = new ModelAndView();
	List<Category> cs= categoryService.list();
	mav.addObject("cs", cs);
	mav.setViewName("listCategory");
	return mav;
}

ModelMap

ModelMap 主要用于传递控制器方法处理数据到页面。ModelMap 使用 addAttribute()addAllAttributes() 方法向页面传递参数。用法等同于 Model

public ModelMap addAttribute(String attributeName, @Nullable Object attributeValue) {
    
    
	Assert.notNull(attributeName, "Model attribute name must not be null");
	this.put(attributeName, attributeValue);
   	return this;
}

public ModelMap addAttribute(Object attributeValue) {
    
    
	Assert.notNull(attributeValue, "Model object must not be null");
	return attributeValue instanceof Collection && ((Collection)attributeValue).isEmpty() ? this : this.addAttribute(Conventions.getVariableName(attributeValue), attributeValue);
}

public ModelMap addAllAttributes(@Nullable Collection<?> attributeValues) {
    
    
	if (attributeValues != null) {
    
    
    	Iterator var2 = attributeValues.iterator();
        while(var2.hasNext()) {
    
    
        	Object attributeValue = var2.next();
            this.addAttribute(attributeValue);
       	}
	}
	return this;
}

public ModelMap addAllAttributes(@Nullable Map<String, ?> attributes) {
    
    
	if (attributes != null) {
    
    
		this.putAll(attributes);
	}
	return this;
}

使用示例

@RequestMapping("listCategory")
public String xxxxmethod(String someparam, ModelMap model) {
    
    

    // 省略方法处理逻辑若干
	model.addAttribute("key",someparam);
	// 返回跳转地址
	return "success";
}

猜你喜欢

转载自blog.csdn.net/weixin_38192427/article/details/120844513
今日推荐