1. Prerequisites
Before starting, install these tools:
Required Software:
- Java JDK 17 or higher – Download from Oracle or Adoptium
- Eclipse IDE or IntelliJ IDEA or VS Code – For writing code
- MySQL Server – Download from MySQL Website
- MySQL Workbench (Optional but helpful) – GUI for MySQL
Verify Installation:
Open Command Prompt/Terminal and type:
java -version
You should see something like: java version "17.0.x"
2. What is Spring Boot?
Spring Boot is a framework that makes it easy to create Java applications, especially web applications.
Key Concepts:
- Framework: Pre-written code that handles common tasks (like connecting to databases, handling web requests)
- Spring Boot: Makes Spring framework easier to use – less configuration needed
- Web Application: A program that runs on a server and responds to browser requests
Think of it like:
- Java = Building blocks (bricks)
- Spring = Construction toolkit (hammer, nails, blueprint)
- Spring Boot = Pre-assembled walls (faster building)
3. Project Setup
Step 3.1: Create New Spring Boot Project
Option A: Using Spring Initializr (Recommended for beginners)
- Go to https://start.spring.io/
- Configure:
- Project: Maven
- Language: Java
- Spring Boot: 3.2.0 (or latest stable)
- Group: com.csc
- Artifact: login-app
- Name: LoginApp
- Package name: com.csc.login
- Packaging: Jar
- Java: 17
- Add Dependencies (click “ADD DEPENDENCIES” button):
- Spring Web
- Spring Data JPA
- MySQL Driver
- Click GENERATE button
- Extract the downloaded ZIP file
- Open the folder in your IDE
Option B: Using Eclipse/IntelliJ
- Eclipse: File → New → Spring Starter Project
- IntelliJ: File → New → Project → Spring Initializr
Use the same settings as above.
4. Understanding Project Structure
After creating the project, you’ll see this structure:
login-app/
├── src/
│ ├── main/
│ │ ├── java/
│ │ │ └── com/csc/login/
│ │ │ └── LoginAppApplication.java ← Main file
│ │ └── resources/
│ │ ├── static/ ← HTML, CSS files here
│ │ └── application.properties ← Configuration
│ └── test/ ← Test files
├── pom.xml ← Dependencies list
└── target/ ← Compiled files
What each folder means:
- src/main/java: Your Java code goes here
- src/main/resources/static: HTML, CSS files
- application.properties: Database connection settings
- pom.xml: Lists all libraries (dependencies) your project needs
5. Building Step by Step
Step 5.1: Configure Database Connection
Open src/main/resources/application.properties and add:
# Database Connection
spring.datasource.url=jdbc:mysql://localhost:3306/logindb
spring.datasource.username=root
spring.datasource.password=yourpassword
# JPA Settings
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect
Line by line explanation:
spring.datasource.url: Where is your database? (localhost = your computer, 3306 = MySQL port, logindb = database name)spring.datasource.username: MySQL username (usually ‘root’)spring.datasource.password: Your MySQL passwordspring.jpa.hibernate.ddl-auto=update: Automatically create/update database tablesspring.jpa.show-sql=true: Show SQL queries in console (helpful for learning)
Step 5.2: Create the User Model (Entity)
What is a Model/Entity?
A model represents data. In this case, a User with username and password.
Create file: src/main/java/com/csc/login/model/User.java
package com.csc.login.model;
import jakarta.persistence.*;
@Entity // ← Tells Spring this is a database table
@Table(name = "users") // ← Table name in database
public class User {
@Id // ← Primary key (unique identifier)
@GeneratedValue(strategy = GenerationType.IDENTITY) // ← Auto-increment
private int id;
private String username; // ← Will become a column in table
private String password; // ← Will become a column in table
// Getters and Setters (needed to access private variables)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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;
}
}
Annotations explained:
@Entity: Marks this class as a database table@Table(name = "users"): The table will be called “users”@Id: This field is the primary key@GeneratedValue: Database will automatically generate ID numbers (1, 2, 3…)
Why Getters/Setters?
Private variables can’t be accessed directly. Getters/Setters provide controlled access.
Step 5.3: Create the Repository
What is a Repository?
A repository handles database operations (save, find, delete). Spring Data JPA provides these automatically!
Create file: src/main/java/com/csc/login/repository/UserRepository.java
package com.csc.login.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.csc.login.model.User;
public interface UserRepository extends JpaRepository<User, Integer> {
// Custom method to find user by username AND password
User findByUsernameAndPassword(String username, String password);
}
Line by line:
extends JpaRepository<User, Integer>:User= Entity typeInteger= ID type- Gives you free methods: save(), findById(), deleteById(), etc.
findByUsernameAndPassword: Spring automatically creates SQL query from method name!- Spring reads: “find” + “By” + “Username” + “And” + “Password”
- Creates:
SELECT * FROM users WHERE username = ? AND password = ?
Magic of Spring Data JPA:
You just write the method name, Spring creates the actual query!
Step 5.4: Create the Service
What is a Service?
Service layer contains business logic. It sits between Controller and Repository.
Create file: src/main/java/com/csc/login/service/UserService.java
package com.csc.login.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.csc.login.model.User;
import com.csc.login.repository.UserRepository;
@Service // ← Marks this as a service component
public class UserService {
@Autowired // ← Automatic dependency injection
private UserRepository repo;
public User validateUser(String username, String password) {
return repo.findByUsernameAndPassword(username, password);
}
}
Explained:
@Service: Tells Spring this is a service class@Autowired: Spring automatically creates and injects UserRepository object- Dependency Injection: Spring creates objects for you, no need for
new UserRepository() validateUser(): Calls repository to check if user exists with given credentials
Why use Service layer?
- Keeps Controller simple
- Business logic in one place
- Easy to add features later (like password encryption)
Step 5.5: Create the Controller
What is a Controller?
Controller handles web requests (when user submits form, clicks button, etc.)
Create file: src/main/java/com/csc/login/controller/LoginController.java
package com.csc.login.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.csc.login.model.User;
import com.csc.login.service.UserService;
@Controller // ← Marks this as a web controller
public class LoginController {
@Autowired // ← Inject UserService
private UserService service;
@PostMapping("/login") // ← Handles POST request to /login
public String login(@RequestParam String username,
@RequestParam String password) {
User user = service.validateUser(username, password);
if (user != null) {
return "redirect:/welcome.html"; // ← Login success
} else {
return "redirect:/login.html"; // ← Login failed
}
}
}
Line by line:
@Controller: This class handles web requests@PostMapping("/login"): When form is submitted to/login, this method runs@RequestParam: Extracts form data@RequestParam String usernamegets the “username” field from formservice.validateUser(): Check if user exists in databasereturn "redirect:/welcome.html": Send user to welcome pageredirect:means “go to this page”
Flow:
- User fills form and clicks “Login”
- Browser sends POST request to
/login - Spring calls this method
- Method checks database
- Redirects based on result
Step 5.6: Create Test Controller (Optional but helpful)
Create file: src/main/java/com/csc/login/controller/TestController.java
package com.csc.login.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController // ← Returns data directly (not a page)
public class TestController {
@GetMapping("/") // ← Handles GET request to /
public String test() {
return "Spring Boot is running successfully!";
}
}
Purpose:
- Quick test to check if Spring Boot is running
- Visit
http://localhost:8080/to see the message
Step 5.7: Create HTML Pages
Create folder structure:
In src/main/resources/static/ create these files:
File 1: login.html
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h2>Login Page</h2>
<form action="/login" method="post">
<input type="text" name="username" placeholder="Username" required><br><br>
<input type="password" name="password" placeholder="Password" required><br><br>
<button type="submit">Login</button>
</form>
</body>
</html>
Explained:
action="/login": Form submits to /login endpointmethod="post": Uses POST request (secure for passwords)name="username": Must match@RequestParam String usernamein controllerrequired: HTML validation – field can’t be empty
File 2: welcome.html
<!DOCTYPE html>
<html>
<head>
<title>Welcome</title>
</head>
<body>
<h1>Welcome to CSC Pallavaram</h1>
<p>Login Successful</p>
</body>
</html>
File 3: style.css
body {
text-align: center;
margin-top: 100px;
font-family: Arial;
}
input {
padding: 8px;
width: 200px;
}
button {
padding: 8px 20px;
}
Step 5.8: Main Application Class
This file is auto-generated. Just verify it exists:
src/main/java/com/csc/login/LoginAppApplication.java
package com.csc.login;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication // ← Enables Spring Boot features
public class LoginAppApplication {
public static void main(String[] args) {
SpringApplication.run(LoginAppApplication.class, args);
}
}
This is the starting point:
@SpringBootApplication: Enables auto-configurationmain(): Entry point of the programSpringApplication.run(): Starts the embedded web server
6. Database Setup
Step 6.1: Create Database in MySQL
Open MySQL Workbench or Command Line and run:
CREATE DATABASE logindb;
USE logindb;
That’s it! Spring will automatically create the users table because of:
spring.jpa.hibernate.ddl-auto=update
Step 6.2: Insert Test Data
Add a test user:
INSERT INTO users (username, password) VALUES ('admin', 'admin123');
Note: In real applications, NEVER store passwords in plain text! Use encryption (we’re keeping it simple for learning).
7. Running the Application
Step 7.1: Run from IDE
Eclipse:
- Right-click on
LoginAppApplication.java - Run As → Java Application
IntelliJ:
- Click the green play button next to
main()method
VS Code:
- Open
LoginAppApplication.java - Click “Run” above the
main()method
Step 7.2: Check Console
You should see:
Tomcat started on port(s): 8080
Started LoginAppApplication in X.XXX seconds
Common port issue:
If port 8080 is busy, add to application.properties:
server.port=8081
8. Testing
Test 1: Check if Spring Boot is running
- Open browser:
http://localhost:8080/ - You should see: “Spring Boot is running successfully!”
Test 2: Open Login Page
- Go to:
http://localhost:8080/login.html - You should see the login form
Test 3: Try Login
- Username:
admin - Password:
admin123 - Click Login
- Should redirect to welcome page
Test 4: Try Wrong Password
- Enter wrong credentials
- Should redirect back to login page
9. Common Errors & Solutions
Error 1: “Unable to connect to database”
Solution:
- Check if MySQL is running
- Verify username/password in
application.properties - Ensure database
logindbexists
Error 2: “Port 8080 already in use”
Solution:
Add to application.properties:
server.port=8081
Error 3: “Table ‘logindb.users’ doesn’t exist”
Solution:
- Check
spring.jpa.hibernate.ddl-auto=updatein properties - Restart application
- Or manually create table:
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(255),
password VARCHAR(255)
);
Error 4: “404 Not Found” for HTML pages
Solution:
- Ensure HTML files are in
src/main/resources/static/ - File names are case-sensitive
- Restart application
Error 5: Blank page on welcome.html
Solution:
- Check browser console for errors (F12)
- Verify file is in
staticfolder - Try accessing directly:
http://localhost:8080/welcome.html
🎯 Understanding the Complete Flow
What happens when user logs in:
- User enters credentials in
login.html - Browser sends POST request to
http://localhost:8080/login - Spring routes request to
LoginController.login()method - Controller extracts username and password from form
- Controller calls
UserService.validateUser() - Service calls
UserRepository.findByUsernameAndPassword() - Repository queries MySQL database
- Database returns User object (or null if not found)
- Result flows back through Service → Controller
- Controller decides where to redirect
- Browser displays welcome.html or login.html
📚 Key Concepts Summary
1. MVC Pattern (Model-View-Controller)
- Model (User.java): Data structure
- View (HTML files): What user sees
- Controller (LoginController.java): Handles requests
2. Layered Architecture
Controller → Service → Repository → Database
Each layer has a specific job.
3. Dependency Injection
Spring creates objects automatically with @Autowired. No need for new.
4. Annotations
@Entity: Database table@Controller: Handles web requests@Service: Business logic@Autowired: Inject dependencies@PostMapping: Handle POST requests
5. Spring Data JPA
Write method names, Spring creates SQL queries automatically!
🚀 Next Steps (After mastering this)
- Add password encryption (BCrypt)
- Add registration page (sign up)
- Add session management (remember logged-in user)
- Add error messages (show “Invalid credentials”)
- Add validation (email format, password strength)
- Use Thymeleaf (dynamic HTML templates)
- Add Spring Security (proper authentication)
📖 Additional Resources
❓ Need Help?
If you get stuck:
- Check console for error messages
- Verify database connection
- Make sure all files are in correct folders
- Restart the application
- Check if all dependencies are in
pom.xml
Happy Learning! 🎉