Spring MVC –如何获取客户端IP地址

2022-06-22 00:00:00 客户端 获取 地址

在Spring框架中,您可以直接@Autowired在任何Spring托管Bean中直接使用HttpServletRequest ,然后再从请求标头中获取客户端的IP地址。

WebUtils.java

package com.mkyong.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class WebUtils {

    private HttpServletRequest request;

    @Autowired
    public void setRequest(HttpServletRequest request) {
        this.request = request;
    }

    private static String getClientIp() {

        String remoteAddr = "";

        if (request != null) {
            remoteAddr = request.getHeader("X-FORWARDED-FOR");
            if (remoteAddr == null || "".equals(remoteAddr)) {
                remoteAddr = request.getRemoteAddr();
            }
        }

        return remoteAddr;
    }

}

参考文献

  1. 如何在Java中获取客户端IP地址

标签:
IP地址
请求标头
SpringMVC

翻译自: https://mkyong.com/spring-mvc/spring-mvc-how-to-get-client-ip-address/

    原文作者:cyan20115
    原文地址: https://blog.csdn.net/cyan20115/article/details/106549289
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。

相关文章