下面是一个简单的Spring Boot用户主页IP归属地显示功能的代码示例:
com.maxmind.geoip2
geoip2
2.7.0
geoip2介绍:
geoip2是一个国外提供IP数据库的,提供有免费的IP数据库,只需要注册他们的账号即可下载IP数据库。
@Component
public class IPUtils {
@Value("${geoip.db-location}")
private String dbLocation;
private DatabaseReader reader;
@PostConstruct
public void setup() throws IOException {
File database = new File(dbLocation);
reader = new DatabaseReader.Builder(database).build();
}
public String getIpAddress(HttpServletRequest request) {
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.getHeader("HTTP_CLIENT_IP");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getRemoteAddr();
}
return ipAddress;
}
public String getCountry(String ipAddress) throws IOException {
InetAddress inetAddress = InetAddress.getByName(ipAddress);
CityResponse response = reader.city(inetAddress);
return response.getCountry().getName();
}
}
3.在UserController中调用IPUtils获取IP地址和归属地信息:
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@Autowired
private IPUtils ipUtils;
@GetMapping("/{id}")
public UserDTO getUserById(@PathVariable Long id, HttpServletRequest request) throws IOException {
User user = userService.getUserById(id);
UserDTO userDTO = new UserDTO();
BeanUtils.copyProperties(user, userDTO);
String ipAddress = ipUtils.getIpAddress(request);
String country = ipUtils.getCountry(ipAddress);
userDTO.setIpAddress(ipAddress);
userDTO.setCountry(country);
return userDTO;
}
}
4.创建一个UserDTO,用于向前端返回用户信息和IP归属地信息:
public class UserDTO {
private Long id;
private String username;
private String email;
private Date createTime;
private String ipAddress;
private String country;
// getter/setter省略
}
5.在application.properties中配置GeoIP2数据库文件的位置:
geoip.db-location=/path/to/GeoLite2-City.mmdb
6.在前端页面中显示IP归属地信息:
- 用户ID:{{user.id}}
- 用户名:{{user.username}}
- 邮箱地址:{{user.email}}
- 注册时间:{{user.createTime}}
- IP地址:{{user.ipAddress}}
- 归属地:{{user.country}}