java jax-rs拦截器_java – Servlet过滤器与CXF拦截器,用于修改请求和响应内容?

在这里回答我自己的问题…我最终使用了一个JAX-RS过滤器,一旦我缺少文档,它就能很好地运行.我使用了

http://cxf.apache.org/docs/jax-rs-filters.html的(相当稀疏的)文档.注意,尽管它的名字,JAX-RS过滤器是一个CXF特定的野兽,不是JAX-RS标准的一部分(据我所知).

以下是一些示例代码:

@Context

private HttpServletRequest httpRequest;

@Context

private UriInfo uriInfo;

/**

* @see org.apache.cxf.jaxrs.ext.ResponseHandler#handleResponse(org.apache.cxf.message.Message,org.apache.cxf.jaxrs.model.OperationResourceInfo,javax.ws.rs.core.Response)

*/

public Response handleResponse(Message message,OperationResourceInfo opResourceInfo,Response response) {

try {

// log the injected context data; useful for debugging CXF problems

logContextData(httpRequest,uriInfo);

OutputStream os = message.getContent(OutputStream.class);

String relevantData = getDataFromRequest(httpRequest);

message.setContent(OutputStream.class,new MyOutputStreamWrapper(os,relevantData));

} catch (CustomException e) {

// return some status that is related to CustomException

return Response.status(Status.UNAUTHORIZED).build();

} catch (Exception e) {

return Response.status(Status.INTERNAL_SERVER_ERROR).build();

}

return response;

}

/**

* @see org.apache.cxf.jaxrs.ext.RequestHandler#handleRequest(org.apache.cxf.message.Message,org.apache.cxf.jaxrs.model.ClassResourceInfo)

*/

public Response handleRequest(Message message,ClassResourceInfo classResourceInfo) {

try {

// log the injected context data; useful for debugging CXF problems

logContextData();

String updatedQueryString = buildNewQueryString(this.uriInfo,httpRequest);

message.put(Message.QUERY_STRING,updatedQueryString);

// returning null tells CXF to continue the request (i.e. a non-null value would halt the request)

return null;

} catch (CustomException e) {

// return some status that is related to CustomException

return Response.status(Status.UNAUTHORIZED).build();

} catch (Exception e) {

return Response.status(Status.INTERNAL_SERVER_ERROR).build();

}

}

我应该注意,MyOutputStreamWrapper的实现是修改响应内容的重要部分.由于安全考虑,我不能将这个源包含在这里(实际上我的实现具有不同的名称).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值