A beginner-friendly tutorial application that demonstrates how to create a full-stack web application with:
- Frontend: Simple HTML/CSS/JavaScript
- Backend: Java with Spring Boot
- Database: PostgreSQL
This app allows you to add users through a web form and see them stored in a PostgreSQL database.
🚀 Visit Simple Java Tutorial App
- How to create a REST API with Java Spring Boot
- How to connect Java to a PostgreSQL database
- How to create a simple frontend that communicates with a backend
- How to handle form submissions and display data
- Basic CRUD operations (Create, Read, Delete)
Before running this application, make sure you have the following installed:
-
Java 11 or higher
- Download from: https://adoptium.net/
- Check if installed:
java -version
-
Maven 3.6 or higher
- Download from: https://maven.apache.org/download.cgi
- Check if installed:
mvn -version
-
PostgreSQL 12 or higher
- Download from: https://www.postgresql.org/download/
- Check if installed:
psql --version
-
Python 3 (for running the frontend)
- Usually pre-installed on Mac/Linux
- Windows: Download from https://python.org
- Check if installed:
python3 --version
On Windows:
# Start PostgreSQL service
net start postgresql-x64-14
On Mac (with Homebrew):
# Start PostgreSQL service
brew services start postgresql
On Linux (Ubuntu/Debian):
# Start PostgreSQL service
sudo systemctl start postgresql
sudo systemctl enable postgresql
Open your terminal and connect to PostgreSQL:
# Connect to PostgreSQL as superuser
sudo -u postgres psql
# Or on Windows/Mac:
psql -U postgres
Once connected to PostgreSQL, run these commands:
-- Create a new database for our tutorial
CREATE DATABASE tutorial_db;
-- Create a new user for our application
CREATE USER tutorial_user WITH PASSWORD 'tutorial_password';
-- Grant all privileges on the database to our user
GRANT ALL PRIVILEGES ON DATABASE tutorial_db TO tutorial_user;
-- Exit PostgreSQL
\q
Test that you can connect with the new user:
psql -h localhost -U tutorial_user -d tutorial_db
Enter the password tutorial_password
when prompted. If successful, you'll see the PostgreSQL prompt.
If you haven't already, make sure you have all the project files in a folder called java-tutorial-app
.
Open a terminal and navigate to the backend directory:
cd java-tutorial-app/backend
Install dependencies and start the backend server:
# Install dependencies and compile the project
mvn clean install
# Start the backend server
mvn spring-boot:run
You should see output like:
🚀 Backend server is running on http://localhost:8080
Keep this terminal open - the backend server needs to keep running.
Open a new terminal and navigate to the frontend directory:
cd java-tutorial-app/frontend/public
Start the frontend server:
# Start the frontend server
python3 -m http.server 3000
You should see output like:
Serving HTTP on 0.0.0.0 port 3000 (http://0.0.0.0:3000/) ...
Open your web browser and go to:
http://localhost:3000
You should see the Simple Tutorial App interface!
- Best for: Full-stack Java Spring Boot applications
- Pros: Native Java support, free PostgreSQL database, easy GitHub integration
- Cons: Cold starts on free tier
- Cost: Free tier available
- Best for: Full-stack applications with simple deployment
- Pros: Excellent developer experience, automatic deployments
- Cons: Limited free tier
- Cost: Usage-based pricing
- Best for: Traditional deployment with extensive add-ons
- Pros: Mature platform, lots of documentation
- Cons: No free tier anymore
- Cost: Paid plans only
- Why not: Vercel is designed for frontend applications and serverless functions only
- Limitation: Cannot run full Java Spring Boot applications
- Alternative: Use Vercel for frontend + separate backend hosting
- GitHub Account - Push your code to a GitHub repository
- Render.com Account - Sign up at https://render.com
- Push to GitHub:
cd java-tutorial-app
git init
git add .
git commit -m "Initial commit - Java tutorial app"
git branch -M main
git remote add origin https://github.com/yourusername/java-tutorial-app.git
git push -u origin main
- Update Frontend API URL:
Edit
frontend/public/script.js
and replacelocalhost:8080
with your future backend URL:
// Change this line:
const API_BASE_URL = 'http://localhost:8080/api/users';
// To this (you'll get the actual URL after backend deployment):
const API_BASE_URL = 'https://your-backend-name.onrender.com/api/users';
- Login to Render.com and click "New +"
- Select "PostgreSQL"
- Configure Database:
- Name:
tutorial-database
(or your preferred name) - Database:
tutorial_db
- User:
tutorial_user
- Region: Choose closest to your location
- Plan: Free (or paid for better performance)
- Name:
- Click "Create Database"
- Save Connection Details: Note the External Database URL provided
- Click "New +" → "Web Service"
- Connect GitHub Repository:
- Select your
java-tutorial-app
repository - Branch:
main
- Select your
- Configure Service:
- Name:
tutorial-backend
(or your preferred name) - Region: Same as your database
- Branch:
main
- Root Directory:
backend
- Runtime:
Java
- Build Command:
./mvnw clean install
- Start Command:
java -jar target/simple-tutorial-backend-1.0.0.jar
- Name:
- Environment Variables:
Click "Advanced" and add these environment variables:
SPRING_DATASOURCE_URL=<your-database-external-url> SPRING_DATASOURCE_USERNAME=<your-database-username> SPRING_DATASOURCE_PASSWORD=<your-database-password> SPRING_JPA_HIBERNATE_DDL_AUTO=update SPRING_JPA_DATABASE_PLATFORM=org.hibernate.dialect.PostgreSQLDialect
- Click "Create Web Service"
-
Update Frontend API URL: Replace the API URL in
frontend/public/script.js
with your backend URL:const API_BASE_URL = 'https://tutorial-backend.onrender.com/api/users';
-
Create Frontend Service:
- Click "New +" → "Static Site"
- Connect same GitHub repository
- Name:
tutorial-frontend
- Branch:
main
- Root Directory:
frontend/public
- Build Command: (leave empty)
- Publish Directory:
.
-
Click "Create Static Site"
- Access your frontend at the provided Render URL
- Test adding users through the web interface
- Verify data persistence by refreshing the page
Backend won't start:
- Check build logs for Maven errors
- Verify environment variables are set correctly
- Ensure database is running and accessible
- "mvn: command not found" error: Use
./mvnw clean install
instead ofmvn clean install
(Maven wrapper is included in this project)
Frontend can't connect to backend:
- Verify API URL in
script.js
matches your backend URL - Check CORS settings in Spring Boot (already configured in this project)
- Ensure backend is running and healthy
Database connection failed:
- Double-check database credentials
- Verify database is in the same region as your backend
- Check firewall/network settings
# Install Homebrew if you don't have it
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
# Install pgAdmin
brew install --cask pgadmin4
- Visit https://www.pgadmin.org/download/pgadmin-4-macos/
- Download the latest version
- Install the .dmg file
cd java-tutorial-app
docker-compose up -d postgres
-
Open pgAdmin (Applications → pgAdmin 4)
-
Create Server Connection:
- Right-click "Servers" in the left panel
- Select "Create" → "Server..."
-
General Tab:
- Name:
Tutorial Local Database
(or any descriptive name)
- Name:
-
Connection Tab:
- Host name/address:
localhost
- Port:
5432
- Maintenance database:
tutorial_db
- Username:
tutorial_user
- Password:
tutorial_password
- Save password: ✅ (optional, for convenience)
- Host name/address:
-
Click "Save"
Once connected, expand the tree:
Servers
└── Tutorial Local Database
└── Databases
└── tutorial_db
└── Schemas
└── public
└── Tables
└── users
To view all users:
- Right-click on "users" table
- Select "View/Edit Data" → "All Rows"
- Your user data will appear in a spreadsheet-like interface
To run custom queries:
- Right-click on "tutorial_db"
- Select "Query Tool"
- Write SQL queries like:
-- View all users
SELECT * FROM users;
-- Count total users
SELECT COUNT(*) FROM users;
-- Find users by email domain
SELECT * FROM users WHERE email LIKE '%@example.com';
- Login to Render.com
- Go to your PostgreSQL database
- Copy connection details:
- External Database URL
- Username
- Password
- Database name
-
Create new server connection in pgAdmin
-
General Tab:
- Name:
Tutorial Cloud Database
- Name:
-
Connection Tab:
- Host: Extract from your database URL (e.g.,
dpg-xxxxx-a.oregon-postgres.render.com
) - Port:
5432
- Database:
tutorial_db
- Username: From Render dashboard
- Password: From Render dashboard
- SSL Mode:
Require
- Host: Extract from your database URL (e.g.,
-
Click "Save"
-- Export users to CSV (run in Query Tool)
COPY users TO '/path/to/backup/users.csv' DELIMITER ',' CSV HEADER;
- Use pgAdmin's "Dashboard" tab to monitor connections and activity
- Check "Statistics" tab for table sizes and query performance
-- Add a new user manually
INSERT INTO users (name, email) VALUES ('Manual User', 'manual@example.com');
-- Update user information
UPDATE users SET name = 'Updated Name' WHERE id = 1;
-- Delete specific user
DELETE FROM users WHERE email = 'unwanted@example.com';
-- Reset auto-increment ID
ALTER SEQUENCE users_id_seq RESTART WITH 1;
"Connection refused":
- Verify PostgreSQL is running:
docker ps
- Check if port 5432 is available:
lsof -i :5432
- Try
127.0.0.1
instead oflocalhost
"Authentication failed":
- Double-check username and password
- Verify credentials in
docker-compose.yml
- Ensure database exists:
docker-compose logs postgres
"SSL connection required" (for cloud databases):
- Set SSL Mode to "Require" in connection settings
- For Render.com, SSL is mandatory for external connections
Slow queries:
- Add indexes for frequently searched columns
- Use EXPLAIN ANALYZE to understand query performance
- Consider connection pooling for high-traffic applications
Connection limits:
- Free tier databases have connection limits
- Close unused connections in pgAdmin
- Monitor active connections in Dashboard
-
Add a User:
- Fill in the "Name" and "Email" fields
- Click "Add User"
- You should see a success message
-
View Users:
- All users are automatically displayed below the form
- Each user shows their ID, name, and email
-
Delete a User:
- Click the "🗑️ Delete" button next to any user
- Confirm the deletion in the popup
-
Refresh the List:
- Click "🔄 Refresh List" to reload users from the database
Problem: Connection refused
or database errors
Solution:
- Make sure PostgreSQL is running:
sudo systemctl status postgresql
- Check database credentials in
backend/src/main/resources/application.properties
- Verify you can connect manually:
psql -h localhost -U tutorial_user -d tutorial_db
Problem: "Error connecting to server" messages
Solution:
- Make sure the backend is running on port 8080
- Check the browser console for CORS errors
- Verify the API URL in
frontend/public/script.js
is correct
Problem: Port 8080 is already in use
Solution:
- Kill the process using the port:
lsof -ti:8080 | xargs kill -9
- Or change the port in
application.properties
:server.port=8081
Problem: Maven can't download dependencies
Solution:
- Check your internet connection
- Clear Maven cache:
mvn clean
- Try:
mvn dependency:resolve
java-tutorial-app/
├── backend/ # Java Spring Boot backend
│ ├── src/main/java/com/tutorial/
│ │ ├── Application.java # Main application entry point
│ │ ├── User.java # User entity (database model)
│ │ ├── UserRepository.java # Database operations interface
│ │ └── UserController.java # REST API endpoints
│ ├── src/main/resources/
│ │ └── application.properties # Database and server configuration
│ └── pom.xml # Maven dependencies and build config
├── frontend/ # Simple HTML/CSS/JS frontend
│ ├── public/
│ │ ├── index.html # Main HTML page
│ │ ├── styles.css # CSS styling
│ │ └── script.js # JavaScript for API calls
│ └── package.json # Frontend project info
└── README.md # This file
- Application.java: Entry point that starts the Spring Boot server
- User.java: Entity class that maps to database table
- UserRepository.java: Interface for database operations (Spring Data JPA)
- UserController.java: REST API endpoints that handle HTTP requests
- application.properties: Configuration for database connection
- index.html: Structure of the web page
- styles.css: Styling and layout
- script.js: JavaScript that makes API calls to the backend
- Automatic table creation: Spring Boot creates the
users
table automatically - CRUD operations: Create, Read, Delete operations through the API
- Data persistence: Data is stored permanently in PostgreSQL
The backend provides these REST API endpoints:
GET /api/users
- Get all usersPOST /api/users
- Create a new userGET /api/users/{id}
- Get a specific user by IDDELETE /api/users/{id}
- Delete a user by ID
Once you understand the basics, try these modifications:
- Add more fields: Add age, phone number, or address to the User entity
- Add validation: Implement email format validation
- Add search: Create an endpoint to search users by name
- Improve UI: Add more styling or use a CSS framework
- Add editing: Implement user update functionality
After completing this tutorial, you might want to learn:
- Spring Security: Add authentication and authorization
- Frontend Frameworks: Try React, Vue, or Angular instead of vanilla JavaScript
- Testing: Write unit tests for your backend
- Deployment: Deploy your app to cloud platforms like Heroku or AWS
- Advanced Database: Learn about relationships, indexes, and migrations
If you run into issues:
- Check the console output for error messages
- Look at the browser's developer console (F12)
- Verify all services are running (PostgreSQL, backend, frontend)
- Check that all ports are available (5432 for PostgreSQL, 8080 for backend, 3000 for frontend)
This project is for educational purposes. Feel free to use and modify as needed for learning!
Happy Learning! 🎉