2013-11-20 54 views
3

我創建了動作OnlyOwner與action composition獲取兩個用戶,並必須將它們返回給控制器。 下面的代碼解釋:從控制器傳遞參數到動作

控制器

@With(OnlyOwner.class) // Call to the action 
public static Result profile(Long id) { 
    return ok(profile.render(user, userLogged)); 
} 

行動

public class OnlyOwner extends Action.Simple{ 

    @Override 
    public Promise<SimpleResult> call(Http.Context ctx) throws Throwable { 
     // Here I'm trying to get the Long id passed to che controller 
     Long id = (Long)ctx.args.get("id"); // but this retrieves a null 
     User user = User.findById(id); 
     User userLogged = // Here I get another user 
     // Now I want to return both the users to the controller 
    } 
} 

什麼是代碼這樣做呢?

回答

2

你必須把對象插入HTTP上下文的ARGS: http://www.playframework.com/documentation/2.2.x/api/java/play/mvc/Http.Context.html#args

public class Application extends Controller { 

    @With(OnlyOwner.class) 
    public static Result profile(Long id) { 
     return ok(profile.render(user(), userLogged()));//method calls 
    } 

    private static User user() { 
     return getUserFromContext("userObject"); 
    } 

    private static User userLogged() { 
     return getUserFromContext("userLoggedObject"); 
    } 

    private static User getUserFromContext(String key) { 
     return (User) Http.Context.current().args.get(key); 
    } 
} 


public class OnlyOwner extends Action.Simple { 
    @Override 
    public Promise<SimpleResult> call(Http.Context ctx) throws Throwable { 
     //if you have id not as query parameter (http://localhost:9000/?id=43443) 
     //but as URL part (http://localhost:9000/users/43443) you will have to parse the URL yourself 
     Long id = Long.parseLong(ctx.request().getQueryString("id")); 
     ctx.args.put("userObject", User.findById(id)); 
     ctx.args.put("userLoggedObject", User.findById(2L)); 
     return delegate.call(ctx); 
    } 
} 
相關問題