Spring MVC – How to get client IP address

In Spring framework, you can @Autowired a HttpServletRequest in any Spring managed bean directly, and later get the client’s IP address from the request headers

WebUtils.java

package com.mkyong.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class WebUtils {

    private HttpServletRequest request;

    @Autowired
    public void setRequest(HttpServletRequest request) {
        this.request = request;
    }

    private static String getClientIp() {

        String remoteAddr = "";

        if (request != null) {
            remoteAddr = request.getHeader("X-FORWARDED-FOR");
            if (remoteAddr == null || "".equals(remoteAddr)) {
                remoteAddr = request.getRemoteAddr();
            }
        }

        return remoteAddr;
    }

}

References

  1. How to get client Ip Address in Java

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
Vikram Thakur
Guest
Vikram Thakur

This will not work. Its wrong !
The bean managed by spring is singleton by default and the request object injected will be a fixed request. So always you will get a common client IP address for the request which is first time injected.Instead of Injecting HttpServletRequest in WebUtils, you should take it as argument like getClientIp(HttpServletRequest request).

Rizwan Shaikh
Guest
Rizwan Shaikh

I agree with you. This is not going to work.

aaa
Guest
aaa

Not to say anything, but this wont even compile.. You cannot access request from static method since request is not static…

Kumar Pallav
Guest
Kumar Pallav

I dont know what Spring has to do in it , It is common Java API doing all work . HTTPServletRequest in Java no Spring , adding a component Yeah, but All Inboud Controller method do have access directly to HttpServletRequest