I know this is old but thought this might be of help to someone. I had a scenario where a CMS was providing the direction as to what view to render for a given content type. In this scenario it was crucial to have something in place for just this circumstance. Below is what I used to handle it.
First I injected the following into my controller
@Autowired
private InternalResourceViewResolver viewResolver;
@Autowired
private ServletContext servletContext;
Next I added this simple method to check for the existence of a view
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);
}
}
I used this like so:
if(!existsView("components/" + fragment.getTemplate().getId())) {
logger.warn("View for component " + fragment.getTemplate().getId() + " Not found. Rendering fallback.");
return new ModelAndView("components/notfoundfallback");
}
My notfoundfallback.jsp looked like this:
<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>
I hope this helps someone in the future. It worked in both standard Spring MVC and SpringBoot MVC.
Thanks,