在Action组合中获取URL参数

4

我有一个在我的控制器中定义的拦截器(Action compositions)。 我需要在请求中访问我的url参数。

例如,对于下面配置文件中的一个条目,我如何在我的操作组合中访问Id参数?

GET /jobs/:id controllers.JobManager.getlist(id: Int)

我的Action方法拦截器类只有对Http.Context对象的引用。虽然可以访问请求体,但无法访问URL参数。

1个回答

1

请自行提取。在您的示例中,路径长度为6个字符加上ID的长度。

String path = ctx.request().path();
String id = path.substring(6, path.length());

此解决方案取决于路线长度。 或者,您可以将起始参数和结束参数传递给您的操作:
@With({ ArgsAction.class })
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface Args {

    int start() default -1;
    int end() default -1;

}

并在Action类中使用它来提取参数:

public class ArgsAction extends Action<Args> {

    @Override
    public Promise<Result> call(Context ctx) throws Throwable {
        final int start = configuration.start();
        final int end = configuration.end();
        if (start != -1) {
            final String path = ctx.request().path();
            String arg = null;
            if (end != -1) {
                arg = path.substring(start, end);
            } else {
                arg = path.substring(start, path.length());
            }
            // Do something with arg...
        }
        return delegate.call(ctx);
    }
}

在JobManager控制器中的用法:

@Args(start = 6)
public getlist(Integer id) {
    return ok();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接