Nick H
Nick H

Reputation: 8992

How to inject HttpServletRequest into a non-resource class?

I have successfully injected the HttpServletRequest using the @Context inside my resource class.

Is it possible to inject the HttpServletRequest into a non-resource class? I have created a class that performs various network operations which require values stored inside HttpSession. For example...

public class RequestExecutor {

    @Context
    HttpServletRequest request;

    public Response performNetworkRequest(Request request) {

        // Do network request - I want to access the session without passing the session object around my code everywhere.
        return response;
    }
}

Is this possible?

Upvotes: 2

Views: 1326

Answers (1)

dur
dur

Reputation: 16979

You can't use @Context, see JSR-311 for JAX-RS 1.1 and JSR-339 for JAX-RS 2.0:

JAX-RS provides facilities for obtaining and processing information about the application deployment context and the context of individual requests. Such information is available to Application subclasses (see section 2.1), root resource classes (see chapter 3), and providers (see chapter 4).

You can also initialize sub resources:

The ResourceContext interface provides access to instantiation and initialization of resource or subresource classes in the default per-request scope. It can be injected to help with creation and initialization, or just initialization, of instances created by an application.

See also: ResourceContext#initResource

But you could use inheritance:

public abstract class AbstractResource {

    @Context
    HttpServletRequest request;

    protected Response performNetworkRequest() {
        // do something with request
    }
}

@Path("myResource")
public class MyResource extends AbstractResource {
    // some methods 
}

Upvotes: 1

Related Questions