8

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 1

37

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks. I was actually busy deleting my post when I got the notification. Figured it out. Thanks anyway!
if client is behind proxy server then possible solution would by using String ip = req.getHeader("X-FORWARDED-FOR");
and then handling it with condition like if (ip == null) ip = request.getRemoteAddr();
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.
@Normal the IP comes from socket connection not from headers
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.