How to extract IP Address in Spring MVC Controller get call?

后端 未结 9 539
长发绾君心
长发绾君心 2020-11-28 04:04

I am working on Spring MVC controller project in which I am making a GET URL call from the browser -

Below is the url by which I am making a GET call from the browse

9条回答
  •  抹茶落季
    2020-11-28 04:48

    Put this method in your BaseController:

    @SuppressWarnings("ConstantConditions")
    protected String fetchClientIpAddr() {
        HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.getRequestAttributes())).getRequest();
        String ip = Optional.ofNullable(request.getHeader("X-FORWARDED-FOR")).orElse(request.getRemoteAddr());
        if (ip.equals("0:0:0:0:0:0:0:1")) ip = "127.0.0.1";
        Assert.isTrue(ip.chars().filter($ -> $ == '.').count() == 3, "Illegal IP: " + ip);
        return ip;
    }
    

提交回复
热议问题