0

I am trying to access httpServletRequest inside a component class. I tried it in several ways.

@Component
public class MyService{

 @Resource
 WebServiceContext wsCtxt;

 public void myWebMethod(){
  MessageContext msgCtxt = wsCtxt.getMessageContext();
  HttpServletRequest req = ( 
  (HttpServletRequest)msgCtxt.get(MessageContext.SERVLET_REQUEST);
  String clientIP = req.getRemoteAddr();
}

This didn't work for me. because WebServiceContext is always null. Then I tried same code inside Web service class. Then that code is working. My Requirement it to get HttpServletRequest inside component class. (ultimately What i am trying to do it get client host from request header). It this possible to do ?. Are there any alternatives for this ?

2
  • Just curious to know why you want to do that? Commented Jun 15, 2018 at 4:15
  • we are having a different environment such as test, dev, production. Current implementation of our project is to get default host as a localhost. but we can override host from vm options. like -Dserver_url=test.xxx.com , then web service will call other web services in test environment. Now we are going to get host from header which is sent through nginx. Commented Jun 15, 2018 at 5:14

1 Answer 1

2

Method #1

Have you tried passing the request object into your component by passing it in as an argument to your service method, and from your service to your component method?

// in your controller... Spring provides the request object
public String myController(HttpServletRequest request, ...) {
    //...
    myService.myServiceMethod(request,...);
}

// in your service...
public void myServiceMethod(HttpServletRequest request, ...) {
    //...
    myComponent.myWebMethod(request,...);
}

// in your component
public String myWebMethod(HttpServletRequest request, ...) {

    // use the raw request object
}

Method #2

Also, DispatcherServlet exposes the request object by wrapping it in a ServletRequestAttributes object, which in turn is stored in a ThreadLocal variable. The actual storing takes place in RequestContextHolder and its static methods. You can access it as follows:

public void myWebMethod(){
    //...

    RequestAttributes reqAttr = RequestContextHolder.getRequestAttributes();
    ServletRequestAttributes servlReqAttr = (ServletRequestAttributes)reqAttr;
    HttpServletRequest req = servlReqAttr.getRequest();

    //...

}

Although a little verbose, you can see what's going on.

You could also condense it:

((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();

I hope this helps!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.