Is there any way in Spring 3 MVC to gain access to the request header information (like source IP address etc.), when parsing a request in a @Controller?
1 Answer
You can retrieve it from HttpServletRequest, using getRemoteAddr() to get access to user IP address and getHeader() to get header value.
For example
@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");
....
}
}
You may pass other parameters to the doSomething() method, like model or request params.
6 Comments
Nico Huysamen
Thanks. I was actually busy deleting my post when I got the notification. Figured it out. Thanks anyway!
Sumit Ramteke
if client is behind proxy server then possible solution would by using
String ip = req.getHeader("X-FORWARDED-FOR");Sumit Ramteke
and then handling it with condition like
if (ip == null) ip = request.getRemoteAddr();Amr Mostafa
Since
request.getRemoteAddr() is standard Servlets specification API that gets used not only in your code but in other 3rd party components as well, the right approach when behind a proxy is to plug in an implementation of HttpServletRequest that's aware of proxy headers. If you are using tomcat (for example), then you do that by adding <Valve className="org.apache.catalina.valves.RemoteIpValve" /> to your server.xml.user2914191
@Normal the IP comes from socket connection not from headers
|