在Java中獲取客戶端的IP地址可以通過ServletRequest對象來實現。具體步驟如下:
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import java.io.IOException;
@WebServlet("/your-servlet-url")
public class YourServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 獲取客戶端的IP地址
String ipAddress = request.getRemoteAddr();
System.out.println("Client IP Address: " + ipAddress);
}
}
注意:getRemoteAddr()方法獲取的是客戶端的IP地址,但是該地址可能是經過代理服務器的,因此不一定是客戶端真實的IP地址。如果需要獲取真實的IP地址,可以嘗試使用X-Forwarded-For頭部信息來獲取。