Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Supporting multiple content types in a Spring-MVC controller

A Rails controller makes it very easy to support multiple content types.

respond_to do |format|
  format.js { render :json => @obj }
  format.xml
  format.html
end

Beautiful. In one controller action I can easily respond to multiple content types with plenty of flexibility as to what I wish to render, be it a template, a serialized form of my object, etc.

Can I do something similar to this in Spring-MVC? What is the standard for supporting multiple content types in Spring? I've seen solutions involving view resolvers, but this looks difficult to manage, especially if I want to support JSON in addition to xhtml and xml.

Any suggestions are appreciated, but the simpler and more elegant solutions will be appreciated more ;)

EDIT

If I'm incorrect in asserting that a view resolver is difficult to manage, please feel free to correct me and provide an example. Preferably one that can return xml, xhtml, and JSON.

like image 622
Samo Avatar asked Dec 09 '10 22:12

Samo


1 Answers

In Spring 3, you want to use the org.springframework.web.servlet.view.ContentNegotiatingViewResolver.

It takes a list of media type and ViewResolvers. From the Spring docs:

<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
  <property name="mediaTypes">
    <map>
      <entry key="atom" value="application/atom+xml"/>
      <entry key="html" value="text/html"/>
      <entry key="json" value="application/json"/>
    </map>
  </property>
  <property name="viewResolvers">
    <list>
      <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
      </bean>
    </list>
  </property>
  <property name="defaultViews">
    <list>
      <bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
    </list>
  </property>
</bean>
<bean id="content" class="com.springsource.samples.rest.SampleContentAtomView"/>

The Controller:

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class BlogsController {

    @RequestMapping("/blogs")
    public String index(ModelMap model) {
        model.addAttribute("blog", new Blog("foobar"));
        return "blogs/index";
    }    
}

You'll also need to include the Jackson JSON jars.

like image 141
Todd Avatar answered Nov 04 '22 01:11

Todd