2016-03-08 44 views
1

我有一個JAX-RS web服務,它返回如下所示的Response對象(它在WebLogic 12.2.1中運行)。它會向客戶端返回一個JSON響應。是否可以編寫攔截器或過濾器,以便在返回Web服務調用時,它會在JSON響應中添加額外的字段?攔截JAX-RS web服務響應以添加JSON字段

@POST 
@Consumes(MediaType.APPLICATION_JSON) 
@Produces(MediaType.APPLICATION_JSON) 
@Path("LogIn") 
public Response logIn(@Context HttpServletRequest request, Parameters requestParameters) {...} 

在此先感謝。

+0

您正在使用哪種JAX-RS實現?如果澤西那麼你可以嘗試執行'ContainerResponseFilter'。 在超越'filter()'的時候,它提供了'ContainerResponseContext'對象,它允許你訪問使用'getEntity()'方法發送的響應。您可以修改此對象並將其設置迴應答中。 –

+0

我正在使用澤西島。我嘗試了你的建議。有用。非常感謝!你能把它作爲答案發布嗎? – user3573403

+0

我已將它更新爲答案。請接受它,如果工作。 –

回答

1

如果使用Jersey,那麼您可以嘗試執行ContainerResponseFilter

On Over-riding filter(),它提供ContainerResponseContext對象,它允許您訪問使用getEntity()方法發送的響應。

您可以修改此對象並將其設置迴應答中。

public class ResponseInterceptor implements ContainerResponseFilter{ 

    @Override 
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) 
      throws IOException { 
     Object obj = responseContext.getEntity(); 
     // Modify the Response obj as per need 
     responseContext.setEntity(obj); 
    } 
}