2013-03-15 91 views
2

我在CXF(v2.6.3)@WebMethod中执行自己的渲染时设置Content-Type时遇到问题。如何在CXF @WebMethod中渲染自己的响应时设置内容类型

以下模式正常工作:

@Path("/foo") 
@WebService 
public class FooService { 
    @Path("/bar") 
    @Produces({ "text/plain" }) 
    @GET 
    @WebMethod 
    public String bar() { 
     return "hi"; 
    } 

这将返回"hi"到HTTP客户端与Content-Type: Content-Type: text/plain头这是我的期望。

然而,当我试图通过使用响应OutputStream做我自己的渲染,"hi"正常返回,但@Produces注释被忽略,则返回默认text/xml内容类型。即使我自己拨打setContentType(...)也是如此。

@Path("/heartbeat2") 
@Produces({ "text/plain" }) 
@WebMethod 
@Get 
public void heartbeat2() { 
    HttpServletResponse response = messageCtx.getHttpServletResponse(); 
    response.getOutputStream().write("hi".getBytes()); 
    // fails with or without this line 
    response.setContentType("text/plain"); 
} 

下面是输出:

HTTP/1.1 200 OK 
Content-Type: text/xml 
Content-Length: 2 
Connection: keep-alive 
Server: Jetty(8.1.9.v20130131) 

hi 

任何想法,我怎么能直接呈现我自己的输出到输出流设置适当的内容类型?提前致谢。

回答

2

我没有看到你在做什么错。至少应设置内容类型HttpServletResponse应该工作。无论如何,如果你使用javax.ws.rs.core.Response,你可以更好地控制你的回报。看看这个工程:

@Path("/foo") 
@WebService 
public class FooService { 
    @Path("/bar") 
    @GET 
    @WebMethod 
    public Response bar() { 
     return Response.ok().type("text/plain").entity("hi").build(); 
    } 
    ... 
+0

是的这是做到这一点的正确方法。非常感谢。 – Gray 2013-06-03 15:55:41

相关问题