2013-03-15 51 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

相關問題