我知道这很旧,但认为这可能对某人有所帮助。我有一个场景,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。
谢谢,