如何用Java API监控登录登出时间并存储至MySQL及问题排查
Let's break down the problems in your code and walk through the fixes step by step:
1. Critical Issues in the Client (Test.java)
Your client code has several blocking problems that prevent it from sending a valid request to the backend:
a. Invalid Return Statement
The line return new java.sql.Timestamp(today.getTime()); in your main method is invalid—main is a void method and can't return a value. This causes a compilation error, meaning your code never even runs past this point.
b. Unreachable Code
The username retrieval logic (String username = System.getProperty("user.name");) comes after the invalid return statement, so it's never executed.
c. Incorrect URL Construction
You're using literal placeholders ({userName}/{systemLoginTime}) in your URL instead of replacing them with actual values. This results in an invalid endpoint that the backend can't process.
d. Mismatched Request Format
Your client sends a JSON body, but your backend expects path variables for the POST request. These two approaches don't align.
Corrected Client Code
import java.io.*; import java.net.*; import java.sql.Timestamp; import java.util.Date; public class Test { public static void main(String[] args) throws IOException { // Get current OS username and formatted login timestamp String userName = System.getProperty("user.name"); Timestamp systemLoginTime = new Timestamp(new Date().getTime()); String formattedTime = systemLoginTime.toString(); // MySQL-friendly format: yyyy-MM-dd HH:mm:ss // Build valid URL with encoded values (handles special characters) String urlString = String.format("http://localhost:8080/insert/%s/%s", URLEncoder.encode(userName, "UTF-8"), URLEncoder.encode(formattedTime, "UTF-8")); URL url = new URL(urlString); try { System.out.println("Username: " + userName); System.out.println("Login Time: " + formattedTime); System.out.println("Request URL: " + url.toString()); // Open connection and configure for POST URLConnection urlc = url.openConnection(); urlc.setDoOutput(true); urlc.setAllowUserInteraction(false); // No body needed (using path variables) - just close the output stream PrintStream ps = new PrintStream(urlc.getOutputStream()); ps.close(); // Read backend response BufferedReader br = new BufferedReader(new InputStreamReader(urlc.getInputStream())); String line; while ((line = br.readLine()) != null) { System.out.println("Backend Response: " + line); } br.close(); } catch (Exception e) { System.out.println("Error occurred:"); e.printStackTrace(); // Print full error details for debugging } } }
2. Backend Verification Steps
Even if your client works, ensure your Spring Boot setup is correct:
a. Database Configuration
Check your application.properties (or application.yml) has valid MySQL credentials:
spring.datasource.url=jdbc:mysql://localhost:3306/your_database_name?useSSL=false&serverTimezone=UTC spring.datasource.username=your_db_username spring.datasource.password=your_db_password spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
b. Database Table Schema
Confirm your mycopinsert table exists with the right columns. Create it if needed:
CREATE TABLE mycopinsert ( id INT AUTO_INCREMENT PRIMARY KEY, userName VARCHAR(50) NOT NULL, systemLoginTime DATETIME NOT NULL, systemLogoffTime DATETIME NULL );
c. Enable Debug Logging
Add this to application.properties to see the exact SQL queries being executed:
logging.level.org.springframework.jdbc.core=DEBUG
This will help you verify if values are being passed correctly to the database.
3. Optional: Improve Backend with Request Body (Best Practice)
Using path variables for POST requests isn't ideal. A more RESTful approach is to send data in the request body:
Updated Controller
package com.example.demo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; @RestController public class MyCopController { @Autowired MyCopRepo ar; @PostMapping("/insert") public String myCop(@RequestBody LoginRequest loginRequest) { return ar.add(loginRequest.getUserName(), loginRequest.getSystemLoginTime()); } // DTO to hold request data static class LoginRequest { private String userName; private String systemLoginTime; // Getters and setters public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getSystemLoginTime() { return systemLoginTime; } public void setSystemLoginTime(String systemLoginTime) { this.systemLoginTime = systemLoginTime; } } }
Updated Client for JSON Body
Modify your client to send a JSON payload instead of using path variables (adjust the Test.java code accordingly).
Key Fixes Recap
- Removed the invalid return statement causing compilation errors
- Properly retrieved username and formatted timestamp
- Built a valid URL with encoded values
- Aligned client request format with backend expectations
- Added detailed error logging for easier debugging
内容的提问来源于stack exchange,提问作者S.B.S.Ganesh

