我正在尝试设置一个将返回 xml 的 spring 3.1 mvc webservice。我有一个方法将 xml 作为已经调用 getxmlforparam() 的字符串返回。下面是我到目前为止的代码片段,它总是返回正确的内容,但内容类型 = text/html.
除了我在下面尝试过的 RequestMapping 生成和 response.addHeader 技术之外,还有其他方法可以设置内容类型吗?
@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;
}
谢谢。
编辑:通过以下 MikeN 的建议直接写入响应对象的解决方案:
@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());
}
}
}