我创建了带有action composition的动作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
}
}
这样做的代码是什么?
答案 0 :(得分: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);
}
}