2014-10-10 17 views
3

Play Framework 2.1을 사용할 때 모든 HTTP 응답을 가로채는 방법이 있습니까? 내가 manipulating the response에 설명서를 읽은Play 2.1의 모든 응답 차단하기

import java.lang.reflect.Method; 

import play.GlobalSettings; 
import play.mvc.*; 
import play.mvc.Http.*; 
import views.html.*; 

public class Global extends GlobalSettings { 

    private static BasicAuthHandler AUTH; 

    @SuppressWarnings("rawtypes") 
    @Override 
    public Action onRequest(Request request, Method actionMethod) { 

     if (...) { 
      return new Action.Simple() { 

       @Override 
       public Result call(Context ctx) throws Throwable { 
        return unauthorized(); 
       } 
      }; 
     } 

     return super.onRequest(request, actionMethod); 
    } 
} 

하지만 그것은 단지 방법을 설명합니다

내가 모든 요청을 가로 챌 내 Global.java 파일에있다, 그러나 나는 또한 응답을 가로 채기 위해 찾고 있어요 것입니다 각 결과에 대해 개별적으로 수행 할 수 있습니다.

답변

3

TransactionalAction은 요청/응답 인터셉터의 한 예입니다. Action을 확장하고 컨트롤러 유형 또는 메소드를 대상으로하는 Transactional 주석을 제공합니다. 동작 주석 제어 방법

예 :

@Transactional 
public static Result ok(){ 
    return ok(); 
} 

More details.

액션 로깅 응답의 예 (마음, Transactional 같은 주석을 제공하지 않는 행위, Action.Simple을 확장) :

public class LogAction extends Action.Simple { 

    @Override 
    public F.Promise<Result> call(Http.Context ctx) throws Throwable { 
     F.Promise<Result> call = delegate.call(ctx); 
     return call.map(r -> { 
      String responseBody = new String(JavaResultExtractor.getBody(r, 0L)); 
      Logger.info(responseBody); 
      return r; 
     }); 
    } 
} 

사용, 방법 정의 :

@With(LogAction.class) 
public static Result ok(){ 
    return ok(); 
} 

사용법, 클래스를 정의 - 모든 방법이 가로 채기 :

@With(LogAction.class) 
public class BaseController extends Controller { 

    .... 

} 

당신 ca @With annotation을 좋아하지 않는다면 한 걸음 앞으로 나아가 야한다. 이 내가 가진 것을 뜻

public class LogAction extends Action<Log> { 
    // use configuration object to access your custom annotation configuration 
} 
+0

: 변경 LogAction 정의를,이 방법을 사용자 정의 주석이 매개 변수를 허용하는 경우

@Log public static Result ok(){ return ok(); } 

:

@With({ LogAction.class }) @Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) public @interface Log { } 

을하고이 방법을 사용 : 자신을 특수 효과에서 사용자 정의 결과를 반환하는 모든 컨트롤러 메소드 위에'@With()'주석을 추가 하시겠습니까? –

+0

클래스 또는 메서드 정의 수준에 넣을 수 있습니다. –