2015-04-06 16 views
0

我使用的是play framework 2.0,它有一個非常簡單的流程... routes - > controllers - > service - > model - > controllers - > result。如何在intercepter中獲取路徑變量

那麼,在這之後,我有一個控制器從路由接收路徑變量。

GET /用戶/:用戶id controller.user.getUser(用戶名:字符串)

如,你可以看到,這其實是用戶ID,我要驗證此用戶ID(檢查對象是否存在於我們的數據庫或者沒有),但不是控制,而是使用一些註釋,這樣的事情..

//My annotation for validating userId 
@ValidateUserId(userId) 
public static Result getUser(userId) 

回答

0

的主要問題與這個概念是一個事實,即標註的PARAMS必須是不變,@see topic about this所以你會不能使用代碼中顯示的userId。相反,您可以創建一個註釋來讀取上下文本身,然後解析URI以獲取用戶的ID。即:

應用程序/ myannotations/MyAnnotations.class

package myannotations; 

import play.mvc.With; 

import java.lang.annotation.ElementType; 
import java.lang.annotation.Retention; 
import java.lang.annotation.RetentionPolicy; 
import java.lang.annotation.Target; 


public class MyAnnotations { 

    @With(ValidateUserIdAction.class) 
    @Target({ElementType.TYPE, ElementType.METHOD}) 
    @Retention(RetentionPolicy.RUNTIME) 
    public @interface ValidateUserId { 
     String patternToReplace(); 
     String redirectTo(); 
    } 

} 

應用程序/ myannotations/ValidateUserIdAction.class

package myannotations; 

import play.mvc.Action; 
import play.mvc.Http; 
import play.mvc.Result; 

import static play.libs.F.Promise; 

public class ValidateUserIdAction extends Action<MyAnnotations.ValidateUserId> { 

    public Promise<Result> call(Http.Context ctx) throws Throwable { 
     boolean isValid = false; 

     // This gets the GET path from request 
     String path = ctx.request().path(); 
     try { 
      // Here we try to 'extract' id value by simple String replacement (basing on the annotation's param) 
      Long userId = Long.valueOf(path.replace(configuration.patternToReplace(), "")); 

      // Here you can put your additional checks - i.e. to verify if user can be found in DB 
      if (userId > 0) isValid = true; 

     } catch (Exception e) { 
      // Handle the exceptions as you want i.e. log it to the logfile 
     } 

     // Here, if ID isValid we continue the request, or redirect to other URL otherwise (also based on annotation's param) 
     return isValid 
       ? delegate.call(ctx) 
       : Promise.<Result>pure(redirect(configuration.redirectTo())); 
    }  
} 

所以你可以用你的行動,比如用它

@MyAnnotations.ValidateUserId(
    patternToReplace = "/user/", 
    redirectTo = "/redirect/to/url/if/invalid" 
) 
public static Result getUser(userId){ 
    .... 
} 

當然,這是非常基本的示例,您可能希望/需要使validationAction類中的條件更加複雜,或者添加更多參數以使其更通用,全由您決定。

+1

嗨@biesior謝謝,是的,它工作。但我想要一些方法來讀取要在方法中傳遞的參數,這樣我就不必分析路徑字符串。但還是謝謝你。 :) – 2015-04-14 07:07:55