2015-04-06 32 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