I’m trying to set up a spring 3.1 mvc webservice that will return xml. I have a method which returns the xml as a string already called getxmlforparam().
Below is a snippet of the code I have so far which always returns the correct content but with the wrong content-type = text/html.
Is there a way of setting the content type other than with the RequestMapping produces and response.addHeader techniques that I have tried below?
@Service
@RequestMapping(value="endpointname")
public class XmlRetriever {
//set up variables here
@RequestMapping(method = RequestMethod.GET, produces = "application/xml")
@ResponseBody
public String getXml(
@RequestParam(value = "param1") final String param1,
/*final HttpServletResponse response*/){
String result = null;
result = getxmlforparam(param1);
/*response.addHeader("Content-Type", "application/xml");*/
return result;
}
Thanks.
EDIT:
solution by writing straight to the response object per MikeN’s suggestion below:
@Service
@RequestMapping(value="endpointname")
public class XmlRetriever {
//set up variables here
@RequestMapping(method = RequestMethod.GET, produces = "application/xml")
@ResponseBody
public String getXml(
@RequestParam(value = "param1") final String param1,
final HttpServletResponse response){
String result = null;
result = getxmlforparam(param1);
response.setContentType("application/xml");
try{
PrintWriter writer = response.getWriter();
writer.write(result);
}
catch(IOException ioex){
log.error("IO Exception thrown when trying to write response", ioex.getMessage());
}
}
}
You should either register your own HttpMessageConvertor (it should now be using a StringHttpMessageConverter, which outputs text/plain, see http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/http/converter/StringHttpMessageConverter.html), or you should handle the whole request yourself.
The latter is probably the easiest, but the least Spring-MVC’ish. You just return null, and use the response object to write the result.
The Spring-MVC way would be to implement the mapping from your internal objects to XML in a HttpMessageConverter, and return your internal object together with @ResponseBody from your MVC controller function.