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, anInternalResourceView
object created and the path to the resource is resolved by concatenatingInternalResourceViewResolver
's prefix, view name (returned by your hanbdler), and suffix.That
View
object is returned. Note that withInternalResourceViewResolver
that object cannot benull
and thereforeViewResolver
chaining cannot be achieved. TheDispatcherServlet
then uses the returnedView
object'srender()
method to create the HTTP response. In this case it will use aRequestDispatcher
and forward to it the resource described by the View's name. If that resource doesn't exist, theServlet
container will produce a 404 response.Given all that, unless your
View
is something completely different than ajsp
or related resource, there's no way to check if the resource exists until the container actually forwards the request with aRequestDispatcher
.You will have to rethink your design.