如何使用Spring MVC从POST请求返回XML响应?

时间:2013-07-15 23:06:33

标签: java spring post spring-mvc

我正在发送一个发送JSON的POST请求。 Controller选择JSON,处理JSON,我希望控制器以XML格式返回一些数据。

如何使用POST请求执行此操作?

@RequestMapping( value = Controller.RESOURCE_PATH + ".xml", headers = "Accept=application/json", produces = "*/*" )
public String exportXml( @RequestBody String requestJson ) throws IOException
{
    JSONObject json = JSONObject.fromObject( requestJson );
    Option option = new Option();
    option.processJson( json );

    return "";
}

1 个答案:

答案 0 :(得分:1)

有很多方法可以实现这一目标。一种是使用MarshallingView和XStreamMarshaller

首先将以下jar添加到类路径(maven依赖项):

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-oxm</artifactId>
  <version>${org.springframework-version}</version>
</dependency>
<dependency>
  <groupId>com.thoughtworks.xstream</groupId>
  <artifactId>xstream</artifactId>
  <version>1.4.4</version>
</dependency>

然后在spring xml配置上配置Marshaller

<bean id="xstreamMarshaller" class="org.springframework.oxm.xstream.XStreamMarshaller"/>

假设您有以下bean想要Marshal(即:显示为XML)

public class MyMessage {
  private String message;

  // getters & setters
}

在你的控制器类中注入org.springframework.oxm.Marshaller并让你的handler方法返回一个这样的MarshallingView:

@Controller
public class MyController {

  @Autowired private Marshaller marshaller;

  @RequestMapping("/helloxml")
  public MarshallingView helloxml(Model model) {
    MyMessage msg = new MyMessage();
    msg.setMessage("hello world");
    model.addAttribute("msg", msg);

    MarshallingView marshallingView = new MarshallingView(marshaller);
    marshallingView.setModelKey("msg"); // set what model attribute to display as xml

    return marshallingView;
  }
}

上述设置会在请求/helloxml时为您提供这样的xml

<com.gerrydevstory.xmlview.MyMessage>
  <message>hello world</message>
</com.gerrydevstory.xmlview.MyMessage>

当然,如果您处理许多XML编组,这不是一个很好的设置。在这种情况下,您应该利用视图解析器配置。

此外,XML元素的名称也可以别名以缩短它。查看XStream文档

最后,请记住,XStream只是Spring支持的众多编组器之一,也可以考虑JAXB,Castor,Jibx等。