我正在尝试设置将返回 xml 的 spring 3.1 mvc web 服务。我有一个将 xml 作为字符串返回的方法,该方法已称为 getxmlforparam()。 下面是我到目前为止的代码片段,它始终返回正确的内容,但内容类型 = text/html 错误。
除了我在下面尝试过的 RequestMapping produces 和 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());
}
}
}
最佳答案
您应该注册自己的 HttpMessageConvertor(它现在应该使用 StringHttpMessageConverter,输出文本/纯文本,请参阅 http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/http/converter/StringHttpMessageConverter.html),或者您应该自己处理整个请求。
后者可能是最简单的,但至少是 Spring-MVC 风格的。您只需返回 null,并使用响应对象写入结果。
Spring-MVC 方法是在 HttpMessageConverter 中实现从内部对象到 XML 的映射,并从 MVC Controller 函数中返回内部对象和@ResponseBody。
关于java - 在 Spring 3.1 mvc webservice 中设置响应的内容类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13294936/