简体   繁体   中英

How to get the sender IP Address in spring integration?

I use Spring integration for Web service message handling. Unfortunately the Message does not contains the sender IP Address. How can I get this information?

@Bean
public SimpleWebServiceInboundGateway myInboundGateway() {
    SimpleWebServiceInboundGateway simpleWebServiceInboundGateway = new SimpleWebServiceInboundGateway();
    simpleWebServiceInboundGateway.setRequestChannelName("testChannel");
    simpleWebServiceInboundGateway.setReplyChannelName("testResponseChannel");
    return simpleWebServiceInboundGateway;
}

@ServiceActivator(inputChannel = "testChannel", outputChannel = "testResponseChannel")
public Message getHeaders(Message message) {
    // how can I reach the sender IP address here
    return message;
}

The SimpleWebServiceInboundGateway doesn't map transport headers by default. See DefaultSoapHeaderMapper . Of course you can implement your own, but that really might be enough for you to use:

((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
              .getRequest()
              .getRemoteAddr();

in that your target @ServiceActivator .

Of course that will work if you don't shift message to a different thread before the service activator. The RequestContextHolder.currentRequestAttributes() is tied with ThreadLocal .

You can retrieve it from HttpServletRequest, using getRemoteAddr() to get access to user IP address and getHeader() to get header value. This is assuming you can modify your controller class.

Perhaps this will help:

@Controller
public class MyController {
    @RequestMapping(value="/do-something")
    public void doSomething(HttpServletRequest request) {
        final String userIpAddress = request.getRemoteAddr();
        final String userAgent = request.getHeader("user-agent");
        System.out.println (userIpAddress);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM