简体   繁体   中英

get url params in Action compositions

I have a Interceptor (Action compositions) defined for my controllers. I need to access my url params in the request

ie for an entry in conf below, how would I access the Id paramter inside my Action composition?

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

my Action method interceptor class only has reference to my Http.Context object. while access to the body of the request is evident the url param is not.

Extract it yourself. In your example path is 6 characters long plus length of id.

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

This solution depends on route's length. Alternatively, you can pass the start and end parameters to your action:

@With({ ArgsAction.class })
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface Args {

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

}

And use it in action class to extract parameter:

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);
    }
}

Usage in JobManager controller:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM