Complete Beginner's Guide: How to Run Every Program (Start from a Fresh Computer)
Read this section fully before touching any of the 78 programs below. It explains everything
from switching on the computer to seeing your first program's output, in plain step-by-step form.
Every program later in this document only needs the specific steps under
"How to Run" (if any) in addition to everything set up here — you do NOT need to repeat this
setup for every program, only once on your computer.
STEP 1 — Start the computer
- Switch on the computer and log in to Windows (or Linux/macOS).
- Make sure you are connected to the Internet (needed to download software in the next steps).
- Create one folder to keep everything organized, e.g.
C:\J2EE-Practicals (Windows) or
~/J2EE-Practicals (Linux/macOS). You will copy jar files, .sql scripts, etc. here.
STEP 2 — Check if Java (JDK) is already installed
- Windows: click Start, type
cmd, press Enter to open Command Prompt.
macOS/Linux: open the Terminal application.
- Type
java -version and press Enter.
- If you see a version number (e.g. "java version 17..."), Java is already installed — skip to Step 4.
If you see "not recognized" or "command not found", continue to Step 3.
STEP 3 — Download and install JDK
- Open your web browser (Chrome/Edge/Firefox).
- Go to
https://www.oracle.com/java/technologies/downloads/ (or https://adoptium.net for the free OpenJDK build).
- Choose JDK 17 (or 11) for your operating system (Windows x64 / macOS / Linux) and click Download.
- Once downloaded, double-click the installer file (e.g.
jdk-17_windows-x64_bin.exe).
- Click Next → Next → Install, keeping all default options, then click Close/Finish when done.
- Note the installation folder shown during setup, typically
C:\Program Files\Java\jdk-17.
STEP 4 — Set JAVA_HOME and PATH (Windows)
- Right-click "This PC" (on Desktop or File Explorer) → Properties.
- Click "Advanced system settings" on the left.
- In the System Properties window, click the "Environment Variables..." button.
- Under "System variables", click "New...". Set Variable name =
JAVA_HOME, Variable value = your JDK folder path (e.g. C:\Program Files\Java\jdk-17). Click OK.
- In the same "System variables" list, select the variable named
Path, click "Edit...", click "New", and add %JAVA_HOME%\bin. Click OK on every open window.
- Close and reopen Command Prompt, then type
java -version and javac -version to confirm both commands now work.
- (Linux/macOS: add
export JAVA_HOME=/path/to/jdk and export PATH=$JAVA_HOME/bin:$PATH to your ~/.bashrc or ~/.zshrc, then run source ~/.bashrc.)
STEP 5 — Download and install Eclipse IDE
- Go to
https://www.eclipse.org/downloads/ in your browser.
- Click "Download x86_64" (Windows) or the correct button for your OS — this downloads the Eclipse Installer.
- Run the downloaded installer file.
- In the installer, click on "Eclipse IDE for Enterprise Java and Web Developers" (this bundle already includes web/Servlet/JSP tools).
- Choose an installation folder when asked, then click Install.
- Accept any license agreements that appear, then wait for installation to finish.
- Click Launch to open Eclipse. Choose (or accept the default) workspace folder when prompted, then click Launch again.
STEP 6 — Download and install Apache Tomcat (needed for Servlet/JSP/MVC programs)
- Go to
https://tomcat.apache.org/ in your browser.
- Click "Tomcat 9" (or 10) in the left menu under "Download".
- Under "Core", download the "zip" (Windows) or "tar.gz" (Linux/macOS) archive for the 32-bit/64-bit distribution.
- Extract the downloaded archive into a simple path with no spaces, e.g.
C:\tomcat9 or /opt/tomcat9.
- (Optional quick test) Open the
bin folder inside it and double-click startup.bat (Windows) or run ./startup.sh in a terminal (Linux/macOS). Open a browser and go to http://localhost:8080/ — you should see the Tomcat welcome page. Then stop it again with shutdown.bat / ./shutdown.sh before continuing (Eclipse will start/stop it for you from now on).
STEP 7 — Register Tomcat inside Eclipse
- In Eclipse, click the "Window" menu → Preferences.
- In the left tree, expand "Server" and click "Runtime Environments".
- Click the "Add..." button on the right.
- Select "Apache Tomcat v9.0" (or the version you downloaded) from the list, click Next.
- Click "Browse..." and select the Tomcat folder from Step 6 (e.g.
C:\tomcat9).
- Click Finish, then click Apply and Close.
STEP 8 — Download and install MySQL Server (needed for JDBC/MVC/Hibernate/Spring-Data programs)
- Go to
https://dev.mysql.com/downloads/installer/ in your browser (or simply install XAMPP from https://www.apachefriends.org/, which bundles MySQL/MariaDB and is easier for beginners).
- Download the MySQL Installer for Windows (or the correct package for your OS).
- Run the installer, choose the "Developer Default" (or "Server only") setup type, and click Next through the screens, allowing it to download and install components.
- When asked, set a root password you will remember (this guide assumes user
root and password root — use whatever you set, and update it in every program's connection string).
- Finish the installer. It also installs "MySQL Workbench", a graphical tool to manage databases.
- Open MySQL Workbench from the Start Menu, connect using root and your password, then open a new SQL tab and run:
CREATE DATABASE college; followed by Ctrl+Enter (or the lightning-bolt "Execute" button) to run it.
- For each program that needs a table (DDL SQL is provided per program below), paste that CREATE TABLE statement into the same SQL tab and execute it once before running the program.
STEP 9 — Download the MySQL JDBC driver jar
- Go to
https://dev.mysql.com/downloads/connector/j/ in your browser.
- Select "Platform Independent" from the Operating System dropdown, then download the ZIP/TAR archive (no login required — look for "No thanks, just start my download" link).
- Extract the archive; inside you will find a file like
mysql-connector-j-8.4.0.jar. Copy this jar into your C:\J2EE-Practicals folder from Step 1 for easy reuse.
STEP 10 — Running a plain JDBC console program (Programs 1–20)
- Open Eclipse. Click File → New → Java Project. Type a project name (e.g.
JDBC-Practicals) and click Finish.
- Right-click the project → New → Class. Give it the exact class name shown in the program (e.g.
InsertEmp) and click Finish. Delete the auto-generated content and paste in the full code given for that program.
- Right-click the project → Build Path → Configure Build Path → Libraries tab → "Add External JARs..." → select the
mysql-connector-j-8.x.x.jar from Step 9 → Apply and Close.
- Make sure the database and table for that program already exist in MySQL Workbench (Step 8, using the DDL given with the program).
- Right-click the .java file in Eclipse → Run As → Java Application.
- View the output in Eclipse's "Console" tab at the bottom (if the program asks for input via
Scanner, click inside the Console tab and type your value, then press Enter).
STEP 11 — Running a Servlet / JSP / MVC program (Programs 21–72)
- In Eclipse: File → New → Dynamic Web Project.
- Type a project name (e.g.
J2EE-Web). In "Target Runtime" choose the Tomcat you registered in Step 7. Click Next twice, then tick "Generate web.xml deployment descriptor", then click Finish.
- In the Project Explorer, expand the project →
src folder: right-click → New → Class (or Package then Class) and paste in each .java file (Servlet, DAO, Bean) given for that program, keeping the same class name as the file name.
- Expand
WebContent (or src/main/webapp): right-click → New → HTML File / JSP File for each .html / .jsp file given for that program, and paste in its content.
- If the program uses a database, add
mysql-connector-j-8.x.x.jar: right-click project → Properties → Java Build Path → Libraries → Add External JARs, OR simply copy the jar file directly into WebContent/WEB-INF/lib using your file explorer/Eclipse drag-and-drop.
- If the program uses JSTL (
<c:...> tags), also download jakarta.servlet.jsp.jstl-api and jakarta.servlet.jsp.jstl jars (or the older jstl-1.2.jar for javax) and place them in WEB-INF/lib the same way.
- If the program needs a stored procedure (.sql file with CREATE PROCEDURE), run that script once in MySQL Workbench before testing.
- Right-click the project → Run As → Run on Server. Choose the Tomcat server, click Finish. Eclipse starts Tomcat and opens a built-in browser tab automatically.
- In the address bar, browse to the starting file for that program, e.g.
http://localhost:8080/J2EE-Web/hello (for a servlet mapped to /hello) or http://localhost:8080/J2EE-Web/index.html (for a form) — use the file/URL-pattern named in that program's code.
- Interact with the form/page in the browser to see the final output.
STEP 12 — Running a Hibernate program (Programs 73–75)
- Create a plain Java Project as in Step 10 (Hibernate programs run with a simple
main() method, no Tomcat needed).
- Download the Hibernate ORM core library: go to
https://sourceforge.net/projects/hibernate/files/hibernate-orm/ (or use a Maven project instead — see note below), download the latest 5.x zip, extract it, and add every jar inside its lib/required folder to your project's Build Path (Step 10's "Add External JARs" method), along with the MySQL connector jar.
- Easier alternative: instead of manual jars, create a Maven Project in Eclipse (File → New → Maven Project) and add
hibernate-core and mysql-connector-j as dependencies in pom.xml; Maven downloads everything automatically.
- Add the
hibernate.cfg.xml file (given with the program) directly under the src folder.
- Add the entity class (e.g.
Student.java) and the class with main() (e.g. HibernateStudentApp.java).
- Right-click the class with
main() → Run As → Java Application, and check the Console tab for output.
STEP 13 — Running a Spring Boot program (Programs 76–78)
- Open your browser and go to
https://start.spring.io.
- Choose Project = Maven, Language = Java, Spring Boot = the default stable version.
- Under Dependencies, click "Add Dependencies" and add: "Spring Web", "Spring Data JPA", "MySQL Driver", and (only for Program 76) "Thymeleaf".
- Click "Generate" at the bottom — this downloads a
.zip file. Extract it to your practicals folder.
- In Eclipse: File → Import → Maven → Existing Maven Projects → Browse to the extracted folder → Finish. Wait for Eclipse to download dependencies (progress shows bottom-right).
- Open
src/main/resources/application.properties and paste in the datasource lines given with the program (URL, username, password).
- Add the given
.java classes (Entity, Repository, Controller) under src/main/java in the same package as the auto-generated *Application.java file. For Program 76, also add the .html template files under src/main/resources/templates.
- Make sure the target MySQL database exists (Step 8) — Spring Data JPA will auto-create the tables.
- Right-click the main
*Application.java file (the one with @SpringBootApplication) → Run As → Spring Boot App (or Java Application).
- Wait for the Console to show "Started ...Application" with no errors, meaning the embedded server is running on port 8080.
- Open a browser to the URL shown in the program (e.g.
http://localhost:8080/login) for web pages, or use Postman/curl for REST endpoints (e.g. curl http://localhost:8080/employees).
Quick reference: which Step applies to which programs
- Programs 1–20 (JDBC): Steps 1–4, 8, 9, 10.
- Programs 21–72 (Servlet / JSP / MVC): Steps 1–9, 11 (add 8–9 only where a program uses a database).
- Programs 73–75 (Hibernate): Steps 1–4, 8, 12.
- Programs 76–78 (Spring Boot): Steps 1–4, 8, 13.
Program 1: Insert a record into the emp table JDBC
Definition
Insert a new employee row into the emp table using JDBC Statement.
Full Program Code
InsertEmp.java
import java.sql.*;
public class InsertEmp {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/college";
String user = "root", pass = "root";
try (Connection con = DriverManager.getConnection(url, user, pass);
Statement st = con.createStatement()) {
String sql = "INSERT INTO emp VALUES(101,'Ramesh Patel','Manager','Rajkot',55000,'Sales')";
int rows = st.executeUpdate(sql);
System.out.println(rows + " record(s) inserted successfully.");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Expected Output
1 record(s) inserted successfully.
Explanation
A JDBC Connection is opened with DriverManager.getConnection(), a Statement object is created, and executeUpdate() runs the INSERT SQL, returning the number of affected rows.
In simple words: this program is a plain Java class (no web browser involved) that talks to MySQL using the JDBC API. The three building blocks you will see in almost every JDBC program are: (1) DriverManager.getConnection() to open a line to the database, (2) a Statement/PreparedStatement/CallableStatement to send SQL, and (3) a ResultSet to read back rows when the SQL is a SELECT. Always close these objects when done (the try (...) {} syntax used here does that automatically) so the database connection is released properly.
How to Run (extra steps beyond general setup)
Run once as a plain Java class (console program). Make sure the emp table exists first (DDL above) and mysql-connector jar is on classpath.
Program 2: Display all employee records JDBC
Definition
Retrieve and print every row of the emp table.
Full Program Code
DisplayAllEmp.java
import java.sql.*;
public class DisplayAllEmp {
public static void main(String[] args) throws Exception {
String url = "jdbc:mysql://localhost:3306/college";
try (Connection con = DriverManager.getConnection(url, "root", "root");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM emp")) {
while (rs.next()) {
System.out.println(rs.getInt("empno") + "\t" + rs.getString("empnm") + "\t" +
rs.getString("designation") + "\t" + rs.getString("city") + "\t" +
rs.getDouble("salary") + "\t" + rs.getString("department"));
}
}
}
}
Expected Output
101 Ramesh Patel Manager Rajkot 55000.0 Sales
102 Sonal Shah Clerk Surat 22000.0 Accounts
Explanation
executeQuery() returns a ResultSet; rs.next() moves the cursor row by row and getter methods read each column by name.
In simple words: this program is a plain Java class (no web browser involved) that talks to MySQL using the JDBC API. The three building blocks you will see in almost every JDBC program are: (1) DriverManager.getConnection() to open a line to the database, (2) a Statement/PreparedStatement/CallableStatement to send SQL, and (3) a ResultSet to read back rows when the SQL is a SELECT. Always close these objects when done (the try (...) {} syntax used here does that automatically) so the database connection is released properly.
Program 3: Employees with salary greater than 50000 JDBC
Definition
Display employees whose salary exceeds 50000 using a WHERE clause.
Full Program Code
HighSalaryEmp.java
import java.sql.*;
public class HighSalaryEmp {
public static void main(String[] args) throws Exception {
try (Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/college", "root", "root");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM emp WHERE salary > 50000")) {
while (rs.next())
System.out.println(rs.getString("empnm") + " - " + rs.getDouble("salary"));
}
}
}
Expected Output
Ramesh Patel - 55000.0
Explanation
The SQL WHERE condition filters rows on the database side before they are returned to Java, which is efficient for large tables.
In simple words: this program is a plain Java class (no web browser involved) that talks to MySQL using the JDBC API. The three building blocks you will see in almost every JDBC program are: (1) DriverManager.getConnection() to open a line to the database, (2) a Statement/PreparedStatement/CallableStatement to send SQL, and (3) a ResultSet to read back rows when the SQL is a SELECT. Always close these objects when done (the try (...) {} syntax used here does that automatically) so the database connection is released properly.
Program 4: Employees from city 'Rajkot' JDBC
Definition
Display all employees whose city equals 'Rajkot'.
Full Program Code
CityEmp.java
import java.sql.*;
public class CityEmp {
public static void main(String[] args) throws Exception {
try (Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/college", "root", "root");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM emp WHERE city='Rajkot'")) {
while (rs.next())
System.out.println(rs.getInt("empno") + " " + rs.getString("empnm"));
}
}
}
Expected Output
101 Ramesh Patel
Explanation
A simple equality condition on a VARCHAR column, enclosed in single quotes in SQL.
In simple words: this program is a plain Java class (no web browser involved) that talks to MySQL using the JDBC API. The three building blocks you will see in almost every JDBC program are: (1) DriverManager.getConnection() to open a line to the database, (2) a Statement/PreparedStatement/CallableStatement to send SQL, and (3) a ResultSet to read back rows when the SQL is a SELECT. Always close these objects when done (the try (...) {} syntax used here does that automatically) so the database connection is released properly.
Program 5: Employees whose name starts with 'A' JDBC
Definition
Use the LIKE operator with a wildcard to find names starting with A.
Full Program Code
NameStartsA.java
import java.sql.*;
public class NameStartsA {
public static void main(String[] args) throws Exception {
try (Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/college", "root", "root");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM emp WHERE empnm LIKE 'A%'")) {
while (rs.next())
System.out.println(rs.getString("empnm"));
}
}
}
Expected Output
Amit Trivedi
Explanation
'A%' matches any string beginning with the letter A followed by zero or more characters.
In simple words: this program is a plain Java class (no web browser involved) that talks to MySQL using the JDBC API. The three building blocks you will see in almost every JDBC program are: (1) DriverManager.getConnection() to open a line to the database, (2) a Statement/PreparedStatement/CallableStatement to send SQL, and (3) a ResultSet to read back rows when the SQL is a SELECT. Always close these objects when done (the try (...) {} syntax used here does that automatically) so the database connection is released properly.
Program 6: Employees whose designation is manager JDBC
Definition
Filter employees on the designation column equal to 'Manager'.
Full Program Code
ManagerEmp.java
import java.sql.*;
public class ManagerEmp {
public static void main(String[] args) throws Exception {
try (Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/college", "root", "root");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM emp WHERE designation='Manager'")) {
while (rs.next())
System.out.println(rs.getString("empnm") + " manages " + rs.getString("department"));
}
}
}
Expected Output
Ramesh Patel manages Sales
Explanation
Exact string match filter on the designation column.
In simple words: this program is a plain Java class (no web browser involved) that talks to MySQL using the JDBC API. The three building blocks you will see in almost every JDBC program are: (1) DriverManager.getConnection() to open a line to the database, (2) a Statement/PreparedStatement/CallableStatement to send SQL, and (3) a ResultSet to read back rows when the SQL is a SELECT. Always close these objects when done (the try (...) {} syntax used here does that automatically) so the database connection is released properly.
Program 7: Count number of employees JDBC
Definition
Use the SQL COUNT() aggregate function.
Full Program Code
CountEmp.java
import java.sql.*;
public class CountEmp {
public static void main(String[] args) throws Exception {
try (Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/college", "root", "root");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT COUNT(*) AS total FROM emp")) {
if (rs.next())
System.out.println("Total employees: " + rs.getInt("total"));
}
}
}
Expected Output
Total employees: 2
Explanation
COUNT(*) returns the number of rows as a single-row, single-column ResultSet, read once with rs.next().
In simple words: this program is a plain Java class (no web browser involved) that talks to MySQL using the JDBC API. The three building blocks you will see in almost every JDBC program are: (1) DriverManager.getConnection() to open a line to the database, (2) a Statement/PreparedStatement/CallableStatement to send SQL, and (3) a ResultSet to read back rows when the SQL is a SELECT. Always close these objects when done (the try (...) {} syntax used here does that automatically) so the database connection is released properly.
Program 8: Employee with highest salary JDBC
Definition
Use MAX() to find the top salary, or ORDER BY + LIMIT.
Full Program Code
HighestSalary.java
import java.sql.*;
public class HighestSalary {
public static void main(String[] args) throws Exception {
try (Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/college", "root", "root");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(
"SELECT * FROM emp ORDER BY salary DESC LIMIT 1")) {
if (rs.next())
System.out.println(rs.getString("empnm") + " - " + rs.getDouble("salary"));
}
}
}
Expected Output
Ramesh Patel - 55000.0
Explanation
Sorting all rows descending by salary and taking the first row is equivalent to finding the maximum along with its full record.
In simple words: this program is a plain Java class (no web browser involved) that talks to MySQL using the JDBC API. The three building blocks you will see in almost every JDBC program are: (1) DriverManager.getConnection() to open a line to the database, (2) a Statement/PreparedStatement/CallableStatement to send SQL, and (3) a ResultSet to read back rows when the SQL is a SELECT. Always close these objects when done (the try (...) {} syntax used here does that automatically) so the database connection is released properly.
Program 9: Sort employee records by empnm JDBC
Definition
Use ORDER BY empnm to sort alphabetically.
Full Program Code
SortEmp.java
import java.sql.*;
public class SortEmp {
public static void main(String[] args) throws Exception {
try (Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/college", "root", "root");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM emp ORDER BY empnm ASC")) {
while (rs.next())
System.out.println(rs.getString("empnm"));
}
}
}
Expected Output
Amit Trivedi
Ramesh Patel
Sonal Shah
Explanation
ORDER BY sorts the result set on the database server before returning rows to the client.
In simple words: this program is a plain Java class (no web browser involved) that talks to MySQL using the JDBC API. The three building blocks you will see in almost every JDBC program are: (1) DriverManager.getConnection() to open a line to the database, (2) a Statement/PreparedStatement/CallableStatement to send SQL, and (3) a ResultSet to read back rows when the SQL is a SELECT. Always close these objects when done (the try (...) {} syntax used here does that automatically) so the database connection is released properly.
Program 10: Display employee record by empno (user input) JDBC
Definition
Accept empno from console and use PreparedStatement to fetch that record.
Full Program Code
EmpByNo.java
import java.sql.*;
import java.util.Scanner;
public class EmpByNo {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
System.out.print("Enter empno: ");
int no = sc.nextInt();
try (Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/college", "root", "root");
PreparedStatement ps = con.prepareStatement("SELECT * FROM emp WHERE empno=?")) {
ps.setInt(1, no);
try (ResultSet rs = ps.executeQuery()) {
if (rs.next())
System.out.println(rs.getString("empnm") + " | " + rs.getString("designation"));
else
System.out.println("No employee found with empno " + no);
}
}
}
}
Expected Output
Enter empno: 101
Ramesh Patel | Manager
Explanation
PreparedStatement with a ? placeholder avoids SQL injection and lets user input be bound safely with setInt().
In simple words: this program is a plain Java class (no web browser involved) that talks to MySQL using the JDBC API. The three building blocks you will see in almost every JDBC program are: (1) DriverManager.getConnection() to open a line to the database, (2) a Statement/PreparedStatement/CallableStatement to send SQL, and (3) a ResultSet to read back rows when the SQL is a SELECT. Always close these objects when done (the try (...) {} syntax used here does that automatically) so the database connection is released properly.
Program 11: Employee name & designation by department (user input) JDBC
Definition
Accept a department name and display matching employee names with designations.
Full Program Code
EmpByDept.java
import java.sql.*;
import java.util.Scanner;
public class EmpByDept {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
System.out.print("Enter department: ");
String dept = sc.nextLine();
try (Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/college", "root", "root");
PreparedStatement ps = con.prepareStatement(
"SELECT empnm, designation FROM emp WHERE department=?")) {
ps.setString(1, dept);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next())
System.out.println(rs.getString("empnm") + " - " + rs.getString("designation"));
}
}
}
}
Expected Output
Enter department: Sales
Ramesh Patel - Manager
Explanation
setString() binds the user's text safely into the query placeholder before execution.
In simple words: this program is a plain Java class (no web browser involved) that talks to MySQL using the JDBC API. The three building blocks you will see in almost every JDBC program are: (1) DriverManager.getConnection() to open a line to the database, (2) a Statement/PreparedStatement/CallableStatement to send SQL, and (3) a ResultSet to read back rows when the SQL is a SELECT. Always close these objects when done (the try (...) {} syntax used here does that automatically) so the database connection is released properly.
Program 12: Insert student record using PreparedStatement JDBC
Definition
Insert a row into stud table using PreparedStatement with bound parameters.
Full Program Code
InsertStud.java
import java.sql.*;
public class InsertStud {
public static void main(String[] args) throws Exception {
try (Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/college", "root", "root");
PreparedStatement ps = con.prepareStatement(
"INSERT INTO stud VALUES(?,?,?,?,?)")) {
ps.setInt(1, 1);
ps.setString(2, "Priya");
ps.setString(3, "Mehta");
ps.setString(4, "BCA");
ps.setInt(5, 5);
int rows = ps.executeUpdate();
System.out.println(rows + " student record inserted.");
}
}
}
Expected Output
1 student record inserted.
Explanation
PreparedStatement is precompiled once; setXxx() methods fill in the placeholders by position (1-indexed).
In simple words: this program is a plain Java class (no web browser involved) that talks to MySQL using the JDBC API. The three building blocks you will see in almost every JDBC program are: (1) DriverManager.getConnection() to open a line to the database, (2) a Statement/PreparedStatement/CallableStatement to send SQL, and (3) a ResultSet to read back rows when the SQL is a SELECT. Always close these objects when done (the try (...) {} syntax used here does that automatically) so the database connection is released properly.
Program 13: Update student record using PreparedStatement JDBC
Definition
Update a student's course using a parameterized UPDATE statement.
Full Program Code
UpdateStud.java
import java.sql.*;
public class UpdateStud {
public static void main(String[] args) throws Exception {
try (Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/college", "root", "root");
PreparedStatement ps = con.prepareStatement(
"UPDATE stud SET course=?, semester=? WHERE rollno=?")) {
ps.setString(1, "BCA-Hons");
ps.setInt(2, 6);
ps.setInt(3, 1);
int rows = ps.executeUpdate();
System.out.println(rows + " record(s) updated.");
}
}
}
Expected Output
1 record(s) updated.
Explanation
executeUpdate() on an UPDATE returns the count of rows modified in the table.
In simple words: this program is a plain Java class (no web browser involved) that talks to MySQL using the JDBC API. The three building blocks you will see in almost every JDBC program are: (1) DriverManager.getConnection() to open a line to the database, (2) a Statement/PreparedStatement/CallableStatement to send SQL, and (3) a ResultSet to read back rows when the SQL is a SELECT. Always close these objects when done (the try (...) {} syntax used here does that automatically) so the database connection is released properly.
Program 14: Delete student record by rollno (user input) JDBC
Definition
Accept rollno from the user and delete the matching row.
Full Program Code
DeleteStud.java
import java.sql.*;
import java.util.Scanner;
public class DeleteStud {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
System.out.print("Enter rollno to delete: ");
int roll = sc.nextInt();
try (Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/college", "root", "root");
PreparedStatement ps = con.prepareStatement("DELETE FROM stud WHERE rollno=?")) {
ps.setInt(1, roll);
int rows = ps.executeUpdate();
System.out.println(rows > 0 ? "Record deleted." : "No such rollno found.");
}
}
}
Expected Output
Enter rollno to delete: 1
Record deleted.
Explanation
DELETE with a bound rollno removes exactly the row(s) matching that primary key.
In simple words: this program is a plain Java class (no web browser involved) that talks to MySQL using the JDBC API. The three building blocks you will see in almost every JDBC program are: (1) DriverManager.getConnection() to open a line to the database, (2) a Statement/PreparedStatement/CallableStatement to send SQL, and (3) a ResultSet to read back rows when the SQL is a SELECT. Always close these objects when done (the try (...) {} syntax used here does that automatically) so the database connection is released properly.
Program 15: Insert default employee using CallableStatement (no-parameter procedure) JDBC
Definition
Create a stored procedure with no parameters that inserts a fixed default row, then call it from Java.
Full Program Code
proc_no_param.sql
DELIMITER //
CREATE PROCEDURE InsertDefaultEmp()
BEGIN
INSERT INTO emp VALUES(999,'Default Emp','Trainee','Rajkot',15000,'HR');
END //
DELIMITER ;
CallDefaultEmp.java
import java.sql.*;
public class CallDefaultEmp {
public static void main(String[] args) throws Exception {
try (Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/college", "root", "root");
CallableStatement cs = con.prepareCall("{call InsertDefaultEmp()}")) {
cs.execute();
System.out.println("Default employee inserted via procedure.");
}
}
}
Expected Output
Default employee inserted via procedure.
Explanation
CallableStatement with prepareCall("{call proc()}") invokes a stored procedure stored inside the database.
In simple words: this program is a plain Java class (no web browser involved) that talks to MySQL using the JDBC API. The three building blocks you will see in almost every JDBC program are: (1) DriverManager.getConnection() to open a line to the database, (2) a Statement/PreparedStatement/CallableStatement to send SQL, and (3) a ResultSet to read back rows when the SQL is a SELECT. Always close these objects when done (the try (...) {} syntax used here does that automatically) so the database connection is released properly.
Program 16: Insert employee using CallableStatement (procedure with parameters) JDBC
Definition
Create a parameterized stored procedure to insert an employee and call it with IN parameters.
Full Program Code
proc_with_param.sql
DELIMITER //
CREATE PROCEDURE InsertEmpParam(IN p_no INT, IN p_nm VARCHAR(50), IN p_desg VARCHAR(30),
IN p_city VARCHAR(30), IN p_sal DOUBLE, IN p_dept VARCHAR(30))
BEGIN
INSERT INTO emp VALUES(p_no,p_nm,p_desg,p_city,p_sal,p_dept);
END //
DELIMITER ;
CallInsertEmpParam.java
import java.sql.*;
public class CallInsertEmpParam {
public static void main(String[] args) throws Exception {
try (Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/college", "root", "root");
CallableStatement cs = con.prepareCall("{call InsertEmpParam(?,?,?,?,?,?)}")) {
cs.setInt(1, 102);
cs.setString(2, "Sonal Shah");
cs.setString(3, "Clerk");
cs.setString(4, "Surat");
cs.setDouble(5, 22000);
cs.setString(6, "Accounts");
cs.execute();
System.out.println("Employee inserted via parameterized procedure.");
}
}
}
Expected Output
Employee inserted via parameterized procedure.
Explanation
IN parameters of the procedure are bound the same way as PreparedStatement placeholders, using position-based setters.
In simple words: this program is a plain Java class (no web browser involved) that talks to MySQL using the JDBC API. The three building blocks you will see in almost every JDBC program are: (1) DriverManager.getConnection() to open a line to the database, (2) a Statement/PreparedStatement/CallableStatement to send SQL, and (3) a ResultSet to read back rows when the SQL is a SELECT. Always close these objects when done (the try (...) {} syntax used here does that automatically) so the database connection is released properly.
Program 17: Display designation by empno using CallableStatement JDBC
Definition
Create a procedure with an OUT parameter that returns the designation for a given empno.
Full Program Code
proc_get_desg.sql
DELIMITER //
CREATE PROCEDURE GetDesignation(IN p_no INT, OUT p_desg VARCHAR(30))
BEGIN
SELECT designation INTO p_desg FROM emp WHERE empno = p_no;
END //
DELIMITER ;
CallGetDesignation.java
import java.sql.*;
public class CallGetDesignation {
public static void main(String[] args) throws Exception {
try (Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/college", "root", "root");
CallableStatement cs = con.prepareCall("{call GetDesignation(?,?)}")) {
cs.setInt(1, 101);
cs.registerOutParameter(2, Types.VARCHAR);
cs.execute();
System.out.println("Designation: " + cs.getString(2));
}
}
}
Expected Output
Designation: Manager
Explanation
registerOutParameter() declares the SQL type of the OUT parameter so JDBC can read the value returned by the procedure with getString().
In simple words: this program is a plain Java class (no web browser involved) that talks to MySQL using the JDBC API. The three building blocks you will see in almost every JDBC program are: (1) DriverManager.getConnection() to open a line to the database, (2) a Statement/PreparedStatement/CallableStatement to send SQL, and (3) a ResultSet to read back rows when the SQL is a SELECT. Always close these objects when done (the try (...) {} syntax used here does that automatically) so the database connection is released properly.
Program 18: Display employees by designation (user input) using CallableStatement JDBC
Definition
Create a procedure returning a result set of all employees matching a given designation.
Full Program Code
proc_by_desg.sql
DELIMITER //
CREATE PROCEDURE EmpByDesignation(IN p_desg VARCHAR(30))
BEGIN
SELECT * FROM emp WHERE designation = p_desg;
END //
DELIMITER ;
CallEmpByDesignation.java
import java.sql.*;
import java.util.Scanner;
public class CallEmpByDesignation {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
System.out.print("Enter designation: ");
String desg = sc.nextLine();
try (Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/college", "root", "root");
CallableStatement cs = con.prepareCall("{call EmpByDesignation(?)}")) {
cs.setString(1, desg);
try (ResultSet rs = cs.executeQuery()) {
while (rs.next())
System.out.println(rs.getString("empnm"));
}
}
}
}
Expected Output
Enter designation: Manager
Ramesh Patel
Explanation
cs.executeQuery() is used instead of execute() because the procedure returns a SELECT result set.
In simple words: this program is a plain Java class (no web browser involved) that talks to MySQL using the JDBC API. The three building blocks you will see in almost every JDBC program are: (1) DriverManager.getConnection() to open a line to the database, (2) a Statement/PreparedStatement/CallableStatement to send SQL, and (3) a ResultSet to read back rows when the SQL is a SELECT. Always close these objects when done (the try (...) {} syntax used here does that automatically) so the database connection is released properly.
Program 19: CRUD operations on product table JDBC
Definition
Perform Create, Read, Update, Delete on a product table (pid, productname, price, quantity) via a menu-driven program.
Full Program Code
product_ddl.sql
CREATE TABLE product(pid INT PRIMARY KEY, productname VARCHAR(50), price DOUBLE, quantity INT);
ProductCRUD.java
import java.sql.*;
import java.util.Scanner;
public class ProductCRUD {
static Connection con;
public static void main(String[] args) throws Exception {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/college", "root", "root");
Scanner sc = new Scanner(System.in);
int ch;
do {
System.out.println("1.Insert 2.View 3.Update 4.Delete 5.Exit");
ch = sc.nextInt();
switch (ch) {
case 1: insert(sc); break;
case 2: view(); break;
case 3: update(sc); break;
case 4: delete(sc); break;
}
} while (ch != 5);
}
static void insert(Scanner sc) throws SQLException {
System.out.print("pid,name,price,qty: ");
int pid = sc.nextInt(); String nm = sc.next(); double pr = sc.nextDouble(); int qty = sc.nextInt();
PreparedStatement ps = con.prepareStatement("INSERT INTO product VALUES(?,?,?,?)");
ps.setInt(1, pid); ps.setString(2, nm); ps.setDouble(3, pr); ps.setInt(4, qty);
System.out.println(ps.executeUpdate() + " inserted");
}
static void view() throws SQLException {
ResultSet rs = con.createStatement().executeQuery("SELECT * FROM product");
while (rs.next())
System.out.println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getDouble(3) + " " + rs.getInt(4));
}
static void update(Scanner sc) throws SQLException {
System.out.print("pid to update, new price: ");
int pid = sc.nextInt(); double pr = sc.nextDouble();
PreparedStatement ps = con.prepareStatement("UPDATE product SET price=? WHERE pid=?");
ps.setDouble(1, pr); ps.setInt(2, pid);
System.out.println(ps.executeUpdate() + " updated");
}
static void delete(Scanner sc) throws SQLException {
System.out.print("pid to delete: ");
int pid = sc.nextInt();
PreparedStatement ps = con.prepareStatement("DELETE FROM product WHERE pid=?");
ps.setInt(1, pid);
System.out.println(ps.executeUpdate() + " deleted");
}
}
Expected Output
1.Insert 2.View 3.Update 4.Delete 5.Exit
1
pid,name,price,qty: 1 Pen 10.0 100
1 inserted
Explanation
A single menu-driven console loop dispatches to four helper methods, each demonstrating one CRUD operation with PreparedStatement.
In simple words: this program is a plain Java class (no web browser involved) that talks to MySQL using the JDBC API. The three building blocks you will see in almost every JDBC program are: (1) DriverManager.getConnection() to open a line to the database, (2) a Statement/PreparedStatement/CallableStatement to send SQL, and (3) a ResultSet to read back rows when the SQL is a SELECT. Always close these objects when done (the try (...) {} syntax used here does that automatically) so the database connection is released properly.
Program 20: Connect to database and retrieve metadata JDBC
Definition
Use DatabaseMetaData to print driver/database info and table columns.
Full Program Code
DbMetadata.java
import java.sql.*;
public class DbMetadata {
public static void main(String[] args) throws Exception {
try (Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/college", "root", "root")) {
DatabaseMetaData dmd = con.getMetaData();
System.out.println("Database: " + dmd.getDatabaseProductName() + " " + dmd.getDatabaseProductVersion());
System.out.println("Driver: " + dmd.getDriverName() + " " + dmd.getDriverVersion());
ResultSet rs = dmd.getColumns(null, null, "emp", null);
while (rs.next())
System.out.println("Column: " + rs.getString("COLUMN_NAME") + " Type: " + rs.getString("TYPE_NAME"));
}
}
}
Expected Output
Database: MySQL 8.0.x
Driver: MySQL Connector/J 8.x
Column: empno Type: INT
Column: empnm Type: VARCHAR
Explanation
DatabaseMetaData exposes information about the database engine and its schema, useful for building generic/dynamic tools.
In simple words: this program is a plain Java class (no web browser involved) that talks to MySQL using the JDBC API. The three building blocks you will see in almost every JDBC program are: (1) DriverManager.getConnection() to open a line to the database, (2) a Statement/PreparedStatement/CallableStatement to send SQL, and (3) a ResultSet to read back rows when the SQL is a SELECT. Always close these objects when done (the try (...) {} syntax used here does that automatically) so the database connection is released properly.
Program 21: Servlet to print Hello World Servlet
Definition
A basic servlet that writes 'Hello World' to the response using doGet().
Full Program Code
HelloServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<h1>Hello World</h1>");
}
}
Expected Output
Browser shows: Hello World (heading)
Explanation
@WebServlet maps the URL pattern /hello to this class; doGet() runs whenever that URL is requested with GET, writing HTML through the PrintWriter.
In simple words: a Servlet is a Java class that runs inside Tomcat and generates a web page (or handles a form) in response to a browser request. @WebServlet("/path") decides which URL triggers the class, doGet() handles normal link/address-bar requests, and doPost() handles form submissions with method="post". Anything the browser sends (form fields, cookies, headers) arrives through the HttpServletRequest parameter, and anything you want to send back goes through HttpServletResponse.
How to Run (extra steps beyond general setup)
Access at http://localhost:8080/<project>/hello
Program 22: Servlet displaying today's date and time Servlet
Definition
Use java.util.Date to print the current date/time in the response.
Full Program Code
DateServlet.java
import java.io.*;
import java.util.Date;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
@WebServlet("/date")
public class DateServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<h2>Current Date & Time: " + new Date() + "</h2>");
}
}
Expected Output
Current Date & Time: Tue Jul 14 10:22:31 IST 2026
Explanation
new Date() captures the server's current timestamp at request time and toString() formats it for display.
In simple words: a Servlet is a Java class that runs inside Tomcat and generates a web page (or handles a form) in response to a browser request. @WebServlet("/path") decides which URL triggers the class, doGet() handles normal link/address-bar requests, and doPost() handles form submissions with method="post". Anything the browser sends (form fields, cookies, headers) arrives through the HttpServletRequest parameter, and anything you want to send back goes through HttpServletResponse.
Program 23: Welcome user after form submission Servlet
Definition
An HTML form collects a username; the servlet reads it as a request parameter and greets the user.
Full Program Code
index.html
<form action="welcome" method="get">
Username: <input type="text" name="uname">
<input type="submit" value="Submit">
</form>
WelcomeServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
@WebServlet("/welcome")
public class WelcomeServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String name = req.getParameter("uname");
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<h2>Welcome " + name + "</h2>");
}
}
Expected Output
Welcome Alpesh
Explanation
req.getParameter("uname") reads the value submitted from the HTML form's input field named 'uname'.
In simple words: a Servlet is a Java class that runs inside Tomcat and generates a web page (or handles a form) in response to a browser request. @WebServlet("/path") decides which URL triggers the class, doGet() handles normal link/address-bar requests, and doPost() handles form submissions with method="post". Anything the browser sends (form fields, cookies, headers) arrives through the HttpServletRequest parameter, and anything you want to send back goes through HttpServletResponse.
Program 24: Display employee form data using GET method Servlet
Definition
Form collects Employee Number, Name, Designation, Qualification and displays them using GET.
Full Program Code
empform.html
<form action="empdetails" method="get">
Emp No: <input name="eno"><br>
Name: <input name="ename"><br>
Designation: <input name="desg"><br>
Qualification: <input name="qual"><br>
<input type="submit" value="Submit">
</form>
EmpDetailsServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
@WebServlet("/empdetails")
public class EmpDetailsServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("Emp No: " + req.getParameter("eno") + "<br>");
out.println("Name: " + req.getParameter("ename") + "<br>");
out.println("Designation: " + req.getParameter("desg") + "<br>");
out.println("Qualification: " + req.getParameter("qual"));
}
}
Expected Output
Emp No: 1
Name: Ravi
Designation: Developer
Qualification: MCA
Explanation
With method="get" the form data is appended to the URL as a query string (e.g. ?eno=1&ename=Ravi...), visible in the address bar.
In simple words: a Servlet is a Java class that runs inside Tomcat and generates a web page (or handles a form) in response to a browser request. @WebServlet("/path") decides which URL triggers the class, doGet() handles normal link/address-bar requests, and doPost() handles form submissions with method="post". Anything the browser sends (form fields, cookies, headers) arrives through the HttpServletRequest parameter, and anything you want to send back goes through HttpServletResponse.
Program 25: Register student using POST (getParameterNames/Values) Servlet
Definition
Form with rollno, name, course, semester, hobbies (checkboxes); servlet iterates all parameters generically.
Full Program Code
regform.html
<form action="register" method="post">
Roll No: <input name="rollno"><br>
Name: <input name="name"><br>
Course: <input name="course"><br>
Semester: <input name="semester"><br>
Hobbies: <input type="checkbox" name="hobby" value="Reading">Reading
<input type="checkbox" name="hobby" value="Sports">Sports<br>
<input type="submit" value="Register">
</form>
RegisterServlet.java
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
Enumeration<String> names = req.getParameterNames();
while (names.hasMoreElements()) {
String pname = names.nextElement();
String[] values = req.getParameterValues(pname);
out.println(pname + " = " + String.join(", ", values) + "<br>");
}
}
}
Expected Output
rollno = 1
name = Priya
course = BCA
semester = 5
hobby = Reading, Sports
Explanation
getParameterNames() enumerates every field name submitted; getParameterValues() returns an array because a field like a checkbox group may submit multiple values under one name.
In simple words: a Servlet is a Java class that runs inside Tomcat and generates a web page (or handles a form) in response to a browser request. @WebServlet("/path") decides which URL triggers the class, doGet() handles normal link/address-bar requests, and doPost() handles form submissions with method="post". Anything the browser sends (form fields, cookies, headers) arrives through the HttpServletRequest parameter, and anything you want to send back goes through HttpServletResponse.
Program 26: Demonstrate Servlet lifecycle Servlet
Definition
Override init(), service()/doGet(), and destroy() and print a message in each to show the lifecycle stages.
Full Program Code
LifecycleServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
@WebServlet("/lifecycle")
public class LifecycleServlet extends HttpServlet {
public void init() {
System.out.println("init(): Servlet is being initialized");
}
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
System.out.println("service(): Handling a request");
res.getWriter().println("Servlet Lifecycle Demo - check server console");
}
public void destroy() {
System.out.println("destroy(): Servlet is being destroyed");
}
}
Expected Output
Console: init(): Servlet is being initialized
Console: service(): Handling a request (on every hit)
Console (on server stop): destroy(): Servlet is being destroyed
Explanation
init() runs once when the servlet is first loaded, service()/doGet() runs once per request, and destroy() runs once before the servlet is unloaded (e.g. server shutdown).
In simple words: a Servlet is a Java class that runs inside Tomcat and generates a web page (or handles a form) in response to a browser request. @WebServlet("/path") decides which URL triggers the class, doGet() handles normal link/address-bar requests, and doPost() handles form submissions with method="post". Anything the browser sends (form fields, cookies, headers) arrives through the HttpServletRequest parameter, and anything you want to send back goes through HttpServletResponse.
Program 27: Display Basic Header Information Servlet
Definition
Enumerate all HTTP request headers using getHeaderNames().
Full Program Code
HeaderServlet.java
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
@WebServlet("/headers")
public class HeaderServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
Enumeration<String> hnames = req.getHeaderNames();
while (hnames.hasMoreElements()) {
String h = hnames.nextElement();
out.println(h + " : " + req.getHeader(h) + "<br>");
}
}
}
Expected Output
host : localhost:8080
user-agent : Mozilla/5.0 ...
accept : text/html,...
Explanation
Every browser request carries metadata (headers) like host, user-agent, accept types; this servlet lists them all dynamically.
In simple words: a Servlet is a Java class that runs inside Tomcat and generates a web page (or handles a form) in response to a browser request. @WebServlet("/path") decides which URL triggers the class, doGet() handles normal link/address-bar requests, and doPost() handles form submissions with method="post". Anything the browser sends (form fields, cookies, headers) arrives through the HttpServletRequest parameter, and anything you want to send back goes through HttpServletResponse.
Program 28: Login form with success/error message Servlet
Definition
Compare submitted username/password to hardcoded admin/admin and show appropriate message.
Full Program Code
login.html
<form action="login" method="post">
Username: <input name="uname"><br>
Password: <input type="password" name="pwd"><br>
<input type="submit" value="Login">
</form>
LoginServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String u = req.getParameter("uname");
String p = req.getParameter("pwd");
res.setContentType("text/html");
PrintWriter out = res.getWriter();
if ("admin".equals(u) && "admin".equals(p))
out.println("<h2>Welcome, Login Successful!</h2>");
else
out.println("<h2>Invalid username or password</h2>");
}
}
Expected Output
Welcome, Login Successful! (for admin/admin)
Invalid username or password (otherwise)
Explanation
A simple equals() check on the two submitted parameters decides which HTML branch to render.
In simple words: a Servlet is a Java class that runs inside Tomcat and generates a web page (or handles a form) in response to a browser request. @WebServlet("/path") decides which URL triggers the class, doGet() handles normal link/address-bar requests, and doPost() handles form submissions with method="post". Anything the browser sends (form fields, cookies, headers) arrives through the HttpServletRequest parameter, and anything you want to send back goes through HttpServletResponse.
Program 29: Radio button arithmetic operations Servlet
Definition
Form has two numbers and radio buttons for +,-,*,/; servlet performs the chosen operation.
Full Program Code
calc.html
<form action="calc" method="post">
Num1: <input name="n1"><br>
Num2: <input name="n2"><br>
<input type="radio" name="op" value="add" checked>Add
<input type="radio" name="op" value="sub">Subtract
<input type="radio" name="op" value="mul">Multiply
<input type="radio" name="op" value="div">Divide<br>
<input type="submit" value="Calculate">
</form>
CalcServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
@WebServlet("/calc")
public class CalcServlet extends HttpServlet {
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
double n1 = Double.parseDouble(req.getParameter("n1"));
double n2 = Double.parseDouble(req.getParameter("n2"));
String op = req.getParameter("op");
double result = 0;
switch (op) {
case "add": result = n1 + n2; break;
case "sub": result = n1 - n2; break;
case "mul": result = n1 * n2; break;
case "div": result = n2 != 0 ? n1 / n2 : 0; break;
}
res.setContentType("text/html");
res.getWriter().println("Result: " + result);
}
}
Expected Output
Result: 15.0
Explanation
Only the checked radio button's value is submitted under the shared name 'op', which the switch statement uses to choose the operation.
In simple words: a Servlet is a Java class that runs inside Tomcat and generates a web page (or handles a form) in response to a browser request. @WebServlet("/path") decides which URL triggers the class, doGet() handles normal link/address-bar requests, and doPost() handles form submissions with method="post". Anything the browser sends (form fields, cookies, headers) arrives through the HttpServletRequest parameter, and anything you want to send back goes through HttpServletResponse.
Program 30: Redirect a page to google.com Servlet
Definition
Use HttpServletResponse.sendRedirect() to send the browser to another URL.
Full Program Code
RedirectServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
@WebServlet("/goGoogle")
public class RedirectServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.sendRedirect("https://www.google.com");
}
}
Expected Output
Browser navigates to https://www.google.com
Explanation
sendRedirect() sends an HTTP 302 response with a Location header; the browser then makes a fresh request to that new URL.
In simple words: a Servlet is a Java class that runs inside Tomcat and generates a web page (or handles a form) in response to a browser request. @WebServlet("/path") decides which URL triggers the class, doGet() handles normal link/address-bar requests, and doPost() handles form submissions with method="post". Anything the browser sends (form fields, cookies, headers) arrives through the HttpServletRequest parameter, and anything you want to send back goes through HttpServletResponse.
Program 31: Custom 404 error page Servlet
Definition
Configure a custom error page for HTTP 404 in web.xml.
Full Program Code
web.xml
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" version="4.0">
<error-page>
<error-code>404</error-code>
<location>/error404.html</location>
</error-page>
</web-app>
error404.html
<html><body>
<h2>Oops! Page Not Found (404)</h2>
<p>The page you requested does not exist. <a href="/">Go home</a></p>
</body></html>
Expected Output
Requesting a non-existent URL shows: Oops! Page Not Found (404)
Explanation
The <error-page> element maps a specific HTTP status code to a custom resource that the container serves instead of its default error page.
In simple words: a Servlet is a Java class that runs inside Tomcat and generates a web page (or handles a form) in response to a browser request. @WebServlet("/path") decides which URL triggers the class, doGet() handles normal link/address-bar requests, and doPost() handles form submissions with method="post". Anything the browser sends (form fields, cookies, headers) arrives through the HttpServletRequest parameter, and anything you want to send back goes through HttpServletResponse.
Program 32: URL Rewriting demo Servlet
Definition
Append session id / data manually to a URL as a query parameter and read it back, for when cookies are disabled.
Full Program Code
URLRewriteServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
@WebServlet("/rewrite")
public class URLRewriteServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String user = req.getParameter("user");
if (user == null) {
String encodedURL = res.encodeURL("rewrite?user=Alpesh");
out.println("<a href='" + encodedURL + "'>Click to pass username via URL</a>");
} else {
out.println("Welcome " + user + " (received via URL rewriting)");
}
}
}
Expected Output
Click link -> Welcome Alpesh (received via URL rewriting)
Explanation
res.encodeURL() appends the session id to the URL automatically when cookies are unavailable, and manual query parameters carry ordinary data across requests.
In simple words: a Servlet is a Java class that runs inside Tomcat and generates a web page (or handles a form) in response to a browser request. @WebServlet("/path") decides which URL triggers the class, doGet() handles normal link/address-bar requests, and doPost() handles form submissions with method="post". Anything the browser sends (form fields, cookies, headers) arrives through the HttpServletRequest parameter, and anything you want to send back goes through HttpServletResponse.
Program 33: Hidden Form Field demo Servlet
Definition
Pass data invisibly between a form and servlet using an <input type="hidden">.
Full Program Code
hiddenform.html
<form action="hidden" method="post">
Name: <input name="uname"><br>
<input type="hidden" name="source" value="RegistrationPage">
<input type="submit" value="Submit">
</form>
HiddenFieldServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
@WebServlet("/hidden")
public class HiddenFieldServlet extends HttpServlet {
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
res.getWriter().println("Name: " + req.getParameter("uname") +
"<br>Came from (hidden field): " + req.getParameter("source"));
}
}
Expected Output
Name: Priya
Came from (hidden field): RegistrationPage
Explanation
Hidden fields are not shown to the user but are still submitted with the form, useful for passing tracking or state data.
In simple words: a Servlet is a Java class that runs inside Tomcat and generates a web page (or handles a form) in response to a browser request. @WebServlet("/path") decides which URL triggers the class, doGet() handles normal link/address-bar requests, and doPost() handles form submissions with method="post". Anything the browser sends (form fields, cookies, headers) arrives through the HttpServletRequest parameter, and anything you want to send back goes through HttpServletResponse.
Program 34: Check/create cookie and display all cookies Servlet
Definition
If a specific cookie is absent, create it; then list all cookies sent by the browser.
Full Program Code
CookieCheckServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
@WebServlet("/cookiecheck")
public class CookieCheckServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
Cookie[] cookies = req.getCookies();
boolean found = false;
if (cookies != null)
for (Cookie c : cookies)
if (c.getName().equals("visited")) found = true;
if (!found) {
Cookie c = new Cookie("visited", "true");
res.addCookie(c);
out.println("New cookie 'visited' created.<br>");
} else {
out.println("Cookie 'visited' already exists.<br>");
}
out.println("All cookies sent by browser:<br>");
if (cookies != null)
for (Cookie c : cookies)
out.println(c.getName() + " = " + c.getValue() + "<br>");
}
}
Expected Output
First visit: New cookie 'visited' created.
Next visit: Cookie 'visited' already exists. + list of cookies
Explanation
req.getCookies() reads cookies the browser sends back on each request; res.addCookie() tells the browser to store a new one for future requests.
In simple words: a Servlet is a Java class that runs inside Tomcat and generates a web page (or handles a form) in response to a browser request. @WebServlet("/path") decides which URL triggers the class, doGet() handles normal link/address-bar requests, and doPost() handles form submissions with method="post". Anything the browser sends (form fields, cookies, headers) arrives through the HttpServletRequest parameter, and anything you want to send back goes through HttpServletResponse.
Program 35: Cookie with name/value, max-age, retrieve all Servlet
Definition
Create a 'username' cookie valid for 1 day, add it, then list all cookies received (or a no-cookie message).
Full Program Code
CookieDemoServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
@WebServlet("/cookiedemo")
public class CookieDemoServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
Cookie c = new Cookie("username", "yourname");
c.setMaxAge(24 * 60 * 60);
res.addCookie(c);
res.setContentType("text/html");
PrintWriter out = res.getWriter();
Cookie[] cookies = req.getCookies();
if (cookies == null || cookies.length == 0) {
out.println("No cookies found.");
} else {
for (Cookie ck : cookies)
out.println(ck.getName() + " = " + ck.getValue() + "<br>");
}
}
}
Expected Output
username = yourname
Explanation
setMaxAge(86400) makes the cookie persist in the browser for 24 hours instead of expiring when the browser closes.
In simple words: a Servlet is a Java class that runs inside Tomcat and generates a web page (or handles a form) in response to a browser request. @WebServlet("/path") decides which URL triggers the class, doGet() handles normal link/address-bar requests, and doPost() handles form submissions with method="post". Anything the browser sends (form fields, cookies, headers) arrives through the HttpServletRequest parameter, and anything you want to send back goes through HttpServletResponse.
Program 36: Welcome / Welcome back using Cookie Servlet
Definition
First visit shows Welcome; subsequent visits (cookie present) show Welcome back.
Full Program Code
WelcomeCookieServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
@WebServlet("/welcomecookie")
public class WelcomeCookieServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
Cookie[] cookies = req.getCookies();
boolean visited = false;
if (cookies != null)
for (Cookie c : cookies)
if (c.getName().equals("visitedBefore")) visited = true;
if (visited) {
out.println("Welcome back!");
} else {
out.println("Welcome!");
Cookie c = new Cookie("visitedBefore", "yes");
c.setMaxAge(24 * 60 * 60);
res.addCookie(c);
}
}
}
Expected Output
First visit: Welcome!
Second visit onward: Welcome back!
Explanation
The presence of the 'visitedBefore' cookie on incoming requests distinguishes a first-time visitor from a returning one.
In simple words: a Servlet is a Java class that runs inside Tomcat and generates a web page (or handles a form) in response to a browser request. @WebServlet("/path") decides which URL triggers the class, doGet() handles normal link/address-bar requests, and doPost() handles form submissions with method="post". Anything the browser sends (form fields, cookies, headers) arrives through the HttpServletRequest parameter, and anything you want to send back goes through HttpServletResponse.
Program 37: Select background color, save in cookie, apply Servlet
Definition
Dropdown of colors submits to servlet, which stores the choice in a cookie and applies it as page background.
Full Program Code
colorform.html
<form action="setcolor" method="get">
<select name="color">
<option value="lightblue">Light Blue</option>
<option value="lightgreen">Light Green</option>
<option value="pink">Pink</option>
</select>
<input type="submit" value="Apply">
</form>
SetColorServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
@WebServlet("/setcolor")
public class SetColorServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String color = req.getParameter("color");
Cookie c = new Cookie("bgcolor", color);
c.setMaxAge(24 * 60 * 60);
res.addCookie(c);
res.setContentType("text/html");
res.getWriter().println("<body bgcolor='" + color + "'><h2>Background set to " + color + "</h2></body>");
}
}
Expected Output
Page renders with the chosen background color, e.g. pink
Explanation
The selected dropdown value is stored as a cookie so the color choice can be remembered and reapplied on future visits.
In simple words: a Servlet is a Java class that runs inside Tomcat and generates a web page (or handles a form) in response to a browser request. @WebServlet("/path") decides which URL triggers the class, doGet() handles normal link/address-bar requests, and doPost() handles form submissions with method="post". Anything the browser sends (form fields, cookies, headers) arrives through the HttpServletRequest parameter, and anything you want to send back goes through HttpServletResponse.
Program 38: Welcome / Welcome back using Session Servlet
Definition
Same as program 36 but using HttpSession instead of cookies.
Full Program Code
WelcomeSessionServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
@WebServlet("/welcomesession")
public class WelcomeSessionServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
HttpSession session = req.getSession();
res.setContentType("text/html");
PrintWriter out = res.getWriter();
if (session.getAttribute("visited") != null) {
out.println("Welcome back!");
} else {
out.println("Welcome!");
session.setAttribute("visited", "yes");
}
}
}
Expected Output
First hit in session: Welcome!
Subsequent hits in same session: Welcome back!
Explanation
req.getSession() creates or retrieves the session tied to the client via a JSESSIONID; setAttribute()/getAttribute() store data on the server side for that session.
In simple words: a Servlet is a Java class that runs inside Tomcat and generates a web page (or handles a form) in response to a browser request. @WebServlet("/path") decides which URL triggers the class, doGet() handles normal link/address-bar requests, and doPost() handles form submissions with method="post". Anything the browser sends (form fields, cookies, headers) arrives through the HttpServletRequest parameter, and anything you want to send back goes through HttpServletResponse.
Program 39: Store name in session and greet on subsequent visits Servlet
Definition
Accept name via form, store in session; on later requests within the same session, greet by name without asking again.
Full Program Code
nameform.html
<form action="greet" method="post">
Name: <input name="uname">
<input type="submit" value="Submit">
</form>
GreetSessionServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
@WebServlet("/greet")
public class GreetSessionServlet extends HttpServlet {
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
HttpSession session = req.getSession();
String name = req.getParameter("uname");
if (name != null) session.setAttribute("uname", name);
String stored = (String) session.getAttribute("uname");
res.setContentType("text/html");
res.getWriter().println("Hello, " + stored + "!");
}
}
Expected Output
Hello, Priya!
Explanation
Once the name is stored with setAttribute(), any servlet sharing the same session can retrieve it via getAttribute() without the user re-entering it.
In simple words: a Servlet is a Java class that runs inside Tomcat and generates a web page (or handles a form) in response to a browser request. @WebServlet("/path") decides which URL triggers the class, doGet() handles normal link/address-bar requests, and doPost() handles form submissions with method="post". Anything the browser sends (form fields, cookies, headers) arrives through the HttpServletRequest parameter, and anything you want to send back goes through HttpServletResponse.
Program 40: Login authentication storing username in session with logout Servlet
Definition
Full login flow: validate credentials, store username in session on success, personalized welcome page, and a logout servlet that invalidates the session.
Full Program Code
LoginAuthServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
@WebServlet("/loginauth")
public class LoginAuthServlet extends HttpServlet {
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String u = req.getParameter("uname");
String p = req.getParameter("pwd");
res.setContentType("text/html");
PrintWriter out = res.getWriter();
if ("admin".equals(u) && "admin".equals(p)) {
HttpSession session = req.getSession();
session.setAttribute("user", u);
out.println("Welcome " + u + "! <a href='logout'>Logout</a>");
} else {
out.println("Login failed: invalid username or password");
}
}
}
LogoutServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
@WebServlet("/logout")
public class LogoutServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
HttpSession session = req.getSession(false);
if (session != null) session.invalidate();
res.getWriter().println("You have been logged out.");
}
}
Expected Output
Welcome admin! Logout link
...after clicking Logout: You have been logged out.
Explanation
session.invalidate() destroys the session and all attributes stored in it, effectively logging the user out.
In simple words: a Servlet is a Java class that runs inside Tomcat and generates a web page (or handles a form) in response to a browser request. @WebServlet("/path") decides which URL triggers the class, doGet() handles normal link/address-bar requests, and doPost() handles form submissions with method="post". Anything the browser sends (form fields, cookies, headers) arrives through the HttpServletRequest parameter, and anything you want to send back goes through HttpServletResponse.
Program 41: Count visits during a session Servlet
Definition
Increment a counter stored as a session attribute on every page load.
Full Program Code
VisitCountServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
@WebServlet("/visitcount")
public class VisitCountServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
HttpSession session = req.getSession();
Integer count = (Integer) session.getAttribute("count");
count = (count == null) ? 1 : count + 1;
session.setAttribute("count", count);
res.setContentType("text/html");
res.getWriter().println("You have visited this page " + count + " time(s).");
}
}
Expected Output
You have visited this page 3 time(s).
Explanation
The counter persists across requests because it lives in the session, and is incremented each time the same page is loaded.
In simple words: a Servlet is a Java class that runs inside Tomcat and generates a web page (or handles a form) in response to a browser request. @WebServlet("/path") decides which URL triggers the class, doGet() handles normal link/address-bar requests, and doPost() handles form submissions with method="post". Anything the browser sends (form fields, cookies, headers) arrives through the HttpServletRequest parameter, and anything you want to send back goes through HttpServletResponse.
Program 42: Select background color, save in session, apply Servlet
Definition
Same as program 37 but the chosen color is stored in the session rather than a cookie.
Full Program Code
SetColorSessionServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
@WebServlet("/setcolorsession")
public class SetColorSessionServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
HttpSession session = req.getSession();
String color = req.getParameter("color");
if (color != null) session.setAttribute("bgcolor", color);
String current = (String) session.getAttribute("bgcolor");
res.setContentType("text/html");
res.getWriter().println("<body bgcolor='" + current + "'><h2>Theme: " + current + "</h2></body>");
}
}
Expected Output
Page renders with the session-stored background color
Explanation
Storing the value in the session (server-side) keeps it available across every page in the same browsing session without round-tripping a cookie.
In simple words: a Servlet is a Java class that runs inside Tomcat and generates a web page (or handles a form) in response to a browser request. @WebServlet("/path") decides which URL triggers the class, doGet() handles normal link/address-bar requests, and doPost() handles form submissions with method="post". Anything the browser sends (form fields, cookies, headers) arrives through the HttpServletRequest parameter, and anything you want to send back goes through HttpServletResponse.
Program 43: Redirect to login if not logged in (session check) Servlet
Definition
Check for a session attribute on every request; if absent, redirect to the login form, else show a welcome message.
Full Program Code
AuthCheckServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
@WebServlet("/secure")
public class AuthCheckServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
HttpSession session = req.getSession(false);
if (session == null || session.getAttribute("user") == null) {
res.sendRedirect("login.html");
return;
}
res.setContentType("text/html");
res.getWriter().println("Welcome, " + session.getAttribute("user") + "! This is a secure page.");
}
}
Expected Output
Not logged in: browser redirected to login.html
Logged in: Welcome, admin! This is a secure page.
Explanation
getSession(false) returns null instead of creating a new session if one doesn't already exist, letting the servlet distinguish logged-in from anonymous users.
In simple words: a Servlet is a Java class that runs inside Tomcat and generates a web page (or handles a form) in response to a browser request. @WebServlet("/path") decides which URL triggers the class, doGet() handles normal link/address-bar requests, and doPost() handles form submissions with method="post". Anything the browser sends (form fields, cookies, headers) arrives through the HttpServletRequest parameter, and anything you want to send back goes through HttpServletResponse.
Program 44: JSP to print Hello World JSP
Definition
A .jsp page mixing HTML with a JSP scriptlet/expression to print Hello World.
Full Program Code
hello.jsp
<html><body>
<h1>Hello World</h1>
<p>Printed using JSP expression: <%= "Hello World from JSP" %></p>
</body></html>
Expected Output
Hello World
Printed using JSP expression: Hello World from JSP
Explanation
JSP is translated by the container into a servlet behind the scenes; <%= %> is a JSP expression tag that outputs a value directly into the HTML.
In simple words: a JSP (JavaServer Page) lets you write HTML and Java in the same file, which is convenient for pages that are mostly display with a little bit of logic. Behind the scenes, Tomcat converts every .jsp file into a servlet the first time it is requested, so a JSP has access to the same request/response/session objects as a servlet, only they are already available as ready-made variables (request, session, application) without you needing to declare them.
Program 45: Accept and display student details JSP
Definition
HTML form posts student data to a JSP that reads request parameters and prints them.
Full Program Code
studform.html
<form action="studdetails.jsp" method="post">
Name: <input name="name"><br>
Course: <input name="course"><br>
Semester: <input name="sem"><br>
<input type="submit" value="Submit">
</form>
studdetails.jsp
<html><body>
<h3>Student Details</h3>
Name: <%= request.getParameter("name") %><br>
Course: <%= request.getParameter("course") %><br>
Semester: <%= request.getParameter("sem") %>
</body></html>
Expected Output
Student Details
Name: Priya
Course: BCA
Semester: 5
Explanation
The implicit 'request' object is automatically available in every JSP page and provides getParameter() just like in a servlet.
In simple words: a JSP (JavaServer Page) lets you write HTML and Java in the same file, which is convenient for pages that are mostly display with a little bit of logic. Behind the scenes, Tomcat converts every .jsp file into a servlet the first time it is requested, so a JSP has access to the same request/response/session objects as a servlet, only they are already available as ready-made variables (request, session, application) without you needing to declare them.
Program 46: Check leap year JSP
Definition
Accept a year and use a scriptlet with if-else to determine if it's a leap year.
Full Program Code
leapform.html
<form action="leap.jsp" method="get">
Year: <input name="year">
<input type="submit" value="Check">
</form>
leap.jsp
<html><body>
<%
int year = Integer.parseInt(request.getParameter("year"));
boolean leap = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
%>
<h3><%= year %> is <%= leap ? "a Leap Year" : "not a Leap Year" %></h3>
</body></html>
Expected Output
2024 is a Leap Year
Explanation
A JSP scriptlet <% %> contains ordinary Java code; the leap year rule is evaluated there and the boolean result is displayed with an expression tag.
In simple words: a JSP (JavaServer Page) lets you write HTML and Java in the same file, which is convenient for pages that are mostly display with a little bit of logic. Behind the scenes, Tomcat converts every .jsp file into a servlet the first time it is requested, so a JSP has access to the same request/response/session objects as a servlet, only they are already available as ready-made variables (request, session, application) without you needing to declare them.
Program 47: Calculate simple interest JSP
Definition
Accept principal, rate, time and compute simple interest = P*R*T/100.
Full Program Code
siform.html
<form action="si.jsp" method="get">
Principal: <input name="p"><br>
Rate: <input name="r"><br>
Time: <input name="t"><br>
<input type="submit" value="Calculate">
</form>
si.jsp
<html><body>
<%
double p = Double.parseDouble(request.getParameter("p"));
double r = Double.parseDouble(request.getParameter("r"));
double t = Double.parseDouble(request.getParameter("t"));
double si = (p * r * t) / 100;
%>
<h3>Simple Interest = <%= si %></h3>
</body></html>
Expected Output
Simple Interest = 3000.0
Explanation
The scriptlet performs the arithmetic in Java and the result is embedded directly into the HTML response.
In simple words: a JSP (JavaServer Page) lets you write HTML and Java in the same file, which is convenient for pages that are mostly display with a little bit of logic. Behind the scenes, Tomcat converts every .jsp file into a servlet the first time it is requested, so a JSP has access to the same request/response/session objects as a servlet, only they are already available as ready-made variables (request, session, application) without you needing to declare them.
Program 48: Division with custom error page (isErrorPage) JSP
Definition
Divide two numbers; if divisor is zero, forward to an error page configured with isErrorPage="true".
Full Program Code
divform.html
<form action="divide.jsp" method="get">
Numerator: <input name="a"><br>
Denominator: <input name="b"><br>
<input type="submit" value="Divide">
</form>
divide.jsp
<%@ page errorPage="error.jsp" %>
<html><body>
<%
int a = Integer.parseInt(request.getParameter("a"));
int b = Integer.parseInt(request.getParameter("b"));
int result = a / b;
%>
<h3>Result = <%= result %></h3>
</body></html>
error.jsp
<%@ page isErrorPage="true" %>
<html><body>
<h3>An error occurred: <%= exception.getMessage() %></h3>
</body></html>
Expected Output
Denominator=0: An error occurred: / by zero
Explanation
errorPage="error.jsp" on the source page automatically forwards any uncaught exception there; isErrorPage="true" on the target page exposes the implicit 'exception' object.
In simple words: a JSP (JavaServer Page) lets you write HTML and Java in the same file, which is convenient for pages that are mostly display with a little bit of logic. Behind the scenes, Tomcat converts every .jsp file into a servlet the first time it is requested, so a JSP has access to the same request/response/session objects as a servlet, only they are already available as ready-made variables (request, session, application) without you needing to declare them.
Program 49: Configure 404 error page in web.xml (JSP) JSP
Definition
Map HTTP 404 to a friendly JSP error page without leaking technical details.
Full Program Code
web.xml
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" version="4.0">
<error-page>
<error-code>404</error-code>
<location>/notfound.jsp</location>
</error-page>
</web-app>
notfound.jsp
<html><body>
<h2>Sorry, the page you are looking for could not be found.</h2>
<a href="/">Return to Home</a>
</body></html>
Expected Output
Requesting a missing URL shows: Sorry, the page you are looking for could not be found.
Explanation
Same error-page mechanism as servlets, but pointed at a .jsp resource instead of a plain .html file.
In simple words: a JSP (JavaServer Page) lets you write HTML and Java in the same file, which is convenient for pages that are mostly display with a little bit of logic. Behind the scenes, Tomcat converts every .jsp file into a servlet the first time it is requested, so a JSP has access to the same request/response/session objects as a servlet, only they are already available as ready-made variables (request, session, application) without you needing to declare them.
Program 50: Include header and footer using jsp:include JSP
Definition
Reuse common header.jsp and footer.jsp inside a main content page.
Full Program Code
header.jsp
<div style='background:#eee;padding:8px;'><b>My Website Header</b></div>
footer.jsp
<div style='background:#eee;padding:8px;'><i>© 2026 My Website</i></div>
main.jsp
<html><body>
<jsp:include page="header.jsp" />
<h2>Welcome to the Main Content Area</h2>
<p>This is the body of the page.</p>
<jsp:include page="footer.jsp" />
</body></html>
Expected Output
My Website Header
Welcome to the Main Content Area / body text
Copyright footer
Explanation
<jsp:include> performs a dynamic (runtime) include, re-executing the included page on every request and merging its output into the caller's response.
In simple words: a JSP (JavaServer Page) lets you write HTML and Java in the same file, which is convenient for pages that are mostly display with a little bit of logic. Behind the scenes, Tomcat converts every .jsp file into a servlet the first time it is requested, so a JSP has access to the same request/response/session objects as a servlet, only they are already available as ready-made variables (request, session, application) without you needing to declare them.
Program 51: jsp:forward based on favorite color JSP
Definition
process.jsp forwards to blue.jsp if input is 'blue', else to default.jsp, with no output sent before forwarding.
Full Program Code
colorform2.html
<form action="process.jsp" method="get">
Favorite Color: <input name="color">
<input type="submit" value="Go">
</form>
process.jsp
<%
String color = request.getParameter("color");
if ("blue".equalsIgnoreCase(color)) {
%>
<jsp:forward page="blue.jsp" />
<%
} else {
%>
<jsp:forward page="default.jsp" />
<%
}
%>
blue.jsp
<html><body><h2 style='color:blue;'>You love Blue!</h2></body></html>
default.jsp
<html><body><h2>Thanks for sharing your favorite color!</h2></body></html>
Expected Output
Input 'blue': You love Blue!
Any other input: Thanks for sharing your favorite color!
Explanation
<jsp:forward> transfers control entirely to another resource on the server without a browser redirect; nothing must be flushed to the client beforehand, otherwise forwarding fails.
In simple words: a JSP (JavaServer Page) lets you write HTML and Java in the same file, which is convenient for pages that are mostly display with a little bit of logic. Behind the scenes, Tomcat converts every .jsp file into a servlet the first time it is requested, so a JSP has access to the same request/response/session objects as a servlet, only they are already available as ready-made variables (request, session, application) without you needing to declare them.
Program 52: jsp:useBean with User bean JSP
Definition
Define a User JavaBean (name, email, age) and instantiate/display it with jsp:useBean and jsp:getProperty.
Full Program Code
User.java
package beans;
public class User implements java.io.Serializable {
private String name, email;
private int age;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
}
userbean.jsp
<jsp:useBean id="u" class="beans.User" scope="page" />
<jsp:setProperty name="u" property="name" value="Priya Mehta" />
<jsp:setProperty name="u" property="email" value="priya@example.com" />
<jsp:setProperty name="u" property="age" value="21" />
<html><body>
Name: <jsp:getProperty name="u" property="name" /><br>
Email: <jsp:getProperty name="u" property="email" /><br>
Age: <jsp:getProperty name="u" property="age" />
</body></html>
Expected Output
Name: Priya Mehta
Email: priya@example.com
Age: 21
Explanation
jsp:useBean instantiates (or reuses) a JavaBean instance in the given scope; setProperty/getProperty call the bean's standard setter/getter methods behind the scenes.
In simple words: a JSP (JavaServer Page) lets you write HTML and Java in the same file, which is convenient for pages that are mostly display with a little bit of logic. Behind the scenes, Tomcat converts every .jsp file into a servlet the first time it is requested, so a JSP has access to the same request/response/session objects as a servlet, only they are already available as ready-made variables (request, session, application) without you needing to declare them.
How to Run (extra steps beyond general setup)
Place User.java under WEB-INF/classes/beans (or src, compiled by the IDE).
Program 53: EmployeeBean with session scope JSP
Definition
Create EmployeeBean (name, designation, salary), instantiate with useBean id=employee scope=session, set via setProperty, display via EL ${}.
Full Program Code
EmployeeBean.java
package beans;
public class EmployeeBean implements java.io.Serializable {
private String name, designation;
private double salary;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getDesignation() { return designation; }
public void setDesignation(String designation) { this.designation = designation; }
public double getSalary() { return salary; }
public void setSalary(double salary) { this.salary = salary; }
}
empbean.jsp
<jsp:useBean id="employee" class="beans.EmployeeBean" scope="session" />
<jsp:setProperty name="employee" property="name" value="Ramesh Patel" />
<jsp:setProperty name="employee" property="designation" value="Manager" />
<jsp:setProperty name="employee" property="salary" value="55000" />
<html><body>
Name: ${employee.name}<br>
Designation: ${employee.designation}<br>
Salary: ${employee.salary}
</body></html>
Expected Output
Name: Ramesh Patel
Designation: Manager
Salary: 55000.0
Explanation
With scope="session" the bean persists across multiple JSP pages for the same user until the session ends; ${employee.name} is Expression Language reading the bean's getName() automatically.
In simple words: a JSP (JavaServer Page) lets you write HTML and Java in the same file, which is convenient for pages that are mostly display with a little bit of logic. Behind the scenes, Tomcat converts every .jsp file into a servlet the first time it is requested, so a JSP has access to the same request/response/session objects as a servlet, only they are already available as ready-made variables (request, session, application) without you needing to declare them.
Program 54: Global visitor counter using application object JSP
Definition
Increment a counter stored in application scope every time the page loads, showing total visits since server start.
Full Program Code
visitorcount.jsp
<%
Integer count = (Integer) application.getAttribute("visitorCount");
if (count == null) count = 0;
count++;
application.setAttribute("visitorCount", count);
%>
<html><body>
<h3>Total visitors since server started: <%= count %></h3>
</body></html>
Expected Output
Total visitors since server started: 7
Explanation
The implicit 'application' object (ServletContext) is shared by all users and all sessions of the web app, making it ideal for a global counter.
In simple words: a JSP (JavaServer Page) lets you write HTML and Java in the same file, which is convenient for pages that are mostly display with a little bit of logic. Behind the scenes, Tomcat converts every .jsp file into a servlet the first time it is requested, so a JSP has access to the same request/response/session objects as a servlet, only they are already available as ready-made variables (request, session, application) without you needing to declare them.
Program 55: Login/welcome/logout using session across pages JSP
Definition
login.jsp collects username, stores in session; welcome.jsp shows it; logout.jsp invalidates session and redirects to login.jsp.
Full Program Code
login.jsp
<html><body>
<form action="dologin.jsp" method="post">
Username: <input name="uname">
<input type="submit" value="Login">
</form>
</body></html>
dologin.jsp
<%
session.setAttribute("uname", request.getParameter("uname"));
response.sendRedirect("welcome.jsp");
%>
welcome.jsp
<html><body>
<h3>Welcome, <%= session.getAttribute("uname") %>!</h3>
<a href="logout.jsp">Logout</a>
</body></html>
logout.jsp
<%
session.invalidate();
response.sendRedirect("login.jsp");
%>
Expected Output
After login: Welcome, Priya! with a Logout link
After logout: back to login.jsp
Explanation
The implicit 'session' object is available on every JSP page automatically, so the username set in dologin.jsp is readable in welcome.jsp without extra code.
In simple words: a JSP (JavaServer Page) lets you write HTML and Java in the same file, which is convenient for pages that are mostly display with a little bit of logic. Behind the scenes, Tomcat converts every .jsp file into a servlet the first time it is requested, so a JSP has access to the same request/response/session objects as a servlet, only they are already available as ready-made variables (request, session, application) without you needing to declare them.
Program 56: Preferred theme using cookies JSP
Definition
Form submits chosen theme; JSP sets a cookie and redirects; on later visits the cookie's theme is auto-applied.
Full Program Code
themeform.jsp
<html><body>
<form action="settheme.jsp" method="get">
<select name="theme"><option value="light">Light</option><option value="dark">Dark</option></select>
<input type="submit" value="Save Theme">
</form>
</body></html>
settheme.jsp
<%
javax.servlet.http.Cookie c = new javax.servlet.http.Cookie("theme", request.getParameter("theme"));
c.setMaxAge(30*24*60*60);
response.addCookie(c);
response.sendRedirect("welcometheme.jsp");
%>
welcometheme.jsp
<%
String theme = "light";
javax.servlet.http.Cookie[] cookies = request.getCookies();
if (cookies != null)
for (javax.servlet.http.Cookie c : cookies)
if (c.getName().equals("theme")) theme = c.getValue();
String bg = theme.equals("dark") ? "#222" : "#fff";
String fg = theme.equals("dark") ? "#fff" : "#000";
%>
<html><body style="background:<%= bg %>;color:<%= fg %>;">
<h3>Current theme: <%= theme %></h3>
</body></html>
Expected Output
Current theme: dark (page renders with dark background)
Explanation
The theme cookie is written once and then read on every subsequent visit to automatically restyle the page without asking the user again.
In simple words: a JSP (JavaServer Page) lets you write HTML and Java in the same file, which is convenient for pages that are mostly display with a little bit of logic. Behind the scenes, Tomcat converts every .jsp file into a servlet the first time it is requested, so a JSP has access to the same request/response/session objects as a servlet, only they are already available as ready-made variables (request, session, application) without you needing to declare them.
Program 57: Welcome / Welcome back using cookie (JSP) JSP
Definition
JSP equivalent of program 36: check for a cookie and greet accordingly.
Full Program Code
welcomecookie.jsp
<%
boolean visited = false;
javax.servlet.http.Cookie[] cookies = request.getCookies();
if (cookies != null)
for (javax.servlet.http.Cookie c : cookies)
if (c.getName().equals("seenBefore")) visited = true;
if (!visited) {
javax.servlet.http.Cookie nc = new javax.servlet.http.Cookie("seenBefore", "yes");
nc.setMaxAge(24*60*60);
response.addCookie(nc);
}
%>
<html><body>
<h3><%= visited ? "Welcome back!" : "Welcome!" %></h3>
</body></html>
Expected Output
First visit: Welcome!
Later visits: Welcome back!
Explanation
Scriptlets can use java.util classes and the standard Cookie API directly inside a JSP just like inside a servlet.
In simple words: a JSP (JavaServer Page) lets you write HTML and Java in the same file, which is convenient for pages that are mostly display with a little bit of logic. Behind the scenes, Tomcat converts every .jsp file into a servlet the first time it is requested, so a JSP has access to the same request/response/session objects as a servlet, only they are already available as ready-made variables (request, session, application) without you needing to declare them.
Program 58: Display current date/time using EL JSP
Definition
Use JSTL/EL with a jsp:useBean java.util.Date to display current date-time without scriptlets.
Full Program Code
datetime.jsp
<jsp:useBean id="now" class="java.util.Date" />
<html><body>
<h3>Current Date & Time: ${now}</h3>
</body></html>
Expected Output
Current Date & Time: Tue Jul 14 10:30:00 IST 2026
Explanation
jsp:useBean creates a new java.util.Date() object as a bean, and EL's ${now} calls its toString() automatically to render it.
In simple words: a JSP (JavaServer Page) lets you write HTML and Java in the same file, which is convenient for pages that are mostly display with a little bit of logic. Behind the scenes, Tomcat converts every .jsp file into a servlet the first time it is requested, so a JSP has access to the same request/response/session objects as a servlet, only they are already available as ready-made variables (request, session, application) without you needing to declare them.
Program 59: Pass name via request object across pages using EL JSP
Definition
index.jsp form posts name; a servlet-like forward passes it via request scope to welcome.jsp which displays it with EL.
Full Program Code
index.jsp
<html><body>
<form action="handle.jsp" method="post">
Name: <input name="uname">
<input type="submit" value="Go">
</form>
</body></html>
handle.jsp
<%
request.setAttribute("uname", request.getParameter("uname"));
%>
<jsp:forward page="welcome2.jsp" />
welcome2.jsp
<html><body>
<h3>Welcome, ${uname}!</h3>
</body></html>
Expected Output
Welcome, Priya!
Explanation
request.setAttribute() stores data for the current request only; after a forward, EL automatically looks it up in request scope by name, no getParameter needed.
In simple words: a JSP (JavaServer Page) lets you write HTML and Java in the same file, which is convenient for pages that are mostly display with a little bit of logic. Behind the scenes, Tomcat converts every .jsp file into a servlet the first time it is requested, so a JSP has access to the same request/response/session objects as a servlet, only they are already available as ready-made variables (request, session, application) without you needing to declare them.
Program 60: Arithmetic using Expression Language JSP
Definition
Accept two numbers via form and compute +,-,*,/ purely using EL arithmetic operators.
Full Program Code
elcalc.jsp
<html><body>
<form action="elresult.jsp" method="get">
Num1: <input name="a"><br>
Num2: <input name="b"><br>
<input type="submit" value="Calculate">
</form>
</body></html>
elresult.jsp
<html><body>
Sum: ${param.a + param.b}<br>
Difference: ${param.a - param.b}<br>
Product: ${param.a * param.b}<br>
Division: ${param.a / param.b}
</body></html>
Expected Output
Sum: 15
Difference: 5
Product: 50
Division: 2.0
Explanation
The implicit EL object 'param' exposes request parameters directly, and EL automatically converts numeric strings for arithmetic operators.
In simple words: a JSP (JavaServer Page) lets you write HTML and Java in the same file, which is convenient for pages that are mostly display with a little bit of logic. Behind the scenes, Tomcat converts every .jsp file into a servlet the first time it is requested, so a JSP has access to the same request/response/session objects as a servlet, only they are already available as ready-made variables (request, session, application) without you needing to declare them.
Program 61: Check leap year using JSTL JSP
Definition
Use JSTL <c:if> / <c:choose> instead of scriptlets to check a leap year.
Full Program Code
leapjstl.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html><body>
<form action="leapjstl.jsp" method="get">
Year: <input name="year"><input type="submit" value="Check">
</form>
<c:if test="${not empty param.year}">
<c:set var="y" value="${param.year}" />
<c:choose>
<c:when test="${(y % 4 == 0 and y % 100 != 0) or (y % 400 == 0)}">
<h3>${y} is a Leap Year</h3>
</c:when>
<c:otherwise>
<h3>${y} is not a Leap Year</h3>
</c:otherwise>
</c:choose>
</c:if>
</body></html>
Expected Output
2024 is a Leap Year
Explanation
JSTL's <c:choose>/<c:when>/<c:otherwise> provide if-else branching declaratively in JSP without any Java scriptlet code.
In simple words: a JSP (JavaServer Page) lets you write HTML and Java in the same file, which is convenient for pages that are mostly display with a little bit of logic. Behind the scenes, Tomcat converts every .jsp file into a servlet the first time it is requested, so a JSP has access to the same request/response/session objects as a servlet, only they are already available as ready-made variables (request, session, application) without you needing to declare them.
How to Run (extra steps beyond general setup)
Add jstl-1.2.jar (or jakarta equivalent) to WEB-INF/lib for the JSTL taglib to resolve.
Program 62: Check even/odd using JSTL JSP
Definition
Accept a number and use <c:if> with the modulus operator to test even/odd.
Full Program Code
evenodd.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html><body>
<form method="get">
Number: <input name="num"><input type="submit" value="Check">
</form>
<c:if test="${not empty param.num}">
<c:if test="${param.num % 2 == 0}"><h3>${param.num} is Even</h3></c:if>
<c:if test="${param.num % 2 != 0}"><h3>${param.num} is Odd</h3></c:if>
</c:if>
</body></html>
Expected Output
7 is Odd
Explanation
Two independent <c:if> tags evaluate the modulus condition and its opposite, each rendering only when true.
In simple words: a JSP (JavaServer Page) lets you write HTML and Java in the same file, which is convenient for pages that are mostly display with a little bit of logic. Behind the scenes, Tomcat converts every .jsp file into a servlet the first time it is requested, so a JSP has access to the same request/response/session objects as a servlet, only they are already available as ready-made variables (request, session, application) without you needing to declare them.
Program 63: Print primes from 1 to 100 using JSTL JSP
Definition
Use nested <c:forEach> loops with a boolean flag to test primality for each number 1-100.
Full Program Code
primes.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html><body>
<h3>Prime numbers from 1 to 100:</h3>
<c:forEach var="i" begin="2" end="100">
<c:set var="isPrime" value="true" />
<c:forEach var="j" begin="2" end="${i - 1}">
<c:if test="${i % j == 0}"><c:set var="isPrime" value="false" /></c:if>
</c:forEach>
<c:if test="${isPrime}">${i} </c:if>
</c:forEach>
</body></html>
Expected Output
2 3 5 7 11 13 17 19 23 ... 97
Explanation
The outer <c:forEach> walks each candidate number; the inner loop tests divisibility by every smaller number, flipping the isPrime flag off on any exact division.
In simple words: a JSP (JavaServer Page) lets you write HTML and Java in the same file, which is convenient for pages that are mostly display with a little bit of logic. Behind the scenes, Tomcat converts every .jsp file into a servlet the first time it is requested, so a JSP has access to the same request/response/session objects as a servlet, only they are already available as ready-made variables (request, session, application) without you needing to declare them.
Program 64: Divisible by 2 check using JSTL JSP
Definition
Accept a number and display whether it is divisible by 2 using JSTL c:if.
Full Program Code
divby2.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html><body>
<form method="get">
Number: <input name="num"><input type="submit" value="Check">
</form>
<c:if test="${not empty param.num}">
<c:choose>
<c:when test="${param.num % 2 == 0}"><h3>${param.num} is divisible by 2</h3></c:when>
<c:otherwise><h3>${param.num} is NOT divisible by 2</h3></c:otherwise>
</c:choose>
</c:if>
</body></html>
Expected Output
10 is divisible by 2
Explanation
Same modulus-based technique as program 62, phrased as a divisibility check rather than even/odd labeling.
In simple words: a JSP (JavaServer Page) lets you write HTML and Java in the same file, which is convenient for pages that are mostly display with a little bit of logic. Behind the scenes, Tomcat converts every .jsp file into a servlet the first time it is requested, so a JSP has access to the same request/response/session objects as a servlet, only they are already available as ready-made variables (request, session, application) without you needing to declare them.
Program 65: Servlet + JSP MVC: accept username, welcome via JSP MVC
Definition
Use a Servlet as Controller to accept a username and forward to a JSP View that welcomes the user, keeping input handling and presentation separate.
Full Program Code
loginform.html
<form action="ctrl" method="post">
Username: <input name="uname">
<input type="submit" value="Submit">
</form>
ControllerServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
@WebServlet("/ctrl")
public class ControllerServlet extends HttpServlet {
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String uname = req.getParameter("uname");
req.setAttribute("uname", uname);
RequestDispatcher rd = req.getRequestDispatcher("welcomeview.jsp");
rd.forward(req, res);
}
}
welcomeview.jsp
<html><body>
<h3>Welcome, ${uname}!</h3>
</body></html>
Expected Output
Welcome, Alpesh!
Explanation
The Servlet (Controller) never generates HTML itself; it only processes input and forwards the request to a JSP (View) using RequestDispatcher, which renders the response.
In simple words: MVC (Model-View-Controller) is just a way of not mixing everything into one file. The Model (a DAO/Bean class) is the only part allowed to talk to the database. The View (a JSP page) is the only part allowed to produce HTML. The Controller (a Servlet) sits in the middle: it reads what the user submitted, calls the Model to fetch or save data, and then uses RequestDispatcher.forward() to hand control to the correct View. This separation is exactly why real-world Java web projects are organized this way — it keeps each file focused on one job and easy to change later.
Program 66: Login using MVC with two separate views MVC
Definition
Servlet controller checks hardcoded admin/admin credentials and forwards to either a success JSP view or a failure JSP view.
Full Program Code
loginmvc.html
<form action="loginctrl" method="post">
Username: <input name="uname"><br>
Password: <input type="password" name="pwd"><br>
<input type="submit" value="Login">
</form>
LoginControllerServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
@WebServlet("/loginctrl")
public class LoginControllerServlet extends HttpServlet {
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String u = req.getParameter("uname");
String p = req.getParameter("pwd");
String target = ("admin".equals(u) && "admin".equals(p)) ? "success.jsp" : "failure.jsp";
req.setAttribute("uname", u);
req.getRequestDispatcher(target).forward(req, res);
}
}
success.jsp
<html><body><h3>Welcome, ${uname}! Login successful.</h3></body></html>
failure.jsp
<html><body><h3>Incorrect username or password.</h3></body></html>
Expected Output
Correct credentials: Welcome, admin! Login successful.
Wrong credentials: Incorrect username or password.
Explanation
The controller alone decides business logic (credential check); it never mixes HTML into the servlet — each outcome has its own dedicated JSP view.
In simple words: MVC (Model-View-Controller) is just a way of not mixing everything into one file. The Model (a DAO/Bean class) is the only part allowed to talk to the database. The View (a JSP page) is the only part allowed to produce HTML. The Controller (a Servlet) sits in the middle: it reads what the user submitted, calls the Model to fetch or save data, and then uses RequestDispatcher.forward() to hand control to the correct View. This separation is exactly why real-world Java web projects are organized this way — it keeps each file focused on one job and easy to change later.
Program 67: Login fetching credentials from database (MVC, 2 views) MVC
Definition
Model layer (DAO) queries a Login table (username, password) via JDBC; Controller uses the DAO result to forward to success or failure view.
Full Program Code
login_table.sql
CREATE TABLE Login(username VARCHAR(30) PRIMARY KEY, password VARCHAR(30));
LoginDAO.java
import java.sql.*;
public class LoginDAO {
public static boolean validate(String u, String p) throws SQLException {
try (Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/college", "root", "root");
PreparedStatement ps = con.prepareStatement(
"SELECT * FROM Login WHERE username=? AND password=?")) {
ps.setString(1, u); ps.setString(2, p);
try (ResultSet rs = ps.executeQuery()) {
return rs.next();
}
}
}
}
DbLoginServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
@WebServlet("/dblogin")
public class DbLoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String u = req.getParameter("uname");
String p = req.getParameter("pwd");
String target;
try {
target = LoginDAO.validate(u, p) ? "dbsuccess.jsp" : "dbfailure.jsp";
} catch (SQLException e) {
throw new ServletException(e);
}
req.setAttribute("uname", u);
req.getRequestDispatcher(target).forward(req, res);
}
}
dbsuccess.jsp
<html><body><h3>Welcome, ${uname}!</h3></body></html>
dbfailure.jsp
<html><body><h3>Incorrect username or password.</h3></body></html>
Expected Output
Matching row in Login table: Welcome, admin!
No match: Incorrect username or password.
Explanation
LoginDAO is the Model — it isolates all database access; the Controller servlet never writes SQL itself, only calls the DAO and picks a view based on the boolean result.
In simple words: MVC (Model-View-Controller) is just a way of not mixing everything into one file. The Model (a DAO/Bean class) is the only part allowed to talk to the database. The View (a JSP page) is the only part allowed to produce HTML. The Controller (a Servlet) sits in the middle: it reads what the user submitted, calls the Model to fetch or save data, and then uses RequestDispatcher.forward() to hand control to the correct View. This separation is exactly why real-world Java web projects are organized this way — it keeps each file focused on one job and easy to change later.
Program 68: Registration module with JSP, Servlet, MVC and database MVC
Definition
Collect Username, Password, Mobile via a JSP form; a Servlet controller inserts them into a User table via a DAO (Model) on submission.
Full Program Code
user_table.sql
CREATE TABLE User(username VARCHAR(30) PRIMARY KEY, password VARCHAR(30), mobile VARCHAR(15));
regform2.jsp
<html><body>
<form action="regctrl" method="post">
Username: <input name="uname"><br>
Password: <input name="pwd"><br>
Mobile: <input name="mobile"><br>
<input type="submit" value="Register">
</form>
</body></html>
UserDAO.java
import java.sql.*;
public class UserDAO {
public static int insert(String u, String p, String m) throws SQLException {
try (Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/college", "root", "root");
PreparedStatement ps = con.prepareStatement(
"INSERT INTO User VALUES(?,?,?)")) {
ps.setString(1, u); ps.setString(2, p); ps.setString(3, m);
return ps.executeUpdate();
}
}
}
RegisterControllerServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
@WebServlet("/regctrl")
public class RegisterControllerServlet extends HttpServlet {
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String u = req.getParameter("uname");
String p = req.getParameter("pwd");
String m = req.getParameter("mobile");
try {
UserDAO.insert(u, p, m);
} catch (SQLException e) {
throw new ServletException(e);
}
req.setAttribute("uname", u);
req.getRequestDispatcher("regsuccess.jsp").forward(req, res);
}
}
regsuccess.jsp
<html><body><h3>Registration successful for ${uname}!</h3></body></html>
Expected Output
Registration successful for Priya!
Explanation
The JSP form is the View for input, UserDAO is the Model handling persistence, and RegisterControllerServlet is the Controller coordinating them — the classic three-layer MVC split.
In simple words: MVC (Model-View-Controller) is just a way of not mixing everything into one file. The Model (a DAO/Bean class) is the only part allowed to talk to the database. The View (a JSP page) is the only part allowed to produce HTML. The Controller (a Servlet) sits in the middle: it reads what the user submitted, calls the Model to fetch or save data, and then uses RequestDispatcher.forward() to hand control to the correct View. This separation is exactly why real-world Java web projects are organized this way — it keeps each file focused on one job and easy to change later.
Program 69: List students by course and semester (Servlet + Model + JSP) MVC
Definition
User submits course and semester; Servlet calls a Model method to query the Student table; JSP View renders the returned list.
Full Program Code
studlistform.html
<form action="studlist" method="get">
Course: <input name="course"><br>
Semester: <input name="semester"><br>
<input type="submit" value="View List">
</form>
StudentDAO.java
import java.sql.*;
import java.util.*;
public class StudentDAO {
public static List<String[]> getByCourseSem(String course, int sem) throws SQLException {
List<String[]> list = new ArrayList<>();
try (Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/college", "root", "root");
PreparedStatement ps = con.prepareStatement(
"SELECT rollno, firstname, lastname FROM stud WHERE course=? AND semester=?")) {
ps.setString(1, course); ps.setInt(2, sem);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next())
list.add(new String[]{ rs.getString(1), rs.getString(2), rs.getString(3) });
}
}
return list;
}
}
StudentListServlet.java
import java.io.*;
import java.util.List;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
@WebServlet("/studlist")
public class StudentListServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String course = req.getParameter("course");
int sem = Integer.parseInt(req.getParameter("semester"));
try {
List<String[]> list = StudentDAO.getByCourseSem(course, sem);
req.setAttribute("studentList", list);
} catch (SQLException e) {
throw new ServletException(e);
}
req.getRequestDispatcher("studlistview.jsp").forward(req, res);
}
}
studlistview.jsp
<%@ page import="java.util.*" %>
<html><body>
<h3>Student List</h3>
<c:forEach xmlns:c="http://java.sun.com/jsp/jstl/core" var="s" items="${studentList}">
${s[0]} - ${s[1]} ${s[2]}<br>
</c:forEach>
</body></html>
Expected Output
Student List
1 - Priya Mehta
3 - Nidhi Joshi
Explanation
The list built by the Model (StudentDAO) is placed into request scope by the Controller and iterated directly by the View using JSTL forEach, keeping SQL entirely out of the JSP.
In simple words: MVC (Model-View-Controller) is just a way of not mixing everything into one file. The Model (a DAO/Bean class) is the only part allowed to talk to the database. The View (a JSP page) is the only part allowed to produce HTML. The Controller (a Servlet) sits in the middle: it reads what the user submitted, calls the Model to fetch or save data, and then uses RequestDispatcher.forward() to hand control to the correct View. This separation is exactly why real-world Java web projects are organized this way — it keeps each file focused on one job and easy to change later.
Program 70: Contact Management System (add + list) using MVC MVC
Definition
Model manages contact data storage, View has an add-contact form and a listing page, Controller processes the form and updates the model.
Full Program Code
contact_table.sql
CREATE TABLE contact(id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50), phone VARCHAR(15));
ContactDAO.java
import java.sql.*;
import java.util.*;
public class ContactDAO {
public static void add(String name, String phone) throws SQLException {
try (Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/college", "root", "root");
PreparedStatement ps = con.prepareStatement(
"INSERT INTO contact(name, phone) VALUES(?,?)")) {
ps.setString(1, name); ps.setString(2, phone);
ps.executeUpdate();
}
}
public static List<String[]> getAll() throws SQLException {
List<String[]> list = new ArrayList<>();
try (Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/college", "root", "root");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT name, phone FROM contact")) {
while (rs.next())
list.add(new String[]{ rs.getString(1), rs.getString(2) });
}
return list;
}
}
ContactServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
@WebServlet("/contact")
public class ContactServlet extends HttpServlet {
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
try {
ContactDAO.add(req.getParameter("name"), req.getParameter("phone"));
req.setAttribute("contacts", ContactDAO.getAll());
} catch (SQLException e) {
throw new ServletException(e);
}
req.getRequestDispatcher("contactlist.jsp").forward(req, res);
}
}
contactform.html
<form action="contact" method="post">
Name: <input name="name"><br>
Phone: <input name="phone"><br>
<input type="submit" value="Add Contact">
</form>
contactlist.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html><body>
<h3>All Contacts</h3>
<c:forEach var="c" items="${contacts}">${c[0]} - ${c[1]}<br></c:forEach>
</body></html>
Expected Output
All Contacts
Priya - 9998887771
Ravi - 9998887772
Explanation
ContactDAO (Model) fully owns data access, ContactServlet (Controller) receives the form submission and coordinates adding + reloading data, and contactlist.jsp (View) only displays what it is given.
In simple words: MVC (Model-View-Controller) is just a way of not mixing everything into one file. The Model (a DAO/Bean class) is the only part allowed to talk to the database. The View (a JSP page) is the only part allowed to produce HTML. The Controller (a Servlet) sits in the middle: it reads what the user submitted, calls the Model to fetch or save data, and then uses RequestDispatcher.forward() to hand control to the correct View. This separation is exactly why real-world Java web projects are organized this way — it keeps each file focused on one job and easy to change later.
Program 71: MVC insert/display employee via Servlet, JSP, JavaBean MVC
Definition
An EmployeeBean carries data between layers; a Servlet inserts a new emp row and forwards to a JSP that lists all employees.
Full Program Code
EmpBean2.java
public class EmpBean2 {
private int empno;
private String empnm, designation, dept;
public int getEmpno() { return empno; }
public void setEmpno(int empno) { this.empno = empno; }
public String getEmpnm() { return empnm; }
public void setEmpnm(String empnm) { this.empnm = empnm; }
public String getDesignation() { return designation; }
public void setDesignation(String designation) { this.designation = designation; }
public String getDept() { return dept; }
public void setDept(String dept) { this.dept = dept; }
}
empmvcform.html
<form action="empmvc" method="post">
Emp No: <input name="empno"><br>
Name: <input name="empnm"><br>
Designation: <input name="designation"><br>
Dept: <input name="dept"><br>
<input type="submit" value="Save">
</form>
EmpMvcServlet.java
import java.io.*;
import java.sql.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
@WebServlet("/empmvc")
public class EmpMvcServlet extends HttpServlet {
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
EmpBean2 bean = new EmpBean2();
bean.setEmpno(Integer.parseInt(req.getParameter("empno")));
bean.setEmpnm(req.getParameter("empnm"));
bean.setDesignation(req.getParameter("designation"));
bean.setDept(req.getParameter("dept"));
try (Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/college", "root", "root");
PreparedStatement ps = con.prepareStatement(
"INSERT INTO emp(empno,empnm,designation,department) VALUES(?,?,?,?)")) {
ps.setInt(1, bean.getEmpno());
ps.setString(2, bean.getEmpnm());
ps.setString(3, bean.getDesignation());
ps.setString(4, bean.getDept());
ps.executeUpdate();
} catch (SQLException e) {
throw new ServletException(e);
}
req.getRequestDispatcher("emplist.jsp").forward(req, res);
}
}
emplist.jsp
<%@ page import="java.sql.*" %>
<html><body>
<h3>All Employees</h3>
<%
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/college", "root", "root");
ResultSet rs = con.createStatement().executeQuery("SELECT empno, empnm, designation, department FROM emp");
while (rs.next()) {
%>
<%= rs.getInt(1) %> - <%= rs.getString(2) %> - <%= rs.getString(3) %> - <%= rs.getString(4) %><br>
<%
}
con.close();
%>
</body></html>
Expected Output
All Employees
101 - Ramesh Patel - Manager - Sales
201 - Kiran Desai - Developer - IT
Explanation
EmpBean2 is a plain JavaBean carrying form data cleanly from the servlet to the persistence code, which is a common lightweight pattern before introducing a full DAO layer.
In simple words: MVC (Model-View-Controller) is just a way of not mixing everything into one file. The Model (a DAO/Bean class) is the only part allowed to talk to the database. The View (a JSP page) is the only part allowed to produce HTML. The Controller (a Servlet) sits in the middle: it reads what the user submitted, calls the Model to fetch or save data, and then uses RequestDispatcher.forward() to hand control to the correct View. This separation is exactly why real-world Java web projects are organized this way — it keeps each file focused on one job and easy to change later.
Program 72: Full CRUD student management using MVC (Servlet + JSP + Bean) MVC
Definition
A complete MVC application on the studnt table (rollno, name, course, semester): separate JSP views for add, list, edit and delete, driven by one controller servlet with an 'action' parameter.
Full Program Code
studnt_table.sql
CREATE TABLE studnt(rollno INT PRIMARY KEY, name VARCHAR(50), course VARCHAR(30), semester INT);
StudntDAO.java
import java.sql.*;
import java.util.*;
public class StudntDAO {
static final String URL = "jdbc:mysql://localhost:3306/college", USER = "root", PASS = "root";
public static void add(int r, String n, String c, int s) throws SQLException {
try (Connection con = DriverManager.getConnection(URL, USER, PASS);
PreparedStatement ps = con.prepareStatement("INSERT INTO studnt VALUES(?,?,?,?)")) {
ps.setInt(1, r); ps.setString(2, n); ps.setString(3, c); ps.setInt(4, s);
ps.executeUpdate();
}
}
public static void update(int r, String n, String c, int s) throws SQLException {
try (Connection con = DriverManager.getConnection(URL, USER, PASS);
PreparedStatement ps = con.prepareStatement(
"UPDATE studnt SET name=?, course=?, semester=? WHERE rollno=?")) {
ps.setString(1, n); ps.setString(2, c); ps.setInt(3, s); ps.setInt(4, r);
ps.executeUpdate();
}
}
public static void delete(int r) throws SQLException {
try (Connection con = DriverManager.getConnection(URL, USER, PASS);
PreparedStatement ps = con.prepareStatement("DELETE FROM studnt WHERE rollno=?")) {
ps.setInt(1, r);
ps.executeUpdate();
}
}
public static List<String[]> getAll() throws SQLException {
List<String[]> list = new ArrayList<>();
try (Connection con = DriverManager.getConnection(URL, USER, PASS);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM studnt")) {
while (rs.next())
list.add(new String[]{ rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4) });
}
return list;
}
}
StudntControllerServlet.java
import java.io.*;
import java.sql.SQLException;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
@WebServlet("/studnt")
public class StudntControllerServlet extends HttpServlet {
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String action = req.getParameter("action");
try {
switch (action) {
case "add":
StudntDAO.add(Integer.parseInt(req.getParameter("rollno")),
req.getParameter("name"), req.getParameter("course"),
Integer.parseInt(req.getParameter("semester")));
break;
case "update":
StudntDAO.update(Integer.parseInt(req.getParameter("rollno")),
req.getParameter("name"), req.getParameter("course"),
Integer.parseInt(req.getParameter("semester")));
break;
case "delete":
StudntDAO.delete(Integer.parseInt(req.getParameter("rollno")));
break;
}
req.setAttribute("students", StudntDAO.getAll());
} catch (SQLException e) {
throw new ServletException(e);
}
req.getRequestDispatcher("studntlist.jsp").forward(req, res);
}
}
studntform.jsp
<html><body>
<h3>Add / Update Student</h3>
<form action="studnt" method="post">
Roll No: <input name="rollno"><br>
Name: <input name="name"><br>
Course: <input name="course"><br>
Semester: <input name="semester"><br>
<input type="hidden" name="action" value="add">
<input type="submit" value="Save">
</form>
</body></html>
studntlist.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html><body>
<h3>Student Records</h3>
<c:forEach var="s" items="${students}">
${s[0]} - ${s[1]} - ${s[2]} - Sem ${s[3]}
<form action="studnt" method="post" style="display:inline">
<input type="hidden" name="rollno" value="${s[0]}">
<input type="hidden" name="action" value="delete">
<input type="submit" value="Delete">
</form><br>
</c:forEach>
</body></html>
Expected Output
Student Records
1 - Priya - BCA - Sem 5 [Delete]
2 - Ravi - BCA - Sem 5 [Delete]
Explanation
A single controller servlet routes to add/update/delete logic in StudntDAO based on the 'action' parameter, and always redisplays the refreshed list through one shared JSP view, which is the standard front-controller flavor of MVC.
In simple words: MVC (Model-View-Controller) is just a way of not mixing everything into one file. The Model (a DAO/Bean class) is the only part allowed to talk to the database. The View (a JSP page) is the only part allowed to produce HTML. The Controller (a Servlet) sits in the middle: it reads what the user submitted, calls the Model to fetch or save data, and then uses RequestDispatcher.forward() to hand control to the correct View. This separation is exactly why real-world Java web projects are organized this way — it keeps each file focused on one job and easy to change later.
Program 73: Hibernate Student entity: save and retrieve Hibernate
Definition
Map a Student entity (rollno, name, course, semester) with Hibernate annotations, save one record with a Session, then load and print it.
Full Program Code
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/college</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="show_sql">true</property>
<mapping class="Student"/>
</session-factory>
</hibernate-configuration>
Student.java
import javax.persistence.*;
@Entity
@Table(name = "hib_student")
public class Student {
@Id
private int rollno;
private String name, course;
private int semester;
public Student() {}
public Student(int rollno, String name, String course, int semester) {
this.rollno = rollno; this.name = name; this.course = course; this.semester = semester;
}
public int getRollno() { return rollno; }
public String getName() { return name; }
public String getCourse() { return course; }
public int getSemester() { return semester; }
public String toString() {
return rollno + " - " + name + " - " + course + " - Sem " + semester;
}
}
HibernateStudentApp.java
import org.hibernate.*;
import org.hibernate.cfg.Configuration;
public class HibernateStudentApp {
public static void main(String[] args) {
SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session session = sf.openSession();
Transaction tx = session.beginTransaction();
Student s = new Student(1, "Priya Mehta", "BCA", 5);
session.save(s);
tx.commit();
session.close();
Session session2 = sf.openSession();
Student loaded = session2.get(Student.class, 1);
System.out.println("Loaded: " + loaded);
session2.close();
sf.close();
}
}
Expected Output
Loaded: 1 - Priya Mehta - BCA - Sem 5
Explanation
Configuration().configure() reads hibernate.cfg.xml to build a SessionFactory; session.save() inside a Transaction persists the object, and session.get() retrieves it back by primary key without writing any SQL.
In simple words: Hibernate is an ORM (Object-Relational Mapping) tool, meaning you work with normal Java objects (like a Student object) and Hibernate quietly writes the SQL for you. @Entity marks a class as mapped to a table, @Id marks its primary key field, a Session is Hibernate's version of a database connection, and session.save() / session.get() replace the INSERT/SELECT SQL you would otherwise have written by hand in plain JDBC.
How to Run (extra steps beyond general setup)
Add hibernate-core, mysql-connector-j and javax.persistence-api jars (or Maven dependencies) to the project before running.
Program 74: Hibernate Employee entity: insert and list all Hibernate
Definition
Map an Employee entity (empno, empnm, department) with Hibernate, insert one record, then use a Query to list all employees.
Full Program Code
Employee.java
import javax.persistence.*;
@Entity
@Table(name = "hib_employee")
public class Employee {
@Id
private int empno;
private String empnm, department;
public Employee() {}
public Employee(int empno, String empnm, String department) {
this.empno = empno; this.empnm = empnm; this.department = department;
}
public int getEmpno() { return empno; }
public String getEmpnm() { return empnm; }
public String getDepartment() { return department; }
public String toString() { return empno + " - " + empnm + " - " + department; }
}
HibernateEmployeeApp.java
import org.hibernate.*;
import org.hibernate.cfg.Configuration;
import java.util.List;
public class HibernateEmployeeApp {
public static void main(String[] args) {
SessionFactory sf = new Configuration().configure().addAnnotatedClass(Employee.class)
.buildSessionFactory();
Session session = sf.openSession();
Transaction tx = session.beginTransaction();
session.save(new Employee(301, "Kiran Desai", "IT"));
tx.commit();
session.close();
Session s2 = sf.openSession();
List<Employee> list = s2.createQuery("from Employee", Employee.class).list();
for (Employee e : list) System.out.println(e);
s2.close();
sf.close();
}
}
Expected Output
301 - Kiran Desai - IT
Explanation
createQuery("from Employee") is HQL — it operates on the entity class and its fields rather than the underlying table/columns directly, and .list() returns fully populated Employee objects.
In simple words: Hibernate is an ORM (Object-Relational Mapping) tool, meaning you work with normal Java objects (like a Student object) and Hibernate quietly writes the SQL for you. @Entity marks a class as mapped to a table, @Id marks its primary key field, a Session is Hibernate's version of a database connection, and session.save() / session.get() replace the INSERT/SELECT SQL you would otherwise have written by hand in plain JDBC.
Program 75: Hibernate Product entity with HQL listing Hibernate
Definition
Map a Product entity (id, name, price) and use HQL to fetch and display all products.
Full Program Code
Product.java
import javax.persistence.*;
@Entity
@Table(name = "hib_product")
public class Product {
@Id
private int id;
private String name;
private double price;
public Product() {}
public Product(int id, String name, double price) {
this.id = id; this.name = name; this.price = price;
}
public int getId() { return id; }
public String getName() { return name; }
public double getPrice() { return price; }
}
HibernateProductApp.java
import org.hibernate.*;
import org.hibernate.cfg.Configuration;
import java.util.List;
public class HibernateProductApp {
public static void main(String[] args) {
SessionFactory sf = new Configuration().configure().addAnnotatedClass(Product.class)
.buildSessionFactory();
Session session = sf.openSession();
Transaction tx = session.beginTransaction();
session.save(new Product(1, "Notebook", 45.0));
session.save(new Product(2, "Pen", 10.0));
tx.commit();
session.close();
Session s2 = sf.openSession();
List<Product> products = s2.createQuery("SELECT p FROM Product p", Product.class).list();
for (Product p : products)
System.out.println(p.getId() + " - " + p.getName() + " - " + p.getPrice());
s2.close();
sf.close();
}
}
Expected Output
1 - Notebook - 45.0
2 - Pen - 10.0
Explanation
HQL's "SELECT p FROM Product p" is the object-oriented equivalent of "SELECT * FROM hib_product"; Hibernate translates it into the actual SQL dialect configured in hibernate.cfg.xml.
In simple words: Hibernate is an ORM (Object-Relational Mapping) tool, meaning you work with normal Java objects (like a Student object) and Hibernate quietly writes the SQL for you. @Entity marks a class as mapped to a table, @Id marks its primary key field, a Session is Hibernate's version of a database connection, and session.save() / session.get() replace the INSERT/SELECT SQL you would otherwise have written by hand in plain JDBC.
Program 76: Spring MVC login application Spring
Definition
Build a login application using Spring MVC: a LoginController maps GET/POST requests, and Thymeleaf templates provide the login form, success page, and failure page.
Full Program Code
pom.xml
<dependencies>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency>
</dependencies>
LoginController.java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.ui.Model;
@Controller
public class LoginController {
@GetMapping("/login")
public String loginForm() {
return "login"; // templates/login.html
}
@PostMapping("/login")
public String doLogin(@RequestParam String username, @RequestParam String password, Model model) {
if ("admin".equals(username) && "admin".equals(password)) {
model.addAttribute("username", username);
return "success"; // templates/success.html
}
return "failure"; // templates/failure.html
}
}
login.html
<html xmlns:th="http://www.thymeleaf.org"><body>
<form th:action="@{/login}" method="post">
Username: <input name="username"><br>
Password: <input type="password" name="password"><br>
<button type="submit">Login</button>
</form>
</body></html>
success.html
<html xmlns:th="http://www.thymeleaf.org"><body>
<h3>Welcome, <span th:text="${username}"></span>! Login successful.</h3>
</body></html>
failure.html
<html><body><h3>Invalid username or password.</h3></body></html>
Expected Output
Welcome, admin! Login successful. (on correct credentials)
Explanation
@Controller marks the class as a Spring MVC controller, @GetMapping/@PostMapping route requests by URL and HTTP method, and returning a String selects which Thymeleaf template under templates/ is rendered as the view.
In simple words: Spring Boot removes most of the manual setup Java web development usually needs (no web.xml, no manually starting Tomcat). @RestController or @Controller marks a class whose methods handle web requests, @GetMapping/@PostMapping/etc. decide which URL and HTTP verb calls which method, and (when using Spring Data JPA) a JpaRepository interface gives you working save/find/delete database methods without writing any SQL or implementation code at all.
How to Run (extra steps beyond general setup)
Generate the project from start.spring.io with 'Spring Web' and 'Thymeleaf' dependencies, import as a Maven project, and run the *Application.java main class.
Program 77: Spring Boot + Spring Data JPA: insert and display employee Spring
Definition
An Employee JPA entity, a Spring Data JpaRepository, and a Controller together insert a new employee and list all employees, with Spring Boot handling the setup.
Full Program Code
Employee2.java
import javax.persistence.*;
@Entity
public class Employee2 {
@Id
private int empno;
private String empnm, designation, dept;
public Employee2() {}
public Employee2(int empno, String empnm, String designation, String dept) {
this.empno = empno; this.empnm = empnm; this.designation = designation; this.dept = dept;
}
public int getEmpno() { return empno; }
public String getEmpnm() { return empnm; }
public String getDesignation() { return designation; }
public String getDept() { return dept; }
}
EmployeeRepository.java
import org.springframework.data.jpa.repository.JpaRepository;
public interface EmployeeRepository extends JpaRepository<Employee2, Integer> {
}
EmployeeController.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
public class EmployeeController {
@Autowired
private EmployeeRepository repo;
@PostMapping("/employees")
public Employee2 add(@RequestBody Employee2 emp) {
return repo.save(emp);
}
@GetMapping("/employees")
public List<Employee2> getAll() {
return repo.findAll();
}
}
application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/college
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
Expected Output
POST /employees {"empno":401,"empnm":"Nidhi Joshi","designation":"Analyst","dept":"IT"} -> 200 OK with the saved JSON
GET /employees -> [{"empno":401,"empnm":"Nidhi Joshi",...}]
Explanation
JpaRepository already provides save(), findAll(), findById(), delete() etc. without any implementation code; @RestController + @RequestBody/@PostMapping wire JSON HTTP requests directly to those repository calls.
In simple words: Spring Boot removes most of the manual setup Java web development usually needs (no web.xml, no manually starting Tomcat). @RestController or @Controller marks a class whose methods handle web requests, @GetMapping/@PostMapping/etc. decide which URL and HTTP verb calls which method, and (when using Spring Data JPA) a JpaRepository interface gives you working save/find/delete database methods without writing any SQL or implementation code at all.
How to Run (extra steps beyond general setup)
Generate the project from start.spring.io with 'Spring Web', 'Spring Data JPA' and 'MySQL Driver'; test endpoints with Postman or curl, e.g. curl http://localhost:8080/employees.
Program 78: Spring Boot + Spring Data JPA CRUD on Student table Spring
Definition
A Student JPA entity (rollno, name, course, semester) with a full CRUD REST controller (create, read, update, delete) backed by JpaRepository.
Full Program Code
Student2.java
import javax.persistence.*;
@Entity
public class Student2 {
@Id
private int rollno;
private String name, course;
private int semester;
public Student2() {}
public Student2(int rollno, String name, String course, int semester) {
this.rollno = rollno; this.name = name; this.course = course; this.semester = semester;
}
public int getRollno() { return rollno; }
public void setRollno(int rollno) { this.rollno = rollno; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getCourse() { return course; }
public void setCourse(String course) { this.course = course; }
public int getSemester() { return semester; }
public void setSemester(int semester) { this.semester = semester; }
}
Student2Repository.java
import org.springframework.data.jpa.repository.JpaRepository;
public interface Student2Repository extends JpaRepository<Student2, Integer> {
}
Student2Controller.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/students")
public class Student2Controller {
@Autowired
private Student2Repository repo;
@PostMapping
public Student2 create(@RequestBody Student2 s) { return repo.save(s); }
@GetMapping
public List<Student2> getAll() { return repo.findAll(); }
@GetMapping("/{rollno}")
public Student2 getOne(@PathVariable int rollno) { return repo.findById(rollno).orElse(null); }
@PutMapping("/{rollno}")
public Student2 update(@PathVariable int rollno, @RequestBody Student2 s) {
s.setRollno(rollno);
return repo.save(s);
}
@DeleteMapping("/{rollno}")
public void delete(@PathVariable int rollno) { repo.deleteById(rollno); }
}
Expected Output
POST /students {...} -> 200 OK
GET /students -> [ list of students ]
PUT /students/1 {...} -> updated record
DELETE /students/1 -> record removed
Explanation
Each HTTP verb maps to one CRUD operation: POST->save (create), GET->findAll/findById (read), PUT->save with an existing id (update), DELETE->deleteById (delete) — Spring Data JPA implements all of this from the interface alone, no SQL or DAO code required.
In simple words: Spring Boot removes most of the manual setup Java web development usually needs (no web.xml, no manually starting Tomcat). @RestController or @Controller marks a class whose methods handle web requests, @GetMapping/@PostMapping/etc. decide which URL and HTTP verb calls which method, and (when using Spring Data JPA) a JpaRepository interface gives you working save/find/delete database methods without writing any SQL or implementation code at all.