Access to request source IP in Spring 3 MVC web ap

2019-04-06 19:39发布

问题:

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:

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.