2013-10-11 92 views

回答

8

發現所以,你會開始這樣的過濾器:

public class TimeLoggingFilter implements EssentialFilter { 

    public EssentialAction apply(final EssentialAction next) { 

     return new TimeLoggingAction() { 

      @Override 
      public EssentialAction apply() { 
       return next.apply(); 
      } 

      @Override 
      public Iteratee<byte[], SimpleResult> apply(final RequestHeader rh) { 
       final long startTime = System.currentTimeMillis(); 

       return next.apply(rh).map(new AbstractFunction1<SimpleResult, SimpleResult>() { 

        @Override 
        public SimpleResult apply(SimpleResult v1) { 
         long time = logTime(rh, startTime); 
         List<Tuple2<String, String>> list = new ArrayList<Tuple2<String, String>>(); 
         Tuple2<String, String> t = 
           new Tuple2<String, String>("Request-Time", 
             String.valueOf(time)); 
         list.add(t); 
         Seq<Tuple2<String, String>> seq = Scala.toSeq(list); 
         return v1.withHeaders(seq); 
        } 

        @Override 
        public <A> Function1<SimpleResult, A> andThen(Function1<SimpleResult, A> g) { 
         return g; 
        } 

        @Override 
        public <A> Function1<A, SimpleResult> compose(Function1<A, SimpleResult> g) { 
         return g; 
        } 

       }, Execution.defaultExecutionContext()); 
      } 


      private long logTime(RequestHeader request, long startTime) { 
       long endTime = System.currentTimeMillis(); 
       long requestTime = endTime - startTime; 
       Logger.info(request.uri() + " from " + request.remoteAddress() + " took " + requestTime + " ms"); 

       return requestTime; 
      } 
     }; 
    } 

    public abstract class TimeLoggingAction extends 
      AbstractFunction1<RequestHeader, Iteratee<byte[], SimpleResult>> 
      implements EssentialAction {} 
} 

,然後在Global.java把它掛:

public <T extends EssentialFilter> Class<T>[] filters() { 
     return new Class[] { TimeLoggingFilter.class }; 
    } 

我今天我自己也在尋找一個類似的例子,但沒有發現任何東西 - 但這看起來很有效。

+0

非常好的答案。我成功地使用了它。我想知道爲什麼這不被接受。 – vizog

+0

我也很欣賞答案,解決了一個大問題。謝謝。 –

+0

我在創建可以選擇性禁用的自定義CSRF篩選器方面存在類似的問題。解決方案[這裏](http://stackoverflow.com/questions/21096729/how-to-selectively-disable-csrf-check-in-play-framework-2-java)在Scala中寫入新的過濾器定義,而我不知道如何將其轉換爲Java。 – plade