`
nicegege
  • 浏览: 590834 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Spring的ModelAndView类

阅读更多

项目中controller的方法跳转的到ModelAndView类,一直很好奇spring怎么实现的?

/*
 * Copyright 2002-2010 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.web.servlet;

import java.util.Map;

import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;

/**
 * Holder for both Model and View in the web MVC framework.
 * Note that these are entirely distinct. This class merely holds
 * both to make it possible for a controller to return both model
 * and view in a single return value.
 *
 * <p>Represents a model and view returned by a handler, to be resolved
 * by a DispatcherServlet. The view can take the form of a String
 * view name which will need to be resolved by a ViewResolver object;
 * alternatively a View object can be specified directly. The model
 * is a Map, allowing the use of multiple objects keyed by name.
 *
 * @author Rod Johnson
 * @author Juergen Hoeller
 * @author Rob Harrop
 * @see DispatcherServlet
 * @see ViewResolver
 * @see HandlerAdapter#handle
 * @see org.springframework.web.servlet.mvc.Controller#handleRequest
 */
public class ModelAndView {

	/** View instance or view name String */
	private Object view;

	/** Model Map */
	private ModelMap model;

	/** Indicates whether or not this instance has been cleared with a call to {@link #clear()} */
	private boolean cleared = false;


	/**
	 * Default constructor for bean-style usage: populating bean
	 * properties instead of passing in constructor arguments.
	 * @see #setView(View)
	 * @see #setViewName(String)
	 */
	public ModelAndView() {
	}

	/**
	 * Convenient constructor when there is no model data to expose.
	 * Can also be used in conjunction with <code>addObject</code>.
	 * @param viewName name of the View to render, to be resolved
	 * by the DispatcherServlet's ViewResolver
	 * @see #addObject
	 */
	public ModelAndView(String viewName) {
		this.view = viewName;
	}

	/**
	 * Convenient constructor when there is no model data to expose.
	 * Can also be used in conjunction with <code>addObject</code>.
	 * @param view View object to render
	 * @see #addObject
	 */
	public ModelAndView(View view) {
		this.view = view;
	}

	/**
	 * Creates new ModelAndView given a view name and a model.
	 * @param viewName name of the View to render, to be resolved
	 * by the DispatcherServlet's ViewResolver
	 * @param model Map of model names (Strings) to model objects
	 * (Objects). Model entries may not be <code>null</code>, but the
	 * model Map may be <code>null</code> if there is no model data.
	 */
	public ModelAndView(String viewName, Map<String, ?> model) {
		this.view = viewName;
		if (model != null) {
			getModelMap().addAllAttributes(model);
		}
	}

	/**
	 * Creates new ModelAndView given a View object and a model.
	 * <emphasis>Note: the supplied model data is copied into the internal
	 * storage of this class. You should not consider to modify the supplied
	 * Map after supplying it to this class</emphasis>
	 * @param view View object to render
	 * @param model Map of model names (Strings) to model objects
	 * (Objects). Model entries may not be <code>null</code>, but the
	 * model Map may be <code>null</code> if there is no model data.
	 */
	public ModelAndView(View view, Map<String, ?> model) {
		this.view = view;
		if (model != null) {
			getModelMap().addAllAttributes(model);
		}
	}

	/**
	 * Convenient constructor to take a single model object.
	 * @param viewName name of the View to render, to be resolved
	 * by the DispatcherServlet's ViewResolver
	 * @param modelName name of the single entry in the model
	 * @param modelObject the single model object
	 */
	public ModelAndView(String viewName, String modelName, Object modelObject) {
		this.view = viewName;
		addObject(modelName, modelObject);
	}

	/**
	 * Convenient constructor to take a single model object.
	 * @param view View object to render
	 * @param modelName name of the single entry in the model
	 * @param modelObject the single model object
	 */
	public ModelAndView(View view, String modelName, Object modelObject) {
		this.view = view;
		addObject(modelName, modelObject);
	}


	/**
	 * Set a view name for this ModelAndView, to be resolved by the
	 * DispatcherServlet via a ViewResolver. Will override any
	 * pre-existing view name or View.
	 */
	public void setViewName(String viewName) {
		this.view = viewName;
	}

	/**
	 * Return the view name to be resolved by the DispatcherServlet
	 * via a ViewResolver, or <code>null</code> if we are using a View object.
	 */
	public String getViewName() {
		return (this.view instanceof String ? (String) this.view : null);
	}

	/**
	 * Set a View object for this ModelAndView. Will override any
	 * pre-existing view name or View.
	 */
	public void setView(View view) {
		this.view = view;
	}

	/**
	 * Return the View object, or <code>null</code> if we are using a view name
	 * to be resolved by the DispatcherServlet via a ViewResolver.
	 */
	public View getView() {
		return (this.view instanceof View ? (View) this.view : null);
	}

	/**
	 * Indicate whether or not this <code>ModelAndView</code> has a view, either
	 * as a view name or as a direct {@link View} instance.
	 */
	public boolean hasView() {
		return (this.view != null);
	}

	/**
	 * Return whether we use a view reference, i.e. <code>true</code>
	 * if the view has been specified via a name to be resolved by the
	 * DispatcherServlet via a ViewResolver.
	 */
	public boolean isReference() {
		return (this.view instanceof String);
	}

	/**
	 * Return the model map. May return <code>null</code>.
	 * Called by DispatcherServlet for evaluation of the model.
	 */
	protected Map<String, Object> getModelInternal() {
		return this.model;
	}

	/**
	 * Return the underlying <code>ModelMap</code> instance (never <code>null</code>).
	 */
	public ModelMap getModelMap() {
		if (this.model == null) {
			this.model = new ModelMap();
		}
		return this.model;
	}

	/**
	 * Return the model map. Never returns <code>null</code>.
	 * To be called by application code for modifying the model.
	 */
	public Map<String, Object> getModel() {
		return getModelMap();
	}


	/**
	 * Add an attribute to the model.
	 * @param attributeName name of the object to add to the model
	 * @param attributeValue object to add to the model (never <code>null</code>)
	 * @see ModelMap#addAttribute(String, Object)
	 * @see #getModelMap()
	 */
	public ModelAndView addObject(String attributeName, Object attributeValue) {
		getModelMap().addAttribute(attributeName, attributeValue);
		return this;
	}

	/**
	 * Add an attribute to the model using parameter name generation.
	 * @param attributeValue the object to add to the model (never <code>null</code>)
	 * @see ModelMap#addAttribute(Object)
	 * @see #getModelMap()
	 */
	public ModelAndView addObject(Object attributeValue) {
		getModelMap().addAttribute(attributeValue);
		return this;
	}

	/**
	 * Add all attributes contained in the provided Map to the model.
	 * @param modelMap a Map of attributeName -> attributeValue pairs
	 * @see ModelMap#addAllAttributes(Map)
	 * @see #getModelMap()
	 */
	public ModelAndView addAllObjects(Map<String, ?> modelMap) {
		getModelMap().addAllAttributes(modelMap);
		return this;
	}


	/**
	 * Clear the state of this ModelAndView object.
	 * The object will be empty afterwards.
	 * <p>Can be used to suppress rendering of a given ModelAndView object
	 * in the <code>postHandle</code> method of a HandlerInterceptor.
	 * @see #isEmpty()
	 * @see HandlerInterceptor#postHandle
	 */
	public void clear() {
		this.view = null;
		this.model = null;
		this.cleared = true;
	}

	/**
	 * Return whether this ModelAndView object is empty,
	 * i.e. whether it does not hold any view and does not contain a model.
	 */
	public boolean isEmpty() {
		return (this.view == null && CollectionUtils.isEmpty(this.model));
	}

	/**
	 * Return whether this ModelAndView object is empty as a result of a call to {@link #clear}
	 * i.e. whether it does not hold any view and does not contain a model.
	 * <p>Returns <code>false</code> if any additional state was added to the instance
	 * <strong>after</strong> the call to {@link #clear}.
	 * @see #clear()
	 */
	public boolean wasCleared() {
		return (this.cleared && isEmpty());
	}


	/**
	 * Return diagnostic information about this model and view.
	 */
	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder("ModelAndView: ");
		if (isReference()) {
			sb.append("reference to view with name '").append(this.view).append("'");
		}
		else {
			sb.append("materialized View is [").append(this.view).append(']');
		}
		sb.append("; model is ").append(this.model);
		return sb.toString();
	}

}

 总结:

ModelAndView类是一个普通类,包含三个成员属性,

/** View instance or view name String */

private Object view;

/** Model Map */

private ModelMap model;

/** Indicates whether or not this instance has been cleared with a call to {@link #clear()} */

private boolean cleared = false;

 

属性view是一个Object对象,类中对view是字符串时,做了详细的逻辑处理。这里不写了以后补充。

属性model是一个ModelMap对象,ModelMap对象继承了 LinkedHashMap<String, Object>。这里有点奇怪为什么没用HashMap<String, Object>。

属性cleared是一个标识,代表是否请求是先清空ModeleAndView成员属性。

分享到:
评论

相关推荐

    Spring ModelAndView

    在Spring MVC中,`ModelAndView` 是一个关键类,用于封装处理结果和视图信息。 `ModelAndView` 类在处理完控制器逻辑后,用于存放模型数据和视图信息。模型数据是处理业务逻辑过程中生成的对象或值,它们会被传递到...

    springmvc关于modelAndView的使用详细

    在Spring MVC框架中,ModelAndView是一个非常重要的类,它用于处理控制器(Controller)与视图(View)之间的数据传递。本篇文章将深入探讨ModelAndView的使用细节,帮助你更好地理解和运用Spring MVC。 首先,理解...

    Spring+Mybatis框架 ModelAndView

    `ModelAndView` 是 Spring MVC 中的一个类,用于将处理结果(Model)和视图逻辑名(View)组合在一起。当控制器方法执行完毕,需要返回一个响应时,通常会创建一个 `ModelAndView` 对象,并添加数据到模型(Model)...

    使用SpringMVC的ModelAndView.zip

    `ModelAndView`是SpringMVC中的一个关键类,它在处理请求和返回响应的过程中起到重要作用。`ModelAndView`包含两个主要部分: - **Model**:模型部分,用于存储处理请求时产生的数据。这些数据可以通过`...

    SpringMVC ModelAndView-2021-04-11.txt

    SpringMVC将服务器处理后的结果返回并带给浏览器

    spring控制器代码

    Spring MVC中的控制器类通常会使用`@Controller`注解来标记。这个注解告诉Spring该类是处理HTTP请求的组件。例如: ```java @Controller public class MyController { // ... } ``` 2. **请求映射 - @...

    spring源码分析(1-10)

    Controller接口定义了处理请求的方法,视图解析器将Model数据渲染成视图,ModelAndView类则用于封装处理结果。 5. **Spring AOP**:AOP(Aspect Oriented Programming)允许在不修改源代码的情况下,添加交叉关注点...

    spring-web-5.2.3.RELEASE和spring-webmvc-5.2.3.RELEASE

    视图通常由模板引擎(如JSP、Thymeleaf或Freemarker)渲染,Spring MVC提供了ModelAndView或者Model接口来管理模型数据。 总的来说,Spring Web和Spring Web MVC是Spring框架的重要组件,它们为Java Web开发提供了...

    spring-petsore spring官方最新demo

    此外,Spring Data JPA配置了实体类,如`Vet`、`Owner`等,通过`@Entity`注解表示这些类为数据库表模型。 五、MVC视图解析 PetClinic使用Thymeleaf作为模板引擎,处理HTML视图的渲染。Thymeleaf允许我们在HTML中...

    Spring例子

    在`ModelAndView`或`Model`对象中添加数据,然后在控制器方法中返回视图名,如`"callNumber"`,Spring MVC会自动寻找对应的视图文件。 配置方面,Spring MVC的应用通常通过`web.xml`(传统方式)或Spring Boot的`...

    spring源码

    ModelAndView类结合了这两者,用于在Controller和View之间传递数据。 此外,Spring MVC还支持异常处理、本地化、主题和国际化等功能。通过HandlerExceptionResolver可以自定义异常处理策略,LocaleResolver用于处理...

    spring.jar spring-webmvc-struts.jar spring-webmvc.jar

    标题中的"spring.jar"、"spring-webmvc-struts.jar"和"spring-webmvc.jar"都是Spring框架相关的Java库文件,通常以.jar结尾的文件是Java的归档文件,包含了类、资源和元数据,用于Java应用程序的运行。这些文件在...

    Spring-4.3源码

    `ModelAndView`或`Model`接口用于向视图传递数据。 在事务管理方面,Spring 4.3提供了声明式事务处理,允许在方法级别定义事务边界。`@Transactional`注解可以标记在一个方法上,以开启一个事务。此外,Spring的...

    spring 整合spring mvc

    import org.springframework.web.servlet.ModelAndView; @Controller public class HelloWorldController { @RequestMapping(value = "/hello", method = RequestMethod.GET) public ModelAndView helloWorld...

    Spring4.X教学视频

    Spring框架是Java开发中最常用的轻量级开源框架之一,它以其强大的依赖注入(Dependency Injection,DI)和面向切面编程(Aspect-Oriented Programming,AOP)能力深受开发者喜爱。Spring4.X作为其一个版本,引入了...

    Spring的各种控制器

    import org.springframework.web.servlet.ModelAndView; public class SimpleController extends SimpleFormController { @RequestMapping("/example") public ModelAndView handleRequest(HttpServletRequest ...

    基本的spring mvc + spring security实现的登录(无数据库)

    - 通常包含src/main/java目录下的Controller、Service、DAO层以及配置类,src/main/resources下可能有Spring MVC和Spring Security的配置文件,webapp下是静态资源和视图文件。 7. **学习重点**: - 理解Spring ...

    spring 源码中文注释

    在Web MVC模块中,`DispatcherServlet`作为核心组件,负责请求的分发,`ModelAndView`和`HandlerMapping`等类则构成了模型-视图-控制器架构的基础。 此外,Spring框架也引入了JSR-330定义的依赖注入注解,如`@...

    SpringMVC ModelAndView、Model及Map、@SessionAttributes场景与应用

    在Spring MVC框架中,ModelAndView、Model、Map以及@SessionAttributes是四个关键概念,它们在处理请求、数据传输和会话管理中起着至关重要的作用。让我们深入探讨这些概念及其在实际开发中的应用场景。 首先,`...

    在Web项目中集成Spring

    在Web项目中集成Spring是一个常见的开发实践,Spring框架以其强大的依赖注入、面向切面编程以及丰富的功能模块,极大地简化了Java Web应用的开发。本文将深入探讨如何在Web项目中集成Spring,包括Spring MVC的使用、...

Global site tag (gtag.js) - Google Analytics