Передача аргумента от контроллера к действию

Я создал действие OnlyOwner с композицией действий, которое получает двух пользователей и верните их контроллеру. Здесь поясняется код:

Контроллер

@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
    }
}

Какой код для этого?


person Fred K    schedule 20.11.2013    source источник


Ответы (1)


Вы должны поместить объекты в аргументы контекста HTTP: 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);
    }
}
person Schleichardt    schedule 20.11.2013