我需要拦截为特定 API 调用生成的来自服务器的响应并进行更改。
为此,我使用了 JAX-RS 'WriterInterceptor',并且还创建了一个 NameBinding。
但是服务器正在拦截来自服务器的每个响应。我在这里做错了什么?
下面显示的是我尝试过的代码。为什么名称绑定不起作用?(我已经验证,在调用其他 API 资源时,我使用名称绑定的特定方法不会被调用。)
名称绑定。
package com.example.common.cm.endpoint;
@Target({ElementType.TYPE, ElementType.METHOD})
@NameBinding
@Retention(RetentionPolicy.RUNTIME)
public @interface JSONtoJWT {}
拦截器。
package com.example.common.cm.endpoint;
@Provider
@JSONtoJWT
public class TestInterceptor implements WriterInterceptor {
private static final Log log = LogFactory.getLog(TestInterceptor.class);
@Override
public void aroundWriteTo(WriterInterceptorContext writerInterceptorContext) throws IOException, WebApplicationException {
log.info("interceptor invoked");
OutputStream outputStream = writerInterceptorContext.getOutputStream();
outputStream.write(("{\"message\": \"Message added in the writer interceptor in the server side\"}").getBytes());
writerInterceptorContext.setOutputStream(outputStream);
writerInterceptorContext.proceed();
log.info("Proceeded");
}
}
API 资源。
package com.example.cm.endpoint.u3.acc;
@Path("/u3/some-validation")
@Consumes({ "application/json; charset=utf-8" })
@Produces({ "application/json; charset=utf-8" })
public class SomeValidationApi {
@POST
@Path("/")
@JSONtoJWT
@Consumes({ "application/json; charset=utf-8" })
@Produces({ "application/json; charset=utf-8" })
public Response someValidationPost(@ApiParam(value = "validations post" ,required=true ) SomeValidationRequestDTO someValidationConsent)
{
return delegate.someValidationPost(someValidationConsent);
}
}
豆类.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxrs="http://cxf.apache.org/jaxrs" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd">
<import resource="classpath:META-INF/cxf/cxf.xml"/>
<context:property-placeholder/>
<context:annotation-config/>
<bean class="org.springframework.web.context.support.ServletContextPropertyPlaceholderConfigurer"/>
<bean class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer"/>
<jaxrs:server id="services" address="/">
<jaxrs:serviceBeans>
***Some other beans here***
<bean class="com.example.cm.endpoint.u3.acc.SomeValidationApi/>
</jaxrs:serviceBeans>
<jaxrs:providers>
<bean class="com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider"/>
<bean class="com.example.common.cm.endpoint.TestInterceptor"/>
</jaxrs:providers>
</jaxrs:server>
</beans>
当我使用上述方法时,服务器的每个响应都会被拦截并添加消息。但我只希望特定资源调用拦截器。
此外,除了带有 writerInterceptor 的 JAX-RS 拦截器之外,还有其他好的选择来实现这一点吗?