Dashboard > Spring Discuss > Working with Spring MVC > Multiple Views Based on File Extension
  Spring Discuss Log In View a printable version of the current page.  
  Multiple Views Based on File Extension
Added by Seth Ladd, last edited by Seth Ladd on Jul 03, 2004
Labels: 
(None)

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:

  1. Extract the extention from the URL.
  2. If no coresponding mapping is found then leave the viewName untouched.
  3. If coresponding mapping is found then:
    1. if it starts with '-' then append mapping value (-jstl in above example to the mapping name),
    2. 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:

http://localhost/index.mx
, 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:

xml.class=...

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

Site running on a free Atlassian Confluence Open Source Project License granted to Spring Framework. Evaluate Confluence today.
Powered by Atlassian Confluence, the Enterprise Wiki. (Version: 2.5.5 Build:#811 Jul 25, 2007) - Bug/feature request - Contact Administrators