簡體   English   中英

將數據添加到Jersey中的Response對象

[英]Adding data to a Response object in Jersey

我正在嘗試使用Aspect為使用Around建議的javax.ws.rs.core.Response添加時間戳。

我是Java和Jersey的新手,我很難做到這一點。 我最接近的是:

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>

最簡單的解決方案是使所有實體類擴展一個具有方法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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM