How to extract IP Address in Spring MVC Controller get call?
Solution 1:
The solution is
@RequestMapping(value = "processing", method = RequestMethod.GET)
public @ResponseBody ProcessResponse processData(@RequestParam("workflow") final String workflow,
@RequestParam("conf") final String value, @RequestParam("dc") final String dc, HttpServletRequest request) {
System.out.println(workflow);
System.out.println(value);
System.out.println(dc);
System.out.println(request.getRemoteAddr());
// some other code
}
Add HttpServletRequest request
to your method definition and then use the Servlet API
Spring Documentation here said in
15.3.2.3 Supported handler method arguments and return types
Handler methods that are annotated with @RequestMapping can have very flexible signatures.
Most of them can be used in arbitrary order (see below for more details).
Request or response objects (Servlet API). Choose any specific request or response type,
for example ServletRequest or HttpServletRequest
Solution 2:
I am late here, but this might help someone looking for the answer. Typically servletRequest.getRemoteAddr()
works.
In many cases your application users might be accessing your web server via a proxy server or maybe your application is behind a load balancer.
So you should access the X-Forwarded-For http header in such a case to get the user's IP address.
e.g. String ipAddress = request.getHeader("X-FORWARDED-FOR");
Hope this helps.