I would like to check if a view exists before I actually resolve it. Here is my controller, with some comments on how I'd like it to work.
@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";
}
}
I want to return a view, but only when I've verified that there is indeed a view with that name defined. How do I do this?
First, consider how view resolution is done in Spring. Assuming you are using a InternalResourceViewResolver
, by default or explicit declaration, an InternalResourceView
object created and the path to the resource is resolved by concatenating InternalResourceViewResolver
's prefix, view name (returned by your hanbdler), and suffix.
That View
object is returned. Note that with InternalResourceViewResolver
that object cannot be null
and therefore ViewResolver
chaining cannot be achieved. The DispatcherServlet
then uses the returned View
object's render()
method to create the HTTP response. In this case it will use a RequestDispatcher
and forward to it the resource described by the View's name. If that resource doesn't exist, the Servlet
container will produce a 404 response.
Given all that, unless your View
is something completely different than a jsp
or related resource, there's no way to check if the resource exists until the container actually forwards the request with a RequestDispatcher
.
You will have to rethink your design.