springmvc篇:【关于View】

View是springMVC的几个核心概念之一,如果你看过springmvc的源码,那么相信大家都知道View本身是个接口,他有很多的实现类。如果你还是个菜鸟,那么请你注意,我这里说的View可不是简单的MVC中的V,他不是指一个jsp页面或者一个HTML.他是SpringMVC中的一个类。它跟jsp或者html这些相关的呈现层有关系,但不是他们。下面我将详细来说明这个这个View。

当我刚刚开始看springmvc源码的时候,也以为所谓的View就是指呈现我们数据的jsp页面或者freemark这些东西。其实不然,那么到底什么是View呢?先来看下面一章图:


上图中绿色虚线为我们的jsp页面,而红色虚线框就是我们这里说的View,这样是不是明白什么是View了吧?View简单来说就是用来存放了要在页面上显示的内容的一个bean。这些内容在成为model,然后用View和Jsp或者其他模板组合起来,把模板中的内容渲染到jsp上,然后在变成了我们在浏览器上看到的最后的样子。

那么一个view到底跟那个jsp或者其他模板映射在一起呢?这个就是ViewResolver的工作了,我在其他章节介绍了这个东东。
下面来看看官方对于View的说明:
 

/**
 * MVC View for a web interaction. Implementations are responsible for rendering
 * content, and exposing the model. A single view exposes multiple model attributes.
 *
 * <p>This class and the MVC approach associated with it is discussed in Chapter 12 of
 * <a href="http://www.amazon.com/exec/obidos/tg/detail/-/0764543857/">Expert One-On-One J2EE Design and Development</a>
 * by Rod Johnson (Wrox, 2002).
 *
 * <p>View implementations may differ widely. An obvious implementation would be
 * JSP-based. Other implementations might be XSLT-based, or use an HTML generation library.
 * This interface is designed to avoid restricting the range of possible implementations.
 *
 * <p>Views should be beans. They are likely to be instantiated as beans by a ViewResolver.
 * As this interface is stateless, view implementations should be thread-safe.
 *
 */
public interface View {

	String RESPONSE_STATUS_ATTRIBUTE = View.class.getName() + ".responseStatus";
	String PATH_VARIABLES = View.class.getName() + ".pathVariables";
	String SELECTED_CONTENT_TYPE = View.class.getName() + ".selectedContentType";

	String getContentType();
	/**
	 * Render the view given the specified model.
	 * <p>The first step will be preparing the request: In the JSP case,
	 * this would mean setting model objects as request attributes.
	 * The second step will be the actual rendering of the view,
	 * for example including the JSP via a RequestDispatcher.
	 * @param model Map with name Strings as keys and corresponding model
	 * objects as values (Map can also be {@code null} in case of empty model)
	 * @param request current HTTP request
	 * @param response HTTP response we are building
	 * @throws Exception if rendering failed
	 */
	void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception;

}

简单翻译一下就是:MVC View 与web相互作用,View的实现类主要用来呈现内容,并导出model(数据模型,比如一个use对象,或者是一个简单的属性,比如username)。View就是一个bean,他们被某个ViewResolver实例化。然后通过view的redner方法可以将所有的model对象中存储的内容都放在reqeust的attributes中。然后在jsp中就可以通过request.getAttribute("")来获取了。

下面来看看View的实现类


这么多子类,这里没法一一都展示,所以会从我们常用的开始,慢慢追加,然后通过单独章节来介绍


 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章