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;
}
}
Not to say anything, but this wont even compile.. You cannot access request from static method since request is not static…
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).
I agree with you. This is not going to work.
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
The side is wok fine, HttpServert is a Session Scope injection
I’m using this in production for blocking brute force and the truth is this is working fine! You are wrong!
Its not going to work because always request ipaddress will be same once HttpServletRequest @Autowired.
Probably should update your site…
That’s so bad. “”Developers”” showing beginners tutorials that are not even working… And I mean look at the start page of “Mykong.com”. It looks like its made from a child.
fwiw, your comments make you sound like a child. Just gross… Mkyong puts all this effort into his site only for you to complain about his hard work over an error and a style you don’t like? Grow up.