的主要問題與這個概念是一個事實,即標註的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類中的條件更加複雜,或者添加更多參數以使其更通用,全由您決定。
嗨@biesior謝謝,是的,它工作。但我想要一些方法來讀取要在方法中傳遞的參數,這樣我就不必分析路徑字符串。但還是謝謝你。 :) – 2015-04-14 07:07:55