Naresh Naresh - 3 months ago 33
reST (reStructuredText) Question

How can I call one jersey service from another service in java ? Also how can I inject HttpServletRequest object inside my AuthenticationFilter

While injecting HttpServletRequest object in Jersey 2.0 I get this exception ->

java.lang.IllegalStateException: Not inside a request scope
.

I tried injecting HttpServletRequest object in AuthenticationFIlter for getting client IP address, but it failed with above exception, But the same code worked in jersey 2.2.3 api perfectly.

package com.mkyong.rest;

import com.sun.jersey.spi.container.ContainerRequest;
import com.sun.jersey.spi.container.ContainerRequestFilter;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.core.Context;

public class AuthFilter implements ContainerRequestFilter {

@Context
HttpServletRequest request;

@Override
public ContainerRequest filter(ContainerRequest request) {

return null;
}

public static String getClientIP(HttpServletRequest request) {

return request.getRemoteAddr();
}

}

Answer

Your question is a bit confusing. You mentioned you are using Jersey 2.x, but you are actually using the Jersey 1.x API.

Jersey 1.x and Jersey 2.x use different package names:

  • Jersey 1.x: com.sun.jersey
  • Jersey 2.x: org.glassfish.jersey

In Jersey 2.x, you would have the following:

import java.io.IOException;

import javax.annotation.Priority;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Priorities;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.Context;
import javax.ws.rs.ext.Provider;

@Provider
@Priority(Priorities.AUTHENTICATION)
public class AuthenticationFilter implements ContainerRequestFilter {

    @Context
    private HttpServletRequest request;

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
        String remoteAddress = request.getRemoteAddr();
        ...
    }
}

The ContainerRequestFilter interface is in the javax.ws.rs.container package, which is part of the JAX-RS 2.0 API. And Jersey 2.x is the reference implementation of the JAX-RS 2.0 specification.