Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
263 views
in Technique[技术] by (71.8m points)

java - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...