【发布时间】:2012-11-08 17:58:28
【问题描述】:
我正在尝试设置一个将返回 xml 的 spring 3.1 mvc webservice。我有一个方法将 xml 作为已经调用 getxmlforparam() 的字符串返回。 下面是我到目前为止的代码的 sn-p,它始终返回正确的内容,但内容类型 = 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());
}
}
}
【问题讨论】:
-
关于您的解决方案的一个问题:是否还需要produce =“application/xml”?
标签: java web-services spring model-view-controller content-type