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的實現類


這麼多子類,這裏沒法一一都展示,所以會從我們常用的開始,慢慢追加,然後通過單獨章節來介紹


 

 

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