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

目录

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

1.2、引入依赖包

1.3、编写工具包

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

2.1、sql语句

总结


 

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

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

1.2、引入依赖包

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

  <!-- IP地址转归属地 -->
        <dependency>
            <groupId>org.lionsoul</groupId>
            <artifactId>ip2region</artifactId>
            <version>2.6.4</version>
        </dependency>

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<String,String>  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<String,String> 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<UserMapper, User> implements UserService {
    @Autowired
    UserMapper userMapper;

    /**
     * 用户登录 并设置token
     *
     * @param userDTOLogin
     */
    @Override
    public UserLoginVO Login(UserDTOLogin userDTOLogin) {
        // 其他逻辑 ......
        Map<String, String> 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及归属地,和登录的最后时间

5e461e19687441679ac833dcffa7cb67.png

总结

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

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

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

2e7e2ddbecd340d3bd4150ff6dc038b0.jpg

 

  • 4
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

树若逝花若殇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值