的主要问题与这个概念是一个事实,即标注的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