[英]Handling Pre/Post Processing of CXF Requests
我们开始通过其CRUD操作审核服务器上的客户请求。
我们希望使用CXF筛选器对每个请求进行预处理和后处理,而不是调用审核类来记录请求。 我什么意思
我们想用旧值(在更改之前,对数据库执行GET操作)审核每个更新请求(包含JSON),但是仅在请求成功完成之后才将其记录到记录器中。
当抛出异常时(通过使用jaxsrs:providers标记和ExceptionMapper实现),我们已经在使用此方法来更改响应主体,但是我不明白如何将其用于请求的前后处理。
谢谢!
更新 :
好吧,我有点理解制作CXF拦截器所需要做的事情:
AbstractPhaseInterceptor
的类 super(Phase.[the-needed-pahse])
来决定您的拦截器何时运行( 这是所有传入/传出阶段的列表) handleMessage
因为它是继承的方法,在这里您将编写逻辑 web.xml
文件中 例如:
public void handleMessage(Message request) throws Fault {
try {
InputStream is = request.getContent(InputStream.class);
String reqBodyAsString = org.apache.commons.io.IOUtils.toString(is, "UTF-8");
IOUtils.closeQuietly(is);
// Do the logic
is = org.apache.commons.io.IOUtils.toInputStream(reqBodyAsString, "UTF-8");
request.setContent(InputStream.class, is);
org.apache.commons.io.IOUtils.closeQuietly(is);
}
catch (IOException ioe) {
ioe.printStackTrace();
}
}
和web.xml
文件:
<jaxrs:server id="[id]" address="[URL]">
<jaxrs:inInterceptors><!-- because we want it to run BEFORE the request logic -->
<ref bean="[interceptor-id]" />
</jaxrs:inInterceptors>
</jaxrs:server>
<bean id="[interceptor-id]" class="[package-path.interceptor-class-name]"/>
您可以看到,在阅读内容之后,我再次将其写回到了请求中。 那是因为我得到一个例外,说我的身体为null
。
这就是我遇到的问题,我有一个拦截器,但是在读取请求主体之后,似乎逻辑无法继续。
您正在使用请求流。 您需要在记录之前对其进行缓存,并在CXF消息中设置新的流
public void handleMessage(Message message) {
//Get the message body into payload[] and set a new non-consumed inputStream into Message
InputStream in = message.getContent(InputStream.class);
byte payload[] = IOUtils.readBytesFromStream(in); //log this
ByteArrayInputStream bin = new ByteArrayInputStream(payload);
message.setContent(InputStream.class, bin);
}
不需要关闭流。 注意还可以使用CXF默认日志记录拦截器https://stackoverflow.com/a/37820362/6371459
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.