springboot登录实现获取用户IP和登录时间

springboot登录实现获取用户IP和登录时间

目录

1、获取IP及查询该IP归属地

1.2、引入依赖包

1.3、编写工具包

2、实现登录修改IP地址和当前时间

2.1、sql语句

总结

前言:当我们在做用户登录的时候,需要看到自己所处哪个省份,我们可以通过获取当前的IP进行查询用户IP的归属地,省市都可以查得到

1、获取IP及查询该IP归属地

1.2、引入依赖包

在我们做获取IP以及归属地的操作时,我们必须引入一个依赖4

org.lionsoul

ip2region

2.6.4

1.3、编写工具包

随后我们编写一个专门用户获取IP及查询该IP的归属地工具包IpAddressUtil

这里虽然写了三个方法,有两个方法是获取IP,还有一个方法是根据该IP查询归属地,及其他的一些信息

package com.sxy.recordnetwork.Utils;

import com.fasterxml.jackson.databind.ObjectMapper;

import jakarta.servlet.http.HttpServletRequest;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.net.HttpURLConnection;

import java.net.URL;

import java.util.Map;

/**

* IP地址Util

*/

@Slf4j

public class IpAddressUtil {

/**

* 1.通过request对象获取IP

* 使用Nginx等反向代理软件, 则不能通过request.getRemoteAddr()获取IP地址

* 果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址,X-Forwarded-For中第一个非unknown的有效IP字符串,则为真实IP地址

*/

public static StringBuilder getIpAddr(HttpServletRequest request) {

String ip = null;

try {

ip = request.getHeader("x-forwarded-for");

if (ip == null || "unknown".equalsIgnoreCase(ip)) {

ip = request.getHeader("Proxy-Client-IP");

}

if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {

ip = request.getHeader("WL-Proxy-Client-IP");

}

if (ip == null || "unknown".equalsIgnoreCase(ip)) {

ip = request.getHeader("HTTP_CLIENT_IP");

}

if (ip == null || "unknown".equalsIgnoreCase(ip)) {

ip = request.getHeader("HTTP_X_FORWARDED_FOR");

}

if (ip == null || "unknown".equalsIgnoreCase(ip)) {

ip = request.getRemoteAddr();

}

} catch (Exception e) {

e.printStackTrace();

}

//使用代理,则获取第一个IP地址

if (ip == null) {

if (ip.indexOf(",") > 0) {

ip = ip.substring(0, ip.indexOf(","));

}

}

log.info("ip:" + ip);

return getAddress(ip);

}

/**

* 2.通过调用接口的方式获取IP

*/

public static Map getIp() {

try {

URL realUrl = new URL("http://whois.pconline.com.cn/ipJson.jsp");

HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();

conn.setRequestMethod("GET");

conn.setUseCaches(false);

conn.setReadTimeout(6000);

conn.setConnectTimeout(6000);

conn.setInstanceFollowRedirects(false);

int code = conn.getResponseCode();

StringBuilder sb = new StringBuilder();

String ip = "";

if (code == 200) {

InputStream in = conn.getInputStream();

BufferedReader reader = new BufferedReader(new InputStreamReader(in));

String line;

while ((line = reader.readLine()) != null) {

sb.append(line);

}

ip = sb.substring(sb.indexOf("ip") + 5, sb.indexOf("pro") - 3);

}

// 转json

StringBuilder address = getAddress(ip);

Map jsonMap = new ObjectMapper().readValue(address.toString(), Map.class);

// 结果如下

/**

* ip: ip

* pro: 省

* proCode: 省邮编

* city: 市

* cityCode: 市邮编

* region:

* regionCode:0

* addr:

* regionNames:

* err:

*/

// 返回出去

return jsonMap;

} catch (Exception e) {

e.printStackTrace();

return null;

}

}

/**

* 3.通过调用接口根据ip获取归属地

*/

public static StringBuilder getAddress(String ip) {

try {

URL realUrl = new URL("http://whois.pconline.com.cn/ipJson.jsp?ip=" + ip + "&json=true");

HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();

conn.setRequestMethod("GET");

conn.setUseCaches(false);

conn.setReadTimeout(6000);

conn.setConnectTimeout(6000);

conn.setInstanceFollowRedirects(false);

int code = conn.getResponseCode();

StringBuilder sb = new StringBuilder();

if (code == 200) {

InputStream in = conn.getInputStream();

BufferedReader reader = new BufferedReader(new InputStreamReader(in, "GBK"));//指定编码格式

String line;

while ((line = reader.readLine()) != null) {

sb.append(line);

}

}

return sb;

} catch (Exception e) {

e.printStackTrace();

return null;

}

}

}

很明显我们通过getIP方法来获取IP,在返回出去之前,调用getAddress方法传入IP,根据IP查询该IP的一些信息,及归属地 最终以Map返回出去

2、实现登录修改IP地址和当前时间

接着我们就在登录的逻辑中写相关操作,返回出来的是一个map集合我们通过get(key)方法,来获取ip,然后根据登录的用户名来修改,这里的用户名是唯一

package com.sxy.recordnetwork.service.impl;

//......

import java.time.LocalDateTime;

import java.util.Map;

@Service

@Slf4j

public class UserServiceImpl extends ServiceImpl implements UserService {

@Autowired

UserMapper userMapper;

/**

* 用户登录 并设置token

*

* @param userDTOLogin

*/

@Override

public UserLoginVO Login(UserDTOLogin userDTOLogin) {

// 其他逻辑 ......

Map ip = IpAddressUtil.getIp();

// 调用用户修改的方法,修改一下登录的最后时间,和登录的最后IP地址归属

// 查看IP是否为空

if (ip == null) {

throw new BaseException(Constants.UNKNOWN_ERROR.getValue());// 未知错误

}

// 修改最后登录的时间和IP

userMapper.updateLoginDateAndLoginIpByUserNameAndLoginIp(ip.get("pro"),userDTOLogin.getUserName());

// 实现登录逻辑

// ......

}

2.1、sql语句

mapper层的sql语句我们来看一下,这里的login_date = now()

这里的now()是sql中的一个函数,获取当前时间的函数

/**

* 修改登录时间,登录IP

* @param loginIp

* @param userName

*/

@Update("update user set login_date = now(), login_ip = #{loginIp} where user_name = #{userName}")

void updateLoginDateAndLoginIpByUserNameAndLoginIp(@Param("loginIp") String loginIp,@Param("userName") String userName);

上述操作完成后,我们就完成了获取用户的IP及归属地,和登录的最后时间

总结

总结:以上就是,如何通过用户登录时获取用户的IP的归属地等一些信息,获取登录的时间,往后可以根据这个继续扩展其他的一些操作。获取IP的归属地用到了一些网络协议

有什么问题还请各位在下方评论区留言,感谢支持!!!

更多内容请关注我的微信订阅号哦~

相关文章