实现一个用户登录时记录登录IP、地址、登陆人、登录时间的日志功能
1. 首先在beans包下写一个实体类
@Data
@NoArgsConstructor
@AllArgsConstructor
public class LoginLog implements Serializable {
private static final long serialVersionUID = -7440711887634642686L;
private int id;
private String ip; //登陆的ip
private String no; //登陆用户名账号
private Date createtime; //登陆的时间
private String location; //登陆的地址
public LoginLog(String ip, String no, Date createtime, String location) {
this.ip = ip;
this.no = no;
this.createtime = createtime;
this.location = location;
}
}
2. 在dao包下写接口需要方法和.xml文件
public interface LoginLogDAO {
//添加日志
int addLoginLog(LoginLog loginLog);
//查询全部日志
List<LoginLog> queryAllLoginLog();
}
<?xml version="1.0" encoding="UTF-8"?>
<!-- dtd:document type definition 配置文件规范 -->
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.kfr.www.dao.LoginLogDAO">
<select id="queryAllLoginLog" resultType="LoginLog">
select * from `loginlog`
</select>
<insert id="addLoginLog">
insert into `loginlog` (ip,`no`,createtime,location )
value (#{ip},#{no},#{createtime},#{location})
</insert>
</mapper>
3. 业务逻辑层service包接口写相应的方法及接口的实现
public interface LoginLogService {
//添加日志
int addLoginLog(LoginLog loginLog);
//查询全部日志
List<LoginLog> queryAllLoginLog();
}
@Service
public class LoginLogImpl implements LoginLogService {
@Autowired
private LoginLogDAO loginLogDAO;
@Override
@Transactional
public int addLoginLog(LoginLog loginLog) {
return loginLogDAO.addLoginLog(loginLog);
}
@Override
public List<LoginLog> queryAllLoginLog() {
return loginLogDAO.queryAllLoginLog();
}
}
4. 在controller包写相应的handler
//登陆
@RequestMapping("/userlogin")
public String findUser(HttpServletResponse response, HttpSession session, HttpServletRequest request,String ip,String city){
String username=request.getParameter("username");
String password=request.getParameter("password");
String auto = request.getParameter("auto");
User user=null;
try {
user = userService.findUser(username, password);
} catch (Exception e) {
e.printStackTrace();
}
if (user!=null){
//加入日志信息
Date date=new Date();
LoginLog loginLog=new LoginLog(ip,username,date,city);
int i = loginLogService.addLoginLog(loginLog);
if (auto!=null) {
//将用户名和密码存在cookie里
Cookie cookie = new Cookie("userinfo", username + "#" + password);
// Cookie cookie1 = new Cookie("userlog", ip + "#" + city);
//设置上下面路径
cookie.setPath("/");
//设置cookie过期时间
cookie.setMaxAge(60 * 60 * 24 * 14);
//放入
response.addCookie(cookie);
//response.addCookie(cookie1);
session.setAttribute("User", user);
return "index";
}
else {
session.setAttribute("User", user);
return "index";
}
}else {
return "redirect:/login";
}
}
- 前端登录界面
<!--下面一个开放的JS中有一个方法可以获取当前IP地址-->
<script src="http://pv.sohu.com/cityjson?ie=utf-8"></script>
<script type="text/javascript">
var ip=""; //所属的IP
var cityAndAddress=""; //登录的地区
$(function () {
//获取IP,页面加载的时候自动执行
//如果失效用这个 https://ipapi.co/json/ ,或者自己找第三方接口
ip=returnCitySN["cip"];
$.ajax({
url: 'http://api.map.baidu.com/location/ip?ak=ia6HfFL660Bvh43exmH9LrI6',
type: 'POST',
dataType: 'jsonp',
success:function(data) {
//获取城市
cityAndAddress=data.content.address_detail.province + "," + data.content.address_detail.city;
//alert("IP:"+ip);
//alert("cityAndAddress:"+cityAndAddress);
$("#ip1").val(ip);
$("#cy1").val(cityAndAddress);
}
});
});
登陆时需要在界面上隐藏IP和位置信息进行提交到后台
<input type="hidden" name="ip" id="ip1">
<input type="hidden" name="city" id="cy1">
之后每次用户登录时都可以进行记录用户的日志信息了
第二种方式
1.在springboot项目中引入包
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<!-- <version>4.9.0</version>-->
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.6.3</version>
</dependency>
2.写个工具类调用https://api.xygeng.cn/openapi/ip/getInfo这个接口
private static JSONObject api2(){
HashMap<String, String> params = new HashMap<>();
params.put("ip","117.133.51.5");
try {
String s =doPost("https://api.xygeng.cn/openapi/ip/getInfo",params);
if (s != null && !s.isEmpty()){
JSONObject jsonObject = JSONObject.parseObject(s);
logger.info("获取信息:{}",jsonObject.toJSONString());
return jsonObject;
}
}catch (Exception e){
logger.info("获取信息异常:",e);
}
return new JSONObject();
}
public static String doPost(String url, Map<String, String> bodyParams) throws IOException {
FormBody.Builder formBuilder = new FormBody.Builder();
if (bodyParams != null && !bodyParams.isEmpty()) {
for (Map.Entry<String, String> entity : bodyParams.entrySet()) {
formBuilder.add(entity.getKey(), entity.getValue());
}
}
RequestBody body = formBuilder.build();
Request request = new Request.Builder().url(url).post(body).build();
try(Response response = client.newCall(request).execute()) {
if (response.isSuccessful()) {
return response.body().string();
}
logger.info("okhttp调用接口错误,响应码为:{}", response.code());
return "";
}
}
3.在接口处获取ip,之后作为参数传入上述接口中获取IP信息
//糊涂工具包下的获取请求ip的方式
String clientIP = ServletUtil.getClientIP(request);
4.返回结果,按照需要进行处理数据