[英]Adding data to a Response object in Jersey
I am trying to use an Aspect
to add a timestamp to a javax.ws.rs.core.Response
using an Around advice. 我正在尝试使用
Aspect
为使用Around建议的javax.ws.rs.core.Response
添加时间戳。
I'm new to Java and Jersey and I'm struggling to do this. 我是Java和Jersey的新手,我很难做到这一点。 The closest I have is this:
我最接近的是:
Object output = proceed();
Method method = ((MethodSignature) thisJoinPoint.getSignature()).getMethod();
Type type = method.getGenericReturnType();
if (type == Response.class)
{
System.out.println("We have a response!");
Response original = (Response) output;
output = (Object)Response.ok(original.getEntity(String.class).toString()+ " " + Double.toString(duration)).build();
}
return output;
The kind of response produced is always an application/JSON
. 产生的响应类型始终是
application/JSON
。 Basically I want to add another field to the JSON that says time:<val of duration>
. 基本上我想在JSON中添加另一个字段,表示
time:<val of duration>
。
The easiest solution is to make all your entity classes extend an interface which has a method getTime()
and setTime()
and then you can set the time value in your interceptor as shown below. 最简单的解决方案是使所有实体类扩展一个具有方法
getTime()
和setTime()
,然后您可以在拦截器中设置时间值,如下所示。
public interface TimedEntity {
long getTime();
void setTime(long time);
}
Your actual entity 你的实际实体
public class Entity implements TimedEntity {
private long time;
// Other fields, getters and setters here..
@Override
public long getTime() {
return time;
}
@Override
public void setTime(long time) {
this.time = time;
}
}
And your interceptor 和你的拦截器
Object output = proceed();
Method method = ((MethodSignature)thisJoinPoint.getSignature()).getMethod();
Type type = method.getGenericReturnType();
if (type == Response.class)
{
System.out.println("We have a response!");
Response original = (Response) output;
if (original != null && original.getEntity() instanceof TimedEntity) {
TimedEntity timedEntity = (TimedEntity) original.getEntity();
timedEntity.setTime(duration);
}
}else if (output instanceof TimedEntity) {
TimedEntity timedEntity = (TimedEntity) output;
timedEntity.setTime(duration);
}
return output;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.