SpringBoot中怎么从request请求头上获取到请求的ip地址呢
时间: 2024-02-24 16:59:45 浏览: 94
在Spring Boot中,可以使用HttpServletRequest来获取请求的IP地址,具体可以通过以下代码来实现:
```java
@Autowired
private HttpServletRequest request;
@RequestMapping(value = "/test")
public void test() {
String ipAddress = request.getHeader("X-Forwarded-For");
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("WL-Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getRemoteAddr();
}
System.out.println("IP地址:" + ipAddress);
}
```
在上述代码中,我们通过request.getHeader方法来获取请求头中的X-Forwarded-For、Proxy-Client-IP和WL-Proxy-Client-IP信息,如果这些信息都为空或为unknown,则使用request.getRemoteAddr方法获取客户端的IP地址。
阅读全文