Category: React • Beginner
Published on 02 Apr 2026
Explanation
Create a simple HTML login form with username and password input fields and a submit button.
Code Example
<form id="loginForm" onSubmit="validate()"> <input type="text" id="username" placeholder="Enter username" /> <input type="password" id="password" placeholder="Enter password" /> <button type="submit">Login</button> </form> <p id="error"></p>
Explanation
Add JavaScript validation to check whether username and password fields are empty before making the API request.
Code Example
function validate(){
const username = document.getElementById("username").value;
const password = document.getElementById("password").value;
if(username === "" || password === "") {
document.getElementById("error").innerText = "All fields are required";
return;
}
loginUser(username, password);
}
Explanation
Use fetch API to send login credentials to the backend REST API.
Code Example
function loginUser(username, password) {
fetch("http://localhost:8080/api/login", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ username,
password })
})
.then(res => res.json())
.then(data => console.log(data));
}
Explanation
Create a Spring Boot REST controller to receive login request from frontend.
Code Example
@RestController
@RequestMapping("/api")
public class LoginController {
@PostMapping("/login")
public String login(
@RequestBody LoginRequest request) {
if(request.getUsername().equals("admin")
&& request.getPassword().equals("1234")) {
return "Login successful";
}
return "Invalid credentials";
}
}
Explanation
Create a LoginRequest model class to map username and password from request body.
Code Example
public class LoginRequest {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}