Multiple views based on request URL extension (by Piotr Maj)
Problem
Force springframework to select different views depending on URL extention.
Solution
In web.xml map your extentions with the DispatcherServlet:
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.mx</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.xml</url-pattern>
</servlet-mapping>
In servlet context configuration file add interceptor:
<bean id="viewSelectorInterceptor"
class="pl.kernelpanic.web.interceptors.ViewSelectorInterceptor">
<property name="mappings">
<props>
<prop key="mx">-jstl</prop>
<prop key="xml">xml</prop>
</props>
</property>
</bean>
and add this interceptor to every handlerMappings.
ViewSelectorInterceptor works as follows:
- Extract the extention from the URL.
- If no coresponding mapping is found then leave the viewName untouched.
- If coresponding mapping is found then:
- if it starts with '-' then append mapping value (-jstl in above example to the mapping name),
- if it do not start with '-' then set mapping value as the view name.
The rest is simple. Use ResourceBundleViewResolver and add your view mappings. For example:
, controller has:
return new ModelAndView("index");
so the view mapping should look like:
index-jstl.class=...
index-jstl.url=/WEB-INF/jsp/index.jsp
Now, if you call http://localhost/index.xml
then you need the following mapping:
Note that if extention mapping is not prefixed with '-' it is possible to redirect all URLs with specified extention to one single view, f.e. XMLModelSerializer or whatever.
To make this work, use the attached ViewSelectorInterceptor