Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the client IP address in a JAX-RS resource class without injecting the HttpServletRequest?

We are using JAX-RS 1.0 and I want to get the client IP address in my resource class. Currently I inject the HttpServletRequest as a method parameter and then get the IP address.

I want to make my code cleaner. I am thinking if I can use a MessageBodyReader class and set the IP address. But if I use a MessageBodyReader I have to unmarshall the XML to a Java object which is additional logic as far as I believe.

Can anyone please let me know how to get the client IP address without having to inject the HttpServletRequest.

like image 955
Krishna Chaitanya Avatar asked Nov 23 '25 05:11

Krishna Chaitanya


1 Answers

There's no magic. What you can do is wrap the HttpServletRequest into a CDI bean with request scope (@RequestScoped) and then inject this bean into your JAX-RS resource classes:

import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;

@RequestScoped
public class RequestDetails {

    @Inject
    private HttpServletRequest request;

    public String getRemoteAddress() {
        return request.getRemoteAddr();
    }
}
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

@Stateless
@Path("client-address")
public class ClientAddressResource {

    @Inject
    private RequestDetails requestDetails; 

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public Response getClientRemoteAddress() {
        return Response.ok(requestDetails.getRemoteAddress()).build();
    }
}

I know this approach is not much different from injecting the HttpServletRequest. But there's no magic.

like image 137
cassiomolin Avatar answered Nov 24 '25 22:11

cassiomolin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!