Mythul
Mythul

Reputation: 1807

How to return a XML response from a POST rquest with Spring MVC?

I am making a POST request which sends a JSON. The Controller picks up the JSON, processes the JSON and I want the controller to return some data in XML format.

How can I do that with a POST request?

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

Upvotes: 0

Views: 1206

Answers (1)

gerrytan
gerrytan

Reputation: 41123

There are many ways to achieve this. One is to use MarshallingView and XStreamMarshaller

Firstly add following jars to your classpath (maven dependencies):

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

Then configure a Marshaller on your spring xml configuration

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

Assuming you have following bean you want to Marshal (ie: display as XML)

public class MyMessage {
  private String message;

  // getters & setters
}

In your controller class inject org.springframework.oxm.Marshaller and have your handler method return a MarshallingView like this:

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

The above setup will give you xml like this when /helloxml is requested

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

Of course this isn't a very good setup if you deal with many XML marshalling. You should leverage view resolvers configuration in this case.

Also the name of XML element can be aliased too to shorten it. Check out the XStream documentation

Finally, keep in mind XStream is just one of many marshaller supported by Spring, also consider JAXB, Castor, Jibx etc.

Upvotes: 1

Related Questions