在 Spring-MVC 控制器中支持多种内容类型

发布于 2024-10-07 08:49:33 字数 473 浏览 3 评论 0原文

Rails 控制器可以非常轻松地支持多种内容类型。

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

美丽的。在一个控制器操作中,我可以轻松地响应多种内容类型,对于我希望呈现的内容具有足够的灵活性,无论是模板、对象的序列化形式等。

我可以在 Spring-MVC 中做类似的事情吗? Spring支持多种内容类型的标准是什么?我见过涉及视图解析器的解决方案,但这看起来很难管理,特别是如果我除了 xhtml 和 xml 之外还想支持 JSON。

任何建议都值得赞赏,但更简单、更优雅的解决方案将更受欢迎;)

编辑

如果我错误地断言视图解析器难以管理,请随时纠正我并提供一个例子。最好能够返回 xml、xhtml 和 JSON。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

绝不放开 2024-10-14 08:49:33

在 Spring 3 中,您需要使用 org.springframework.web.servlet.view.ContentNegotiatingViewResolver。

它采用媒体类型和 ViewResolvers 列表。来自 Spring文档

<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"/>

控制器:

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";
    }    
}

您还需要包含 Jackson JSON jar。

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.

清晨说晚安 2024-10-14 08:49:33

这是工作示例控制器,它根据请求标头“Content-Type”呈现 JSON 和 HTML。

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MimeTypeUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class PersonService {
    @RequestMapping(value = "/persons/{userId}", method = RequestMethod.GET)
    public ResponseEntity<?> getPersonByName(@RequestHeader("Content-Type") String contentMediaType,
            @PathVariable("userId") String userId,@RequestParam("anyParam") boolean isAscending) throws IOException {

        Person person = getPersonById(userId);
        if (isJSON(contentMediaType)) {
            return new ResponseEntity<Person>(person, HttpStatus.OK);
        }

        return new ResponseEntity("Your HTML Goes Here", HttpStatus.OK);
        //Note: Above you could use any HTML builder framework, like HandleBar/Moustache/JSP/Plain HTML Template etc.
    }


    private static final boolean isJSON(String contentMediaType) {
        if ("application/json".equalsIgnoreCase(contentMediaType)) {
            return true;
        }

        return false;
    }

}

Here goes the working example controller, that renders JSON and HTML both based on request Header "Content-Type".

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MimeTypeUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class PersonService {
    @RequestMapping(value = "/persons/{userId}", method = RequestMethod.GET)
    public ResponseEntity<?> getPersonByName(@RequestHeader("Content-Type") String contentMediaType,
            @PathVariable("userId") String userId,@RequestParam("anyParam") boolean isAscending) throws IOException {

        Person person = getPersonById(userId);
        if (isJSON(contentMediaType)) {
            return new ResponseEntity<Person>(person, HttpStatus.OK);
        }

        return new ResponseEntity("Your HTML Goes Here", HttpStatus.OK);
        //Note: Above you could use any HTML builder framework, like HandleBar/Moustache/JSP/Plain HTML Template etc.
    }


    private static final boolean isJSON(String contentMediaType) {
        if ("application/json".equalsIgnoreCase(contentMediaType)) {
            return true;
        }

        return false;
    }

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文