【问题标题】:Setting content-type of response in Spring 3.1 mvc webservice在 Spring 3.1 mvc webservice 中设置响应的内容类型
【发布时间】: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


【解决方案1】:

您应该注册自己的 HttpMessageConvertor(它现在应该使用 StringHttpMessageConverter,输出 text/plain,请参阅 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。

【讨论】:

  • 谢谢,我设法通过您描述的响应对象返回字符串来使其工作,如上所示。我也会看看尝试使用消息转换器来做到这一点。
猜你喜欢
  • 2011-04-06
  • 1970-01-01
  • 2015-03-10
  • 2014-10-21
  • 2012-04-20
  • 1970-01-01
  • 2010-12-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多