javaservletsjax-rs

How to get ServletRequest in any class using @Context or similar?


I've used @Context to access the HttpServletRequest in the past, and it's worked.

I've got another class where I've tried to use this, but it's not being assigned, (ie request is null)

@Context
HttpServletRequest request;

All I'm trying to do is get the request parameters in a class, without having to pass them through to each parent instance.

So how can I get request.getParameter("username") when request is assigning as null?


Solution

  • The only way I found I could do this was by passing it down the call stack, though I did manage to shorten up that call stack apporoach using Guice.

    To do this, I bound my Provider to the the request like so: bind(MyClass.class).toProvider(MyClassProvider.class).in(ServletScopes.REQUEST);

    and my provider simply looked like this:

    public static class MyClassProvider implements Provider<MyClass>
    {
        private HttpServletRequest request;
    
        @Inject
        public MyClassProvider(@Context HttpServletRequest request)
        {
            this.request = request;
        }
    
        @Override
        public MyClass get()
        {
            return new MyClass(request);
        }
    }
    

    So now when my class is created, it has the Request context available.