SpringMVC的View模組用什麼實現?

2086nmj發表於2024-03-06

參考:https://blog.csdn.net/andy_zhang2007/article/details/99644770

介面View定義瞭如下兩個方法 :

1. String getContentType():返回Content-Type字串。如果不能提前確定,返回null。

2. render(@Nullable Map<String, ?> model, HttpServletRequest request, HttpServletResponse response):使用指定的資料模型model渲染頁面。如果沒有模型資料,model可以是null或者空物件。

為了提供更多便利,Spring MVC對介面View提供了抽象實現AbstractView,封裝了一些通用邏輯。框架某處,或者開發人員如果要實現一個View,繼承AbstractView做自己的擴充套件定製即可。

如上是Spring框架自身提供的一些View實現,從此清單可以看出,絕大多數繼承自AbstractView。

View介面:

package org.springframework.web.servlet;

import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.lang.Nullable;


public interface View {

    /**
     * Name of the HttpServletRequest attribute that contains the response status code.
     * Note: This attribute is not required to be supported by all View implementations.
     * @since 3.0
     */
    String RESPONSE_STATUS_ATTRIBUTE = View.class.getName() + ".responseStatus";

    /**
     * Name of the HttpServletRequest attribute that contains a Map with path variables.
     * The map consists of String-based URI template variable names as keys and their corresponding
     * Object-based values -- extracted from segments of the URL and type converted.
     * Note: This attribute is not required to be supported by all View implementations.
     * @since 3.1
     */
    String PATH_VARIABLES = View.class.getName() + ".pathVariables";

    /**
     * The org.springframework.http.MediaType selected during content negotiation,
     * which may be more specific than the one the View is configured with. For example:
     * "application/vnd.example-v1+xml" vs "application/*+xml".
     * @since 3.2
     */
    String SELECTED_CONTENT_TYPE = View.class.getName() + ".selectedContentType";


    /**
     * Return the content type of the view, if predetermined.
     * Can be used to check the view's content type upfront,
     * i.e. before an actual rendering attempt.
     * @return the content type String (optionally including a character set),
     * or null if not predetermined
     */
    @Nullable
    default String getContentType() {
        return null;
    }

    /**
     * Render the view given the specified model.
     * 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 a Map with name Strings as keys and corresponding model
     * objects as values (Map can also be null in case of empty model)
     * @param request current HTTP request
     * @param response he HTTP response we are building
     * @throws Exception if rendering failed
     */
    void render(@Nullable Map<String, ?> model, HttpServletRequest request, HttpServletResponse response)
            throws Exception;

}

相關文章