【问题标题】:Passing argument from Controller to Action将参数从控制器传递到动作
【发布时间】:2013-11-20 10:21:50
【问题描述】:

我创建了带有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
    }
}

执行此操作的代码是什么?

【问题讨论】:

    标签: java playframework action playframework-2.2


    【解决方案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);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多