otter606
otter606

Reputation: 355

spring MVC XmlViewResolver configuration

We're wanting to provide alternative PDF views as well as regular JSP views from our controllers and have added a ContentNegotiatingViewResolver and an XmlViewResolver to handle this. All the examples I've found, including the Spring docs, return a simple view name, which the XmlViewResolver maps to a bean ID in its views.xml file ( in our case, a bean that writes PDF to the HttpResponse).

However we have our jsps organised in subfolders of the location defined in our InternalResourceViewResolver.

E.g.,

<bean id="viewResolver" class= "org.springframework.web.servlet.view.InternalResourceViewResolver"  p:order="2">          
    <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
    <property name="prefix" value="/WEB-INF/pages/"/>
    <property name="suffix" value=".jsp"/>
 </bean>

So, from within our controller we return view names like "a/b/c" for a JSP that is in /WEB-INF/pages/a/b/c.jsp.

This works fine for JSPs, except that you can't have a bean id defined in views.xml as 'a/b/c'; it's not a valid bean ID. We've investigated several options that either don't work are not satisfactory:

  1. Put all JSPs in a single folder so that we can just use a bean-id-naming-compatible view name that can be resolved by an XmlViewResolver. This works but isn't ideal for organising our JSPs.
  2. Have multiple InternalResourceViewResolver definitions using different prefixes. This just doesn't work; the first resolver of this type does not return null if it fails to find a matching view, it just fails with an exception and subsequent ViewResolvers are not used.
  3. Use a separate controller method (or conditional code in the controller that returns the view name depending on what is the requested content type or URL suffix); these solutions seem to defeat the purpose of keeping a Controller ignorant of its views.
  4. Try using wild-cards in the location property of XmlViewResolver; this fails with an exception.

I'm sure there is a nice elegant solution but it is eluding me just now. Is there a better approach such that I can return a view name like 'a/b/c' which has the potential to be resolved by an XmlViewResolver ?

Thank you for any suggestions.

Richard

Upvotes: 1

Views: 1106

Answers (1)

otter606
otter606

Reputation: 355

Of course, bean aliases are the way to go...after a bit of digging around:

In the views.xml file targetted by XmlViewResolver:

<bean id="PdfView" class="com.blah.PdfDocView" /> 
<alias name="PdfView" alias="/a/b/structuredDocument"/>

which maps '/a/b/structuredDocument' to the PdfDocView bean.

Upvotes: 1

Related Questions