簡體   English   中英

如何檢查視圖是否存在?

[英]How do I check if a view exists?

我想在實際解決之前檢查視圖是否存在。 這是我的控制器,有一些關於我希望它如何工作的評論。

@RequestMapping(value="/somethinghere/")
    public String getSomething(Model inModel,
            @RequestParam(value="one", defaultValue=Constant.EMPTY_STRING) String one,
            @RequestParam(value="two", defaultValue = Constant.EMPTY_STRING) String two) {
        String view = one + two;
         if (a view with name equal to one + two exists) {
            return view;
        } else {
            return "defaultview";
        }                
}

我想返回一個視圖,但只有當我確認確實存在一個定義了該名稱的視圖時。 我該怎么做?

首先,考慮如何在 Spring 中完成視圖解析。 假設您正在使用InternalResourceViewResolver ,默認情況下或顯式聲明,創建InternalResourceView對象並通過連接InternalResourceViewResolver的前綴、視圖名稱(由您的處理程序返回)和后綴來解析資源路徑。

返回該View對象。 請注意,對於InternalResourceViewResolver ,該對象不能為null ,因此無法實現ViewResolver鏈接 DispatcherServlet然后使用返回的View對象的render()方法來創建 HTTP 響應。 在這種情況下,它將使用RequestDispatcher並將視圖名稱描述的資源轉發給它。 如果該資源不存在,則Servlet容器將產生 404 響應。

鑒於所有這些,除非您的Viewjsp或相關資源完全不同,否則在容器實際使用RequestDispatcher轉發請求之前,無法檢查資源是否存在。

您將不得不重新考慮您的設計。

我知道這很舊,但認為這可能對某人有幫助。 我有一個場景,CMS 提供了關於為給定內容類型呈現什么視圖的方向。 在這種情況下,為這種情況准備一些東西是至關重要的。 下面是我用來處理它的。

首先,我將以下內容注入我的控制器

@Autowired
private InternalResourceViewResolver viewResolver;

@Autowired
private ServletContext servletContext;

接下來我添加了這個簡單的方法來檢查視圖是否存在

private boolean existsView(String path) {
    try {
        JstlView view = (JstlView) viewResolver.resolveViewName(path, null);
        RequestDispatcher rd = null;
        URL resource = servletContext.getResource(view.getUrl());
        return resource != null;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

我這樣使用它:

    if(!existsView("components/" + fragment.getTemplate().getId())) {
        logger.warn("View for component " + fragment.getTemplate().getId() + " Not found. Rendering fallback.");
        return new ModelAndView("components/notfoundfallback");
    }

我的 notfoundfallback.jsp 看起來像這樣:

<div class="contact-form">
    <div class="contact-form__container container">
        <div class="contact-form__content" style="background-color: aliceblue;">
            <div class="contact-form__header">
                <h2>No design for content available</h2>
                <span>
                    You are seeing this placeholder component because the content you wish to see
                    doesn't yet have a design for display purposes. This will be rectified as soon as possible.
                </span>
            </div>
        </div>
    </div>
</div>

我希望這對未來的人有所幫助。 它適用於標准 Spring MVC 和 SpringBoot MVC。

謝謝,

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM