2

我正在尝试设置一个将返回 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());
    }
  }
}
4

1 回答 1

0

您应该注册自己的 HttpMessageConvertor(它现在应该使用 StringHttpMessageConverter,它输出文本/纯文本,请参阅http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/http /converter/StringHttpMessageConverter.html),或者您应该自己处理整个请求。

后者可能是最简单的,但 Spring-MVC'ish 最少。您只需返回 null,并使用响应对象来写入结果。

Spring-MVC 方法是在 HttpMessageConverter 中实现从内部对象到 XML 的映射,并从 MVC 控制器函数返回内部对象和 @ResponseBody。

于 2012-11-08T19:47:00.097 回答