2017-04-06 94 views
1

我想用Aspect使用Around建議將時間戳添加到javax.ws.rs.core.Response將數據添加到澤西島的響應對象

我是新來的Java和澤西島,我努力做到這一點。我最接近的是這樣的:

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; 

那種產生響應的始終是一個application/JSON。基本上我想向JSON添加另一個字段,字段爲time:<val of duration>

回答

0

最簡單的解決方案是讓所有實體類擴展一個接口,該接口有一個方法getTime()setTime(),然後您可以在攔截器中設置時間值,如下所示。

public interface TimedEntity { 
    long getTime(); 

    void setTime(long time); 
} 

您的實際實體

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; 
    } 
} 

而且你的攔截器

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;