Java 将参数从控制器传递到操作
我已经创建了action OnlyOwner,它可以获得两个用户,并且必须将它们返回给控制器。 下面是代码的解释: 控制器Java 将参数从控制器传递到操作,java,playframework,action,playframework-2.2,Java,Playframework,Action,Playframework 2.2,我已经创建了action 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{
@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
}
}
仅公共类所有者扩展操作。简单{
@凌驾
公共承诺调用(Http.Context ctx)抛出可丢弃的{
//在这里,我试图将长id传递给che控制器
Long id=(Long)ctx.args.get(“id”);//但它检索空值
User=User.findById(id);
User userLogged=//这里有另一个用户
//现在我想将两个用户都返回到控制器
}
}
执行此操作的代码是什么?您必须将对象放入HTTP上下文的参数中:
公共类应用程序扩展控制器{
@使用(仅限所有者类)
公共静态结果配置文件(长id){
返回ok(profile.render(user(),userLogged());//方法调用
}
私有静态用户(){
返回getUserFromContext(“userObject”);
}
私有静态用户userLogged(){
返回getUserFromContext(“userLoggedObject”);
}
私有静态用户getUserFromContext(字符串键){
返回(用户)Http.Context.current().args.get(键);
}
}
仅限公共类所有者扩展操作。简单{
@凌驾
公共承诺调用(Http.Context ctx)抛出可丢弃的{
//如果没有id作为查询参数(http://localhost:9000/?id=43443)
//但作为URL的一部分(http://localhost:9000/users/43443)您必须自己解析URL
Long id=Long.parseLong(ctx.request().getQueryString(“id”));
ctx.args.put(“userObject”,User.findById(id));
ctx.args.put(“userLoggedObject”,User.findById(2L));
返回委托呼叫(ctx);
}
}
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);
}
}