如何使用java API监控登录时间和注销时间并存储到mysql数据库中



每当用户登录系统时,我都会尝试该特定用户名和当前时间并将其存储到MySQL数据库中。我的数据库表名称是用户名,系统登录时间,系统注销时间。我已经尝试了很多次,但是当用户登录系统时,它在数据库中不起作用

This is my code java API:
import java.io.*;
import java.net.*;
public class Test
{
public static void main(String[] args) throws IOException {
String userName = "";
String systemLoginTime = "";
URL url = new URL("http://localhost:8080/insert/{userName}/{systemLoginTime}");
//Insert your JSON query request
String query = "{'userName':USERNAME,'systemLoginTime':'TODAY'}";
//It change the apostrophe char to double colon char, to form a correct JSON string
query=query.replace("'", """);
try{
System.getenv().get("USERNAME");
java.util.Date today = new java.util.Date();
return new java.sql.Timestamp(today.getTime());
//com.sun.security.auth.module.NTSystem().getName;
String username = System.getProperty("user.name");
System.out.println("username = " + username);
//make connections
URLConnection urlc = url.openConnection();
//It Content Type is so importan to support JSON call
urlc.setRequestProperty("Content-Type", "application/json");
printMessage("Your URL: " + url.toString());
//use post mode
urlc.setDoOutput(true);
urlc.setAllowUserInteraction(false);
//send query
PrintStream ps = new PrintStream(urlc.getOutputStream());
ps.print(query);
printMessage("Your Query: " + query);
ps.close();
//get result
BufferedReader br = new BufferedReader(new InputStreamReader(urlc.getInputStream()));
String l = null;
while ((l=br.readLine())!=null) {
printMessage(l);
}
br.close();
} catch (Exception e){
printMessage("Error ocurred");
printMessage(e.toString());
}
}
private static void printMessage(String s){
System.out.println(s);
}
}

====

===================================
This is my Spring Boot Repository class
package com.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
@Repository
public class MyCopRepo
{
@Autowired
JdbcTemplate jdbt;
public String add(String userName, String systemLoginTime)
{
String userName1= userName;
String systemLoginTime1=systemLoginTime; 
//String systemLogoffTime1= systemLogoffTime;
String query = "insert into mycopinsert(userName, systemLoginTime) values(?,?)";
int i = jdbt.update(query, userName1, systemLoginTime1);
if(i>0)
{
return "Inserted Successfully";
}
return "Not Inserted";
}
}

====

================================================
This is my Controller class:
package com.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyCopController
{
@Autowired
MyCopRepo ar;
@PostMapping("/insert/{userName}/{systemLoginTime}")
public String myCop(@PathVariable("userName") String userName, @PathVariable("systemLoginTime") String systemLoginTime)
{
return ar.add(userName, systemLoginTime);
}
}

您可以尝试这样的事情,而不是作为参数传递,只是在对数据库进行查询之前获取登录时间。

public String add(String userName)
{
String userName1= userName;
String systemLoginTime=java.sql.Timestamp(new Date().getTime());
//String systemLogoffTime1= systemLogoffTime;
String query = "insert into mycopinsert(userName, systemLoginTime) values(?,?)";
int i = jdbt.update(query, userName1, systemLoginTime1);
if(i>0)
{
return "Inserted Successfully";
}
return "Not Inserted";
}
}

你还应该将代码封装在main中,创建方法对内容进行分组(而不是在每个部分之前添加注释(,这样更容易理解和易于调试。

将项目配置为使用 Hibernate & Springboot,您的解决方案将变为:

@postmapping("/login")
public String login(@RequestBody LoginEventRequestBody request) {
LoginEvent event = new LoginEvent();
event.setUsername(request.getUserName);
event.setTimeStamp(new Timestamp(new Date().getTime()));
loginEventService.save(event);
return "successfully logged login event";
}

实质上,您需要将登录逻辑与日志记录逻辑分开。用户成功登录后,记录登录事件。 您仍然可以使用路径变量。我个人只是觉得这个更干净

如何设置此
登录事件请求正文
登录事件登录事件控制器 登录事件服务登录
事件
存储库

应用程序。属性

LoginEventRequestBody.java

package org.app.loginEvent;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import org.immutables.value.Value;
@Value.Immutable
@JsonDeserialize(builder = LoginEventRequestBody.Builder.class)
@Value.Style(
visibility = Value.Style.ImplementationVisibility.PACKAGE,
builderVisibility = Value.Style.BuilderVisibility.PUBLIC
)
public interface LoginEventRequestBody {
String getUserName();
class Builder extends ImmutableLoginEventRequestBody.Builder {
}
static LoginEventRequestBody.Builder builder() {
return new LoginEventRequestBody.Builder();
}
}

登录事件.java

package org.app.loginEvent;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.sql.Timestamp;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "login_event")
public class LoginEvent {
@Id
@GeneratedValue
@JsonProperty("id")
private Long id;
@JsonProperty("userName")
private String userName;
@JsonProperty("timestamp")
private Timestamp timestamp;  
public LoginEvent() {
}
public LoginEvent(String userName, Timestamp timestamp) {
this.userName = userName;
this.timestamp = timestamp;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Timestamp getTimestamp() {
return timestamp;
}
public void setTimestamp(Timestamp timestamp) {
this.timestamp = timestamp;
}
}

登录事件控制器

package org.app.loginEvent;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("events")
public class LoginEventController {
private final LoginEventService loginEventService;
public LoginEventController(LoginEventService loginEventService) {
this.loginEventService = loginEventService;
}
@postmapping("/login")
public String login(@RequestBody LoginRequestBody request) {
LoginEvent event = new LoginEvent();
event.setUsername(request.getUserName);
event.setTimeStamp(new Timestamp(new Date().getTime()));
loginEventService.save(event);
return "successfully logged login event";
}
}

登录事件服务

package org.app.loginEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional
public class LoginEventService {
@Autowired
private LoginEventRepository loginEventRepository;
public void save(LoginEventloginEvent) {
loginEventRepository.save(loginEvent);
}
}

登录事件存储库

package org.app.loginEvent;
import org.springframework.data.jpa.repository.JpaRepository;
public interface LoginEventRepository extends JpaRepository<LoginEvent, Long> {
}

应用程序属性

#--------------------------------------------------
#mysql
#--------------------------------------------------
spring.datasource.username              =root
spring.datasource.password              =root
spring.datasource.url                   =jdbc:mysql://localhost:3306/mydb
spring.datasource.driverClassName       =com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto           =update

当用户登录时, 向事件跟踪器发出请求

HTTP 方法

POST

网址端点

http://localhost:8080/events/login

请求正文

{
userName:"userNameOfThePersonTryingToLogIn"
}

#now check your database and you will find the event has logged
#repeat this process for your logout event

相关内容

  • 没有找到相关文章

最新更新