Announcement Announcement Module
No announcement yet.
SpringMVC + velocity to render XML? Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • SpringMVC + velocity to render XML?

    In advance, pardon my ignorance -- I've only been using the framework for a few months now, and am still pretty green.

    I'm on a project that's using Spring, SpringMVC, Hibernate and Velocity all running on Tomcat.

    When tasked with adding RSS output, I followed the same strategem that'd we'd followed for every other view: I added a mapping to SimpelUrlHandler, then created a controlle and a velocity template.

    To accomodate the fact that RSS is XML, I simply added a resposne.setContentType("text/xml") in the controller before returning the ModelAndView.

    However, it appears that by the time the execution chain finishes, this has been overridden, as the content type returned is instead "text/html".

    From (now) reading the manual, it seems a better approach would have been to use an xsltview.

    However, I thought I'd check before I go re-working what i've done.

    Is there a way to ouput XML in SpringMVC while still using velocity to render the view?

  • #2
    To set the content type safely, you need to do it at the view or view resolver level.

    You can use Velocity to generate the XML since Velocity is perfectly capable of creating any text content. However, I would recommend using an extension of AbstractXsltView (leaving the stylesheetLocation property as null). In doing so, you only need create the Source object using your favourite XML API (W3C, Dom4J, JDOM) and not worry about rendering anything.



    • #3
      Got it working

      Thanks for the help. I ended up getting it working via an alternate route:

      I subclassed VelocityViewResolver and VelocityToolBoxView, and in my new VelocityXMLView overrode mergeTemplate as follows:

      protected void mergeTemplate(Template template, Context context, HttpServletResponse response) throws Exception {
      template.merge(context, response.getWriter());

      And it worked like a charm. Given the work i'd already put into the templates (and the deadline I'm under), this was the easiest route. Next time, however, I'll extend AbstractXsltView if I need XML output.


      • #4
        This also works.

        <bean id="viewResolver"
        class="org.springframework.web.servlet.view.veloci ty.VelocityViewResolver">
        <property name="cache" value="false" />
        <property name="prefix" value="" />
        <property name="suffix" value=".vm" />
        <property name="contentType" value="text/xml"></property>