0% found this document useful (0 votes)
4 views196 pages

Java Journal

The document outlines a curriculum for a Web Development with Java Lab course for Semester II, including practical assignments across various units such as Java Database Connectivity, Java Servlets, Java Server Pages, Spring Boot, and ReactJS. Each unit contains specific programming tasks with deadlines, focusing on different aspects of web development and database management. The document also includes example code for a menu-driven Employee Management application utilizing JDBC for database operations.

Uploaded by

khatuasoumen77
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views196 pages

Java Journal

The document outlines a curriculum for a Web Development with Java Lab course for Semester II, including practical assignments across various units such as Java Database Connectivity, Java Servlets, Java Server Pages, Spring Boot, and ReactJS. Each unit contains specific programming tasks with deadlines, focusing on different aspects of web development and database management. The document also includes example code for a menu-driven Employee Management application utilizing JDBC for database operations.

Uploaded by

khatuasoumen77
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

INDEX

Semester II - Web Development with Java Lab (2025-26)

No. Program Name Date Sign /


Remark

Unit I - Java Database Connectivity 02/02/2026

Q1 Write a program to create a menu driven program using Statements. 02/02/2026

Q2 Write a program to create a menu driven program using Prepared statements. 06/02/2026

Q3 Write a program to demonstrate the callable statements. 09/02/2026

Q4 Write a program to demonstrate the resultSet readonly and Updateable.

Unit II - Java Servlets

Q1 Write a program to display date, time and number of requests (count) using Generic 11/02/2026
and HTTP servlet life cycle.

Q2 Write a program to show servlet config and context with student information. 11/02/2026

Q3 Write a program to add 2 numbers using get parameter. 11/02/2026

Q4 Write a program to make a calculator using doGet method. 16/02/2026

Q5 Write a program to create login page email and password using doGet() and redirect 16/02/2026
page to welcome page containing Welcome username entered.

Q6 Write a program to show HTTP request and HTTP response methods. 16/02/2026

Q7 Write a program to print 1 to 10 lucky number from 1 to 100 random number. 23/02/2026

Q8 Write a program to create a login page to store information using cookie. 23/02/2026

Q9 Write a program to create a login form using request dispatcher method like include 23/02/2026
and forward to print appropriate messages like Welcome username, if login id or
password is incorrect, redirect to login page with appropriate error message.

Q10 Write a program to create a login form using send redirect method to print 27/02/2026
appropriate messages like Welcome username, if login id or password is incorrect,
redirect to login page with appropriate error message.

Q11 Write a program to create login form using request dispatcher method like include 27/02/2026
and forward & using database to print appropriate messages like Welcome username,
if login id or password is incorrect redirect to login page with appropriate error
message.
Q12 Write a program to create a login form & print message using HTTP session 27/02/2026
interface.

Unit III - Java Server Pages (JSP)

Q1 Write a program to make a calculator (ADD, SUBTRACT, MULTIPLY, DIVIDE) 09/03/2026


using JSP.

Q2 Write a program to calculate the factorial of a given number using JSP. 09/03/2026

Q3 Write a program to reverse the string using JSP. 16/03/2026

Q4 Write a program to create a JSP snippet using four scripting elements (scriplet). 16/03/2026

Q5 Write a program to create a JSP code using the include tag. 23/03/2026

Q6 Write a program to print ArrayIndexOutOfBound, ArithmaticException, 23/03/2026


NullPointerException using isError Page & errorPage.

Q7 Write a program in JSP code to use all page Directive attributes. 27/03/2026

Q8 Write a program in JSP to perform session tracking using Cookies. 27/03/2026

Q9 Write a program in JSP to perform session tracking using HttpSession. 27/03/2026

Q10 Write a program in JSP to perform login functionality if login is correctly redirected 30/03/2026
to another page with message Welcome User otherwise revert back to login page
again using database.

Q11 Write a program in JSP to perform Crud operation on emp(eid, ename, sal, dept) 30/03/2026
with help of MySql database.

Unit IV - Spring Boot and RESTful Web Services,


Unit V - Data Persistence, Transactions, and Testing

Q1 Write a program to implement Inversion of Control using Spring container with 06/04/2026
package ioc and inside create classes and xml file.

Q2 Write a program to demonstrate Dependency Injection using constructor and setter 06/04/2026
methods

Q3 Write a program to demonstrate Dependency Injection using setter methods. 06/04/2026

Q4 Write a program to demonstrate Dependency Injection using constructor and setter 13/04/2026
methods using annotations.

Q5 Write a program to Create a basic Spring Boot application using Spring Initializer or 13/04/2026
STS and print “My First Spring Application”.
Web Development with Java Lab – MCA Sem II

Q6 Write a program to build a simple application with layered architecture of spring 13/04/2026
boot without a database. Use concept of Collection interface

Q7 Write a program to build a simple application with layered architecture of spring 20/04/2026
boot with database eg. dbemp Table emp (eid, ename, sal, dept)

Q8 Write a program to build application to handle Exception Handling in Spring Boot 20/04/2026

Q9 Write a program to build a simple application of spring boot with database eg. 20/04/2026
dbemp. Table emp (eid, ename, sal, dept) and perform testing using Junit.

UNIT VI - ReactJS Frontend

Q1 Write a React Program using Components and JSX. 27/04/2026

Q2 Write a React Program using State in Class Components. 27/04/2026

Q3 Write a React Program using Props to print student information. 27/04/2026

Q4 Write a React Program for Event Handling. 27/04/2026

Q5 Write a React Program for Forms Handling using useState and useEffect. 27/04/2026

Q6 Write a React Program using Lists using array mapping. 04/05/2026

Q7 Write a React Program using Conditional Rendering. 04/05/2026

Q8 Write a React Program for REST API Integration. 04/05/2026

Q9 Write a React Program for Search Filter to search particular keyword form Array 04/05/2026
set.

Q10 Write a React Program for To-Do List Application. 04/05/2026

Q11 Write a React Program for connecting database in spring boot and frontend in React. 04/05/2026

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 3


Web Development with Java Lab – MCA Sem II

UNIT 1 – JAVA DATABASE CONNECTIVITY

PRACTICAL NO. 01
Write a program to create a menu driven program using Statements
A) Insert record
B) Update record
a) Update by name
b) Update by Designation
c) Update by employee id
C) Delete record
a) Delete by name
b) Delete by Designation
c) Delete by employee id
D) Display record
E) Count the number of records
F) Search by id, name

CODE:
([Link])

package EmployeeApp;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class EmployeeApp {
static final String URL = "jdbc:mysql://localhost:3306/employee_db";
static final String USER = "root";
Bindhya Prakash Karkera | DY25SHSP0MCA054 | 4
Web Development with Java Lab – MCA Sem II

static final String PASS = "Root";


static Connection con;
public static void main(String[] args) {
try {
[Link]("[Link]");
con = [Link](URL, USER, PASS);
Scanner sc = new Scanner([Link]);
int choice;
do {
[Link]("\n===== MENU =====");
[Link]("1. Insert Record");
[Link]("2. Update Record");
[Link]("3. Delete Record");
[Link]("4. Display Records");
[Link]("5. Count Records");
[Link]("6. Search Record");
[Link]("0. Exit");
[Link]("Enter Choice : ");
choice = [Link]();
switch (choice) {
case 1:
insertRecord(sc);
break;
case 2:
updateMenu(sc);
break;
case 3:
deleteMenu(sc);
break;
case 4:
displayRecords();
break;
case 5:
countRecords();

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 5


Web Development with Java Lab – MCA Sem II

break;
case 6:
searchMenu(sc);
break;
case 0:
[Link]("Program Closed");
break;
default:
[Link]("Invalid Choice");
}
} while (choice != 0);
[Link]();
} catch (Exception e) {
[Link]();
}
}
static void insertRecord(Scanner sc) throws SQLException {

[Link]("Enter Employee ID : ");


int id = [Link]();
[Link]();

[Link]("Enter Name : ");


String name = [Link]();

[Link]("Enter Designation : ");


String designation = [Link]();

[Link]("Enter Salary : ");


double salary = [Link]();

String sql = "INSERT INTO employee VALUES (?, ?, ?, ?)";

PreparedStatement ps = [Link](sql);

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 6


Web Development with Java Lab – MCA Sem II

[Link](1, id);
[Link](2, name);
[Link](3, designation);
[Link](4, salary);

[Link]();

[Link]("Record Inserted Successfully");


}
static void updateMenu(Scanner sc) throws SQLException {

[Link]("\n--- Update Menu ---");


[Link]("1. Update by ID");
[Link]("2. Update by Name");
[Link]("3. Update by Designation");

[Link]("Enter Choice : ");


int ch = [Link]();
[Link]();

[Link]("Enter New Salary : ");


double salary = [Link]();
[Link]();

if (ch == 1) {

[Link]("Enter Employee ID : ");


int id = [Link]();

String sql = "UPDATE employee SET salary=? WHERE emp_id=?";

PreparedStatement ps = [Link](sql);

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 7


Web Development with Java Lab – MCA Sem II

[Link](1, salary);
[Link](2, id);
[Link]();
[Link]("Record Updated Successfully");

} else if (ch == 2) {

[Link]("Enter Name : ");


String name = [Link]();

String sql = "UPDATE employee SET salary=? WHERE name=?";

PreparedStatement ps = [Link](sql);

[Link](1, salary);
[Link](2, name);

[Link]();

[Link]("Record Updated Successfully");

} else if (ch == 3) {
[Link]("Enter Designation : ");
String designation = [Link]();

String sql = "UPDATE employee SET salary=? WHERE designation=?";

PreparedStatement ps = [Link](sql);

[Link](1, salary);
[Link](2, designation);

[Link]();

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 8


Web Development with Java Lab – MCA Sem II

[Link]("Record Updated Successfully");

} else {

[Link]("Invalid Choice");
}
}
static void deleteMenu(Scanner sc) throws SQLException {

[Link]("\n--- Delete Menu ---");


[Link]("1. Delete by ID");
[Link]("2. Delete by Name");
[Link]("3. Delete by Designation");

[Link]("Enter Choice : ");


int ch = [Link]();
[Link]();

if (ch == 1) {

[Link]("Enter Employee ID : ");


int id = [Link]();

String sql = "DELETE FROM employee WHERE emp_id=?";

PreparedStatement ps = [Link](sql);

[Link](1, id);

[Link]();

[Link]("Record Deleted Successfully");

} else if (ch == 2) {

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 9


Web Development with Java Lab – MCA Sem II

[Link]("Enter Name : ");


String name = [Link]();

String sql = "DELETE FROM employee WHERE name=?";

PreparedStatement ps = [Link](sql);

[Link](1, name);

[Link]();

[Link]("Record Deleted Successfully");

} else if (ch == 3) {

[Link]("Enter Designation : ");


String designation = [Link]();

String sql = "DELETE FROM employee WHERE designation=?";

PreparedStatement ps = [Link](sql);

[Link](1, designation);

[Link]();

[Link]("Record Deleted Successfully");

} else {

[Link]("Invalid Choice");
}
}

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 10


Web Development with Java Lab – MCA Sem II

static void displayRecords() throws SQLException {

Statement st = [Link]();

ResultSet rs = [Link]("SELECT * FROM employee");

[Link]("\n--- Employee Records ---");

while ([Link]()) {

[Link](
[Link]("emp_id") + " | " +
[Link]("name") + " | " +
[Link]("designation") + " | " +
[Link]("salary")
);
}
}
static void countRecords() throws SQLException {

Statement st = [Link]();

ResultSet rs = [Link]("SELECT COUNT(*) FROM employee");

if ([Link]()) {

[Link]("Total Records : " + [Link](1));


}
}
static void searchMenu(Scanner sc) throws SQLException {

[Link]("\n--- Search Menu ---");


[Link]("1. Search by ID");

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 11


Web Development with Java Lab – MCA Sem II

[Link]("2. Search by Name");

[Link]("Enter Choice : ");


int ch = [Link]();
[Link]();

if (ch == 1) {

[Link]("Enter Employee ID : ");


int id = [Link]();

String sql = "SELECT * FROM employee WHERE emp_id=?";

PreparedStatement ps = [Link](sql);

[Link](1, id);

ResultSet rs = [Link]();

while ([Link]()) {

[Link](
[Link]("emp_id") + " | " +
[Link]("name") + " | " +
[Link]("designation") + " | " +
[Link]("salary")
);
}

} else if (ch == 2) {

[Link]("Enter Name : ");


String name = [Link]();

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 12


Web Development with Java Lab – MCA Sem II

String sql = "SELECT * FROM employee WHERE name=?";

PreparedStatement ps = [Link](sql);

[Link](1, name);

ResultSet rs = [Link]();

while ([Link]()) {

[Link](
[Link]("emp_id") + " | " +
[Link]("name") + " | " +
[Link]("designation") + " | " +
[Link]("salary")
);
}

} else {

[Link]("Invalid Choice");
}
}
}

OUTPUT: (insert record)

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 13


Web Development with Java Lab – MCA Sem II

OUTPUT: (update by name, designation and employee id)

OUTPUT: (delete record by name, designation and id)

OUTPUT: (display records

OUTPUT: (count the number of records)

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 14


Web Development with Java Lab – MCA Sem II

PRACTICAL NO. 02
Write a program to create a menu driven program using Prepared
statements
A) Insert record
B) Update record
a) Update by name
b) Update by Designation
c) Update by employee id
C) Delete record
a) Delete by name
b) Delete by Designation
c) Delete by employee id
D) Display record
E) Count the number of records
F) Search by id, name

CODE:
([Link])

package EmpPrepared;

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class EmpPrepared {

static final String URL = "jdbc:mysql://localhost:3306/emp1";


static final String USER = "root";
static final String PASS = "123456";

static Connection con;

public static void main(String[] args) {


Bindhya Prakash Karkera | DY25SHSP0MCA054 | 15
Web Development with Java Lab – MCA Sem II

try {

[Link]("[Link]");
con = [Link](URL, USER, PASS);

Scanner sc = new Scanner([Link]);

int choice;

do {

[Link]("\n===== MENU =====");


[Link]("1. Insert Record");
[Link]("2. Update Record");
[Link]("3. Delete Record");
[Link]("4. Display Records");
[Link]("5. Count Records");
[Link]("6. Search Record");
[Link]("0. Exit");

[Link]("Enter Choice : ");


choice = [Link]();

switch (choice) {

case 1:
insert(sc);
break;

case 2:
updateMenu(sc);
break;

case 3:
deleteMenu(sc);
break;

case 4:
display();
break;

case 5:
count();
break;

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 16


Web Development with Java Lab – MCA Sem II

case 6:
searchMenu(sc);
break;

case 0:
[Link]("Program Closed");
break;

default:
[Link]("Invalid Choice");
}

} while (choice != 0);

[Link]();

} catch (Exception e) {
[Link]();
}
}
static void insert(Scanner sc) throws SQLException {

[Link]("Enter Employee ID : ");


int id = [Link]();
[Link]();

[Link]("Enter Name : ");


String name = [Link]();

[Link]("Enter Designation : ");


String designation = [Link]();

[Link]("Enter Salary : ");


double salary = [Link]();

String sql = "INSERT INTO employee VALUES (?, ?, ?, ?)";

PreparedStatement ps = [Link](sql);

[Link](1, id);
[Link](2, name);
[Link](3, designation);
[Link](4, salary);

[Link]();

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 17


Web Development with Java Lab – MCA Sem II

[Link]("Record Inserted Successfully");


}
static void updateMenu(Scanner sc) throws SQLException {

[Link]("\n--- Update Menu ---");


[Link]("1. Update by ID");
[Link]("2. Update by Name");
[Link]("3. Update by Designation");

[Link]("Enter Choice : ");


int ch = [Link]();
[Link]();

[Link]("Enter New Salary : ");


double salary = [Link]();
[Link]();

PreparedStatement ps = null;

if (ch == 1) {

[Link]("Enter Employee ID : ");


int id = [Link]();

String sql = "UPDATE employee SET salary=? WHERE emp_id=?";

ps = [Link](sql);

[Link](1, salary);
[Link](2, id);

} else if (ch == 2) {

[Link]("Enter Name : ");


String name = [Link]();

String sql = "UPDATE employee SET salary=? WHERE name=?";

ps = [Link](sql);

[Link](1, salary);
[Link](2, name);

} else if (ch == 3) {

[Link]("Enter Designation : ");


Bindhya Prakash Karkera | DY25SHSP0MCA054 | 18
Web Development with Java Lab – MCA Sem II

String designation = [Link]();

String sql = "UPDATE employee SET salary=? WHERE designation=?";

ps = [Link](sql);

[Link](1, salary);
[Link](2, designation);

} else {

[Link]("Invalid Choice");
}

if (ps != null) {

[Link]();

[Link]("Record Updated Successfully");


}
}
static void deleteMenu(Scanner sc) throws SQLException {

[Link]("\n--- Delete Menu ---");


[Link]("1. Delete by ID");
[Link]("2. Delete by Name");
[Link]("3. Delete by Designation");

[Link]("Enter Choice : ");


int ch = [Link]();
[Link]();

PreparedStatement ps = null;

if (ch == 1) {

[Link]("Enter Employee ID : ");


int id = [Link]();

String sql = "DELETE FROM employee WHERE emp_id=?";

ps = [Link](sql);

[Link](1, id);

} else if (ch == 2) {
Bindhya Prakash Karkera | DY25SHSP0MCA054 | 19
Web Development with Java Lab – MCA Sem II

[Link]("Enter Name : ");


String name = [Link]();

String sql = "DELETE FROM employee WHERE name=?";

ps = [Link](sql);

[Link](1, name);

} else if (ch == 3) {

[Link]("Enter Designation : ");


String designation = [Link]();

String sql = "DELETE FROM employee WHERE designation=?";

ps = [Link](sql);

[Link](1, designation);

} else {

[Link]("Invalid Choice");
}

if (ps != null) {

[Link]();

[Link]("Record Deleted Successfully");


}
}
static void display() throws SQLException {

String sql = "SELECT * FROM employee";

PreparedStatement ps = [Link](sql);

ResultSet rs = [Link]();

[Link]("\n--- Employee Records ---");

while ([Link]()) {

[Link](
Bindhya Prakash Karkera | DY25SHSP0MCA054 | 20
Web Development with Java Lab – MCA Sem II

[Link]("emp_id") + " | " +


[Link]("name") + " | " +
[Link]("designation") + " | " +
[Link]("salary")
);
}
}
static void count() throws SQLException {

String sql = "SELECT COUNT(*) FROM employee";

PreparedStatement ps = [Link](sql);

ResultSet rs = [Link]();

if ([Link]()) {

[Link]("Total Records : " + [Link](1));


}
}
static void searchMenu(Scanner sc) throws SQLException {

[Link]("\n--- Search Menu ---");


[Link]("1. Search by ID");
[Link]("2. Search by Name");

[Link]("Enter Choice : ");


int ch = [Link]();
[Link]();

PreparedStatement ps;

if (ch == 1) {

[Link]("Enter Employee ID : ");


int id = [Link]();

String sql = "SELECT * FROM employee WHERE emp_id=?";

ps = [Link](sql);

[Link](1, id);

} else {

[Link]("Enter Name : ");


Bindhya Prakash Karkera | DY25SHSP0MCA054 | 21
Web Development with Java Lab – MCA Sem II

String name = [Link]();

String sql = "SELECT * FROM employee WHERE name=?";

ps = [Link](sql);

[Link](1, name);
}

ResultSet rs = [Link]();

while ([Link]()) {

[Link](
[Link]("emp_id") + " | " +
[Link]("name") + " | " +
[Link]("designation") + " | " +
[Link]("salary")
);
}
}
}

OUTPUT: (Insert records)

OUTPUT: (Update record by name, designation and id)

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 22


Web Development with Java Lab – MCA Sem II

OUTPUT: (delete record by name, designation and id)

OUTPUT: (Display records)

OUTPUT: (search by id, name)

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 23


Web Development with Java Lab – MCA Sem II

PRACTICAL NUMBER. 03
Write a program to demonstrate the callable statements
A) In
B) Out
C) In-Out

CODE:
([Link])
package CallableExample;

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class CallableExample {

static final String URL =


"jdbc:mysql://localhost:3306/emp_call";
static final String USER = "root";
static final String PASS = "123456";
public static void main(String[] args) {
try {
[Link]("[Link]");
Connection con =
[Link](URL, USER, PASS);

[Link]("=== IN Parameter Example ===");

CallableStatement cs1 =
[Link]("{call getEmployee(?)}");
[Link](1, 1);

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 24


Web Development with Java Lab – MCA Sem II

ResultSet rs = [Link]();
while ([Link]()) {
[Link](
[Link]("emp_id") + " | " +
[Link]("name") + " | " +
[Link]("salary")
);
}
[Link]("\n=== OUT Parameter Example ===");
CallableStatement cs2 =
[Link]("{call getSalary(?)}");
[Link](1, [Link]);
[Link]();
double maxSalary = [Link](1);
[Link]("Max Salary : " + maxSalary);

[Link]("\n=== IN-OUT Parameter Example ===");


CallableStatement cs3 =
[Link]("{call updateSalary(?)}");
[Link](1, 20000);

[Link](1, [Link]);
[Link]();
double updatedSalary = [Link](1);
[Link]("Updated Salary : " + updatedSalary);
[Link]();
} catch (Exception e) {
[Link]();
}
}
}

IN parameter procedure:
DELIMITER $$

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 25


Web Development with Java Lab – MCA Sem II

CREATE PROCEDURE getEmployee(IN eid INT)


BEGIN
SELECT * FROM employee WHERE emp_id = eid;
END $$

DELIMITER ;

OUT parameter procedure:


DELIMITER $$

CREATE PROCEDURE getSalary(OUT sal DOUBLE)


BEGIN
SELECT MAX(salary) INTO sal FROM employee;
END $$

DELIMITER ;

IN-OUT parameter procedure:


DELIMITER $$

CREATE PROCEDURE updateSalary(INOUT sal DOUBLE)


BEGIN
SET sal = sal + 5000;
END $$

DELIMITER ;

OUTPUT:

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 26


Web Development with Java Lab – MCA Sem II

PRACTICAL NO. 04
Write a program to demonstrate the resultSet readonly and Updateable
A) Insert record
B) Update record
a) Update by name
b) Update by Designation
c) Update by employee id
C) Delete record
a) Delete by name
b) Delete by Designation
c) Delete by employee id
D) Display record
E) Count the number of records
F) Search by id, name

CODE:
([Link])
package EmployeeRS;

import [Link].*;
import [Link];

public class EmployeeRS {


static final String URL =
"jdbc:mysql://localhost:3306/emp_rs";

static final String USER = "root";

static final String PASS = "123456";


public static void main(String[] args) {
try {
[Link]("[Link]");

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 27


Web Development with Java Lab – MCA Sem II

Connection con =
[Link](URL, USER, PASS);
Scanner sc = new Scanner([Link]);
int choice;
do {
[Link]("\n===== MENU =====");
[Link]("1. Insert Record");
[Link]("2. Update Record");
[Link]("3. Delete Record");
[Link]("4. Display Records");
[Link]("5. Count Records");
[Link]("6. Search Record");
[Link]("0. Exit");
[Link]("Enter Choice : ");
choice = [Link]();
[Link]();

switch (choice) {
case 1:
insertRecord(con, sc);
break;
case 2:
updateMenu(con, sc);
break;
case 3:
deleteMenu(con, sc);
break;
case 4:
displayRecords(con);
break;
case 5:
countRecords(con);
break;
case 6:

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 28


Web Development with Java Lab – MCA Sem II

searchMenu(con, sc);
break;
case 0:
[Link]("Program Closed");
break;
default:
[Link]("Invalid Choice");
}
} while (choice != 0);
[Link]();
} catch (Exception e) {
[Link]();
}
}
static void insertRecord(Connection con, Scanner sc)
throws SQLException {

Statement st = [Link](
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE
);
ResultSet rs = [Link](
"SELECT * FROM employee"
);
[Link]("Enter Employee ID : ");
int id = [Link]();
[Link]();
[Link]("Enter Name : ");
String name = [Link]();

[Link]("Enter Designation : ");


String designation = [Link]();
[Link]("Enter Salary : ");
double salary = [Link]();

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 29


Web Development with Java Lab – MCA Sem II

[Link]();
[Link]();
[Link]("emp_id", id);
[Link]("name", name);
[Link]("designation", designation);
[Link]("salary", salary);
[Link]();
[Link]("Record Inserted Successfully");
}
static void updateMenu(Connection con, Scanner sc)
throws SQLException {

[Link]("\n1. Update by ID");


[Link]("2. Update by Name");
[Link]("3. Update by Designation")
int ch = [Link]();
[Link]();

Statement st = [Link](
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE
);
ResultSet rs = [Link](
"SELECT * FROM employee"
);
if (ch == 1) {
[Link]("Enter Employee ID : ");
int id = [Link]();
[Link]();

while ([Link]()) {
if ([Link]("emp_id") == id) {

[Link]("Enter New Salary : ");

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 30


Web Development with Java Lab – MCA Sem II

double salary = [Link]();

[Link]("salary", salary);
[Link]();
[Link]("Record Updated");
return;
}
}
} else if (ch == 2) {

[Link]("Enter Name : ");


String name = [Link]();
while ([Link]())
if ([Link]("name")
.equalsIgnoreCase(name)) {
[Link]("Enter New Salary : ");
double salary = [Link]();
[Link]("salary", salary);
[Link]();
[Link]("Record Updated");
return;
}
}
} else if (ch == 3) {
[Link]("Enter Designation : ");
String designation = [Link]();
while ([Link]()) {

if ([Link]("designation")
.equalsIgnoreCase(designation)) {

[Link]("Enter New Salary : ");


double salary = [Link]();
[Link]("salary", salary);

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 31


Web Development with Java Lab – MCA Sem II

[Link]();
[Link]("Record Updated");
return;
}
}
}
[Link]("Record Not Found");
}
static void deleteMenu(Connection con, Scanner sc)
throws SQLException {

Statement st = [Link](
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE
);
ResultSet rs = [Link](
"SELECT * FROM employee"
);
[Link]("\n1. Delete by ID");
[Link]("2. Delete by Name");
[Link]("3. Delete by Designation");

int ch = [Link]();
[Link]();

if (ch == 1) {

[Link]("Enter Employee ID : ");


int id = [Link]();
while ([Link]()) {

if ([Link]("emp_id") == id) {
[Link]();
[Link]("Record Deleted");

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 32


Web Development with Java Lab – MCA Sem II

return;
}
}
} else if (ch == 2) {
[Link]("Enter Name : ");
String name = [Link]();
while ([Link]()) {

if ([Link]("name")
.equalsIgnoreCase(name)) {
[Link]();
[Link]("Record Deleted");

return;
}
}
} else if (ch == 3) {
[Link]("Enter Designation : ");
String designation = [Link]();
while ([Link]()) {
if ([Link]("designation")
.equalsIgnoreCase(designation)) {
[Link]()
[Link]("Record Deleted");
return;
}
}
}

[Link]("Record Not Found");


}

static void displayRecords(Connection con)


throws SQLException {

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 33


Web Development with Java Lab – MCA Sem II

Statement st = [Link](
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY
);
ResultSet rs = [Link](
"SELECT * FROM employee"
);
[Link]("\n--- Employee Records ---");
while ([Link]()) {
[Link](
[Link]("emp_id") + " | " +
[Link]("name") + " | " +
[Link]("designation") + " | " +
[Link]("salary")
);
}
}
static void countRecords(Connection con)
throws SQLException {
Statement st = [Link](
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY
);
ResultSet rs = [Link](
"SELECT COUNT(*) FROM employee"
);
if ([Link]()) {
[Link](
"Total Records : " + [Link](1)
);
}
}
static void searchMenu(Connection con, Scanner sc)

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 34


Web Development with Java Lab – MCA Sem II

throws SQLException
Statement st = [Link](
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY
);
ResultSet rs = [Link](
"SELECT * FROM employee"
);
[Link]("\n1. Search by ID");
[Link]("2. Search by Name");
int ch = [Link]();
[Link]();
boolean found = false;
if (ch == 1) {
[Link]("Enter Employee ID : ");
int id = [Link]();
while ([Link]()) {
if ([Link]("emp_id") == id) {
[Link](
[Link]("emp_id") + " | " +
[Link]("name") + " | " +
[Link]("designation") + " | " +
[Link]("salary")
);
found = true;
}
} else if (ch == 2) {
[Link]("Enter Name : ");
String name = [Link]();
while ([Link]()) {
if ([Link]("name")
.equalsIgnoreCase(name)) {
[Link](
[Link]("emp_id") + " | " +

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 35


Web Development with Java Lab – MCA Sem II

[Link]("name") + " | " +


[Link]("designation") + " | " +
[Link]("salary")
);
found = true;
}
}
}
if (!found) {
[Link]("Record Not Found"); }}}
OUTPUT:

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 36


Web Development with Java Lab – MCA Sem II

UNIT 2 – JAVA SERVLETS


PRACTICAL NO. 01
Write a program to display date, time and number of requests (count)
using Generic and HTTP servlet life cycle.

CODE:
([Link])
package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

@WebServlet("/generic")
public class GenericServletDemo extends GenericServlet {
int count = 0;
public void init(ServletConfig config)
throws ServletException {

[Link](config);
[Link](
"Generic Servlet Initialized"
);
}
public void service(
ServletRequest req,

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 37


Web Development with Java Lab – MCA Sem II

ServletResponse res)
throws ServletException, IOException {
count++;
[Link]("text/html");

PrintWriter out = [Link]();

Date date = new Date();


[Link]("<html>");
[Link]("<head>");
[Link]("<title>Generic Servlet</title>");
[Link]("</head>");

[Link]("<body>");

[Link]("<h2>Generic Servlet Life Cycle</h2>");

[Link](
"<p>Date & Time : "
+ [Link]()
+ "</p>"
);
[Link](
"<p>Request Count : "
+ count
+ "</p>"
);
[Link]("</body>");
[Link]("</html>");
}
public void destroy() {

[Link](
"Generic Servlet Destroyed"

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 38


Web Development with Java Lab – MCA Sem II

);
}
}

CODE:
([Link])
package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

@WebServlet("/http")
public class HttpServletDemo extends HttpServlet {
int count = 0;
public void init()
throws ServletException {

[Link](
"HTTP Servlet Initialized"
);
}
protected void doGet(
HttpServletRequest request,
HttpServletResponse response)

throws ServletException, IOException {

count++;

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 39


Web Development with Java Lab – MCA Sem II

[Link]("text/html");
PrintWriter out = [Link]();
Date date = new Date();

[Link]("<html>");
[Link]("<head>");
[Link]("<title>HTTP Servlet</title>");
[Link]("</head>");
[Link]("<body>");
[Link]("<h2>HTTP Servlet Life Cycle</h2>");
[Link](
"<p>Date & Time : "
+ [Link]()
+ "</p>"
);
[Link](
"<p>Request Count : "
+ count
+ "</p>"
);
[Link]("</body>");
[Link]("</html>");
}

public void destroy() {


[Link](
"HTTP Servlet Destroyed"
);
}
}

CODE:
([Link])
<!DOCTYPE html>

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 40


Web Development with Java Lab – MCA Sem II

<html>
<head>
<title>Servlet Demo</title>
</head>
<body>
<h2>Servlet Demo Home Page</h2>
<a href="generic">
Run Generic Servlet
</a>
<br><br>
<a href="http">
Run HTTP Servlet
</a>
</body>
</html>

OUTPUT:

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 41


Web Development with Java Lab – MCA Sem II

PRACTICAL NO. 02
Write a program to show servlet config and context with student
information.

CODE:
([Link])
package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

@WebServlet(
urlPatterns = "/student",
initParams = {
@WebInitParam(
name = "name",
value = "Rahul"
),
@WebInitParam(
name = "roll",
value = "101"
),
@WebInitParam(
name = "course",
value = "BCA"
)
Bindhya Prakash Karkera | DY25SHSP0MCA054 | 42
Web Development with Java Lab – MCA Sem II

}
)
public class StudentServlet extends HttpServlet {
protected void doGet(
HttpServletRequest request,
HttpServletResponse response)

throws ServletException, IOException {


[Link]("text/html");

PrintWriter out = [Link]();


ServletConfig config = getServletConfig();
String name =
[Link]("name");
String roll =
[Link]("roll");
String course =
[Link]("course");
ServletContext context =
getServletContext();
String college =
[Link]("college");
[Link]("<html>");
[Link]("<body>");
[Link]("<h2>Student Information</h2>");
[Link](
"<p>Name : " + name + "</p>"
);
[Link](
"<p>Roll No : " + roll + "</p>"
);
[Link](
"<p>Course : " + course + "</p>"
);

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 43


Web Development with Java Lab – MCA Sem II

[Link]("<h2>College Information</h2>");
[Link](
"<p>College Name : "
+ college
+ "</p>"
);
[Link]("</body>");
[Link]("</html>");
}
}
CODE:
([Link])
package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
@WebListener
public class MyListener
implements ServletContextListener {

public void contextInitialized(


ServletContextEvent event) {

ServletContext context =
[Link]();
[Link](
"college",
"ABC College, Mumbai"
);
}
public void contextDestroyed(
ServletContextEvent event) {

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 44


Web Development with Java Lab – MCA Sem II

}
}

CODE:
([Link])
<!DOCTYPE html>
<html>
<head>
<title>Student App</title>
</head>
<body>
<h2>Student Information System</h2>
<a href="student">
Click to View Student Details
</a>
</body>
</html>

OUTPUT:

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 45


Web Development with Java Lab – MCA Sem II

PRACTICAL NO. 03
Write a program to add 2 numbers using get parameter.

CODE:
([Link])
package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

@WebServlet("/add")
public class AddServlet extends HttpServlet {

protected void doGet(


HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();

String n1 =
[Link]("num1");
String n2 =
[Link]("num2");
int num1 = [Link](n1);
int num2 = [Link](n2);
int sum = num1 + num2;

[Link]("<html>");
Bindhya Prakash Karkera | DY25SHSP0MCA054 | 46
Web Development with Java Lab – MCA Sem II

[Link]("<body>");
[Link]("<h2>Addition Result</h2>");
[Link](
"<p>Number 1 : "
+ num1
+ "</p>"
);
[Link](
"<p>Number 2 : "
+ num2
+ "</p>"
);
[Link](
"<h3>Sum = "
+ sum
+ "</h3>"
);
[Link]("</body>");
[Link]("</html>");
}
}

CODE:
([Link])
<!DOCTYPE html>
<html>
<head>
<title>Addition</title>
</head>
<body>
<h2>Add Two Numbers</h2>
<form action="add" method="get">
Enter Number 1 :
<input type="text" name="num1">

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 47


Web Development with Java Lab – MCA Sem II

<br><br>
Enter Number 2 :
<input type="text" name="num2">
<br><br>
<input type="submit" value="Add">
</form>
</body>
</html>

OUTPUT:

PRACTICAL NO. 04
Write a program to make a calculator using doGet method.

CODE:
([Link])
package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 48


Web Development with Java Lab – MCA Sem II

@WebServlet("/calc")
public class CalculatorServlet extends HttpServlet {
protected void doGet(
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();

try {
int num1 = [Link](
[Link]("num1")
);
int num2 = [Link](
[Link]("num2")
);
String op =
[Link]("operation");
int result = 0;
String symbol = "";
if ([Link]("Add")) {

result = num1 + num2;


symbol = "+";
}
else if ([Link]("Sub")) {
result = num1 - num2;
symbol = "-";
}
else if ([Link]("Mul")) {
result = num1 * num2;
symbol = "*";
}
else if ([Link]("Div")) {

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 49


Web Development with Java Lab – MCA Sem II

if (num2 == 0) {
[Link](
"<h3>Cannot divide by zero</h3>"
);
return;
}
result = num1 / num2;
symbol = "/";
}
[Link]("<html>");
[Link]("<body>");
[Link]("<h2>Calculator Result</h2>");
[Link](
"<p>"
+ num1
+""
+ symbol
+""
+ num2
+"="
+ result
+ "</p>"
);

[Link]("</body>");
[Link]("</html>");
}
catch (Exception e) {
[Link](
"<h3>Please Enter Valid Numbers!</h3>"
);
}
}
}

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 50


Web Development with Java Lab – MCA Sem II

CODE:
([Link])
<!DOCTYPE html>
<html>
<head>
<title>Calculator</title>
</head>
<body>
<h2>Simple Calculator</h2>
<form action="calc" method="get">
Enter Number 1 :
<input type="text" name="num1">
<br><br>
Enter Number 2 :
<input type="text" name="num2">
<br><br>
<input type="submit"
name="operation"
value="Add">
<input type="submit"
name="operation"
value="Sub">
<input type="submit"
name="operation"
value="Mul">
<input type="submit"
name="operation"
value="Div"
</form>
</body>
</html>

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 51


Web Development with Java Lab – MCA Sem II

OUTPUT:

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 52


Web Development with Java Lab – MCA Sem II

PRACTICAL NO. 05
Write a program to create login page email and password using doGet()
and redirect page to welcome page containing Welcome username
entered.

CODE:
([Link])
package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
protected void doGet(
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

String email =
[Link]("email");
String password =
[Link]("password");

if ([Link]("admin@[Link]")
&& [Link]("1234")) {
[Link](
"welcome?user=" + email
);
Bindhya Prakash Karkera | DY25SHSP0MCA054 | 53
Web Development with Java Lab – MCA Sem II

}
else {
[Link]("text/html");
PrintWriter out =
[Link]();
[Link](
"<h3>Invalid Email or Password!</h3>"
);
}
}
}

CODE:
([Link])
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

@WebServlet("/welcome")
public class WelcomeServlet extends HttpServlet {
protected void doGet(
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String user =
[Link]("user");
[Link]("text/html");
PrintWriter out =
[Link]();

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 54


Web Development with Java Lab – MCA Sem II

[Link]("<html>");
[Link]("<body>");
[Link](
"<h2>Welcome " + user + "</h2>"
);
[Link]("</body>");
[Link]("</html>");
}
}

CODE:
([Link])
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<h2>Login Form</h2>
<form action="login" method="get">
Email :
<input type="text" name="email">
<br><br>
Password :
<input type="password" name="password">
<br><br>
<input type="submit" value="Login">
</form>
</body>
</html>

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 55


Web Development with Java Lab – MCA Sem II

OUTPUT:

PRACTICAL NO. 06
Write a program to show HTTP request and HTTP response methods.

CODE:
([Link])
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class MyServlet extends HttpServlet {
protected void doGet(

HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();
String name =
[Link]("username");

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 56


Web Development with Java Lab – MCA Sem II

[Link]("<html>");
[Link]("<body>");

[Link](
"<h2>GET Request Received</h2>"
);
[Link](
"<p>Hello "
+ name
+ " (GET)</p>"
);
[Link]("</body>");
[Link]("</html>");

protected void doPost(

HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();
String name =
[Link]("username");
[Link]("<html>");
[Link]("<body>");
[Link](
"<h2>POST Request Received</h2>"
);
[Link](
"<p>Hello "
+ name
+ " (POST)</p>"
);
[Link]("</body>");

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 57


Web Development with Java Lab – MCA Sem II

[Link]("</html>");
}
}

CODE:
([Link])
<!DOCTYPE html>
<html>
<head>
<title>HTTP Demo</title>
</head>
<body>
<h2>HTTP Request & Response</h2>
<!-- GET METHOD -->
<form action="MyServlet" method="get">
Enter Name :
<input type="text" name="username">
<input type="submit"
value="GET Request">
</form>
<br><br>
<!-- POST METHOD -->
<form action="MyServlet" method="post">
Enter Name :
<input type="text" name="username">
<input type="submit"
value="POST Request">
</form>
</body>
</html>

CODE:
([Link])
<?xml version="1.0" encoding="UTF-8"?>

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 58


Web Development with Java Lab – MCA Sem II

<web-app xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="
[Link]
[Link]
version="3.1">
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>
[Link]
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>
/MyServlet
</url-pattern>
</servlet-mapping>
</web-app>

OUTPUT:

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 59


Web Development with Java Lab – MCA Sem II

PRACTICAL NO. 07
Write a program to print 1 to 10 lucky number from 1 to 100 random
number.

CODE:
([Link])
package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class LuckyServlet extends HttpServlet {
protected void doGet(
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();

Random rand = new Random();

[Link]("<html>");
[Link]("<body>");
[Link](
"<h2>10 Lucky Numbers (1 to 100)</h2>"
);
for (int i = 1; i <= 10; i++) {
int num =
[Link](100) + 1;
[Link](
Bindhya Prakash Karkera | DY25SHSP0MCA054 | 60
Web Development with Java Lab – MCA Sem II

"<p>Lucky Number "


+i
+":"
+ num
+ "</p>"
);
}
[Link]("</body>");
[Link]("</html>");
}
}

CODE:
([Link])
<!DOCTYPE html>

<html>
<head>
<title>Lucky Numbers</title>
</head>
<body>
<h2>Generate Lucky Numbers</h2>
<form action="LuckyServlet"
method="get">
<input type="submit"
value="Show Lucky Numbers">
</form>
</body>
</html>

CODE:
([Link])
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="[Link]

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 61


Web Development with Java Lab – MCA Sem II

xmlns:xsi="[Link]
xsi:schemaLocation="
[Link]
[Link]
version="3.1">
<servlet>
<servlet-name>
LuckyServlet
</servlet-name>
<servlet-class>
[Link]
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>
LuckyServlet
</servlet-name>
<url-pattern>
/LuckyServlet
</url-pattern>
</servlet-mapping>
</web-app>

OUTPUT:

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 62


Web Development with Java Lab – MCA Sem II

PRACTICAL NO. 08
Write a program to create a login page to store information using
cookie.

CODE:
([Link])
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<h2>Login Form</h2>
<form action="LoginServlet" method="post">
Username:
<input type="text" name="username">
<br><br>
Password:
<input type="password" name="password">
<br><br>

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 63


Web Development with Java Lab – MCA Sem II

<input type="submit" value="Login">


</form>
</body>
</html>

CODE:
([Link])
package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class LoginServlet extends HttpServlet {
protected void doPost(
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();
String username =
[Link]("username");
String password =
[Link]("password");
if ([Link]("ronak@[Link]")
&& [Link]("123")) {
Cookie ck =
new Cookie("user", username);
[Link](ck);
[Link]("<html>");
[Link]("<body>");

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 64


Web Development with Java Lab – MCA Sem II

[Link]("<h2>Login Successful</h2>");
[Link](
"<p>Cookie Stored Successfully!</p>"
);
[Link](
"<a href='ViewCookieServlet'>View Cookie</a>"
);
[Link]("</body>");
[Link]("</html>");
} else {
[Link]("<html>");
[Link]("<body>");
[Link]("<h2>Invalid Login</h2>");
[Link](
"<a href='[Link]'>Try Again</a>"
);
[Link]("</body>");
[Link]("</html>");
}
}
}

CODE:
([Link])
package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class ViewCookieServlet extends HttpServlet {

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 65


Web Development with Java Lab – MCA Sem II

protected void doGet(


HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();
Cookie[] cookies =
[Link]();
[Link]("<html>");
[Link]("<body>");
if (cookies != null) {
for (Cookie c : cookies) {
if ([Link]().equals("user")) {
String username =
[Link]();
[Link](
"<h2>Stored Cookie Information</h2>"
);
[Link](
"<p>Username : "
+ username
+ "</p>"
);
[Link](
"<h3>Welcome "
+ username
+ "!</h3>"
);
}
}
} else {
[Link]("<p>No Cookies Found</p>");
}
[Link]("</body>");

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 66


Web Development with Java Lab – MCA Sem II

[Link]("</html>");
}
}
CODE:
([Link])
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="
[Link]
[Link]
version="3.1">
<!-- Login Servlet -->
<servlet>
<servlet-name>
LoginServlet
</servlet-name>
<servlet-class>
[Link]
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>
LoginServlet
</servlet-name>
<url-pattern>
/LoginServlet
</url-pattern>
</servlet-mapping>
<!-- View Cookie Servlet -->
<servlet>
<servlet-name>
ViewCookieServlet
</servlet-name>

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 67


Web Development with Java Lab – MCA Sem II

<servlet-class>
[Link]
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>
ViewCookieServlet
</servlet-name>
<url-pattern>
/ViewCookieServlet
</url-pattern>
</servlet-mapping>
</web-app>

OUTPUT:

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 68


Web Development with Java Lab – MCA Sem II

PRACTICAL NO. 09
Write a program to create a login form using request dispatcher method
like include and forward to print appropriate messages like Welcome
username, if login id or password is incorrect, redirect to login page
with appropriate error message.

CODE:
([Link])
<!DOCTYPE html>
<html>
<head>
<title>Welcome</title>
</head>
<body>
<h2>Welcome Page</h2>
<h3>Login Successful</h3>
</body>
</html>

CODE:
([Link])
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<h2>Login Form</h2>
<form action="LoginServlet" method="post">
Username:
<input type="text" name="username">
<br><br>
Password:
<input type="password" name="password">

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 69


Web Development with Java Lab – MCA Sem II

<br><br>
<input type="submit" value="Login">
</form>
</body>
</html>

CODE:
([Link])
<!DOCTYPE html>
<html>
<head>
<title>Welcome</title>
</head>
<body>
<h2>Welcome Page</h2>
<h3>Login Successful</h3>
</body>
</html>

CODE:
([Link])
package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class LoginServlet extends HttpServlet {
protected void doPost(
HttpServletRequest request,
HttpServletResponse response)

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 70


Web Development with Java Lab – MCA Sem II

throws ServletException, IOException {


[Link]("text/html");
PrintWriter out = [Link]();
String username =
[Link]("username");
String password =
[Link]("password");
if ([Link]("ronak@[Link]")
&& [Link]("123")) {
RequestDispatcher rd =
[Link](
"[Link]"
);
[Link](request, response);
} else {
[Link](
"<h3 style='color:red;'>Invalid Username or Password!</h3>"
);
RequestDispatcher rd =
[Link](
"[Link]"
)
[Link](request, response);
}
}
}

CODE:
([Link])
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="
[Link]

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 71


Web Development with Java Lab – MCA Sem II

[Link]
version="3.1">
<servlet>
<servlet-name>
LoginServlet
</servlet-name>
<servlet-class>
[Link]
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>
LoginServlet
</servlet-name>
<url-pattern>
/LoginServlet
</url-pattern>
</servlet-mapping>
</web-app>

OUTPUT:

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 72


Web Development with Java Lab – MCA Sem II

PRACTICAL NO. 10

Write a program to create a login form using send redirect method to


print appropriate messages like Welcome username, if login id or
password is incorrect, redirect to login page with appropriate error
message.

CODE:
([Link])
package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
protected void doPost(
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String user = [Link]("username");
String pass = [Link]("password");
String validUser = "admin";
String validPass = "1234";
if ([Link](validUser) && [Link](validPass)) {
[Link]("welcome?user=" + user);
} else
[Link](
"[Link]?error=Invalid Username or Password"
);
}
Bindhya Prakash Karkera | DY25SHSP0MCA054 | 73
Web Development with Java Lab – MCA Sem II

}
}

CODE:
([Link])
package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@WebServlet("/welcome")
public class WelcomeServlet extends HttpServlet {
protected void doGet(
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

String user = [Link]("user");


[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<html><body>");
[Link]("<h2>Welcome " + user + "</h2>");
[Link]("</body></html>");
}
}

CODE:
([Link])
<!DOCTYPE html>
<html>

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 74


Web Development with Java Lab – MCA Sem II

<head>
<title>Login Page</title>
</head>
<body>
<h2>Login Form</h2>
<form action="login" method="post">
Username:
<input type="text" name="username">
<br><br>
Password:
<input type="password" name="password">
<br><br>
<input type="submit" value="Login">
</form>
<p style="color:red;">
<script>
const params =
new URLSearchParams([Link]);
if ([Link]("error")) {
[Link]([Link]("error"));
}
</script>
</p>
</body>
</html>

CODE:
([Link])
<web-app xmlns="[Link]
version="3.1">
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>[Link]</servlet-class>
</servlet>

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 75


Web Development with Java Lab – MCA Sem II

<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>WelcomeServlet</servlet-name>
<servlet-class>[Link]</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>WelcomeServlet</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>

OUTPUT:

PRACTICAL NO. 11
Write a program to create login form using request dispatcher method
like include and forward & using database to print appropriate
messages like Welcome username, if login id or password is incorrect
redirect to login page with appropriate error message.

CODE:
([Link])
<!DOCTYPE html>
Bindhya Prakash Karkera | DY25SHSP0MCA054 | 76
Web Development with Java Lab – MCA Sem II

<html>
<head>
<title>Login Page</title>
</head>
<body>
<h2>Login Form</h2>
<form action="login" method="post">
Username:
<input type="text" name="username" required>
<br><br>
Password:
<input type="password" name="password" required>
<br><br>
<input type="submit" value="Login">
</form>
</body>
</html>

CODE:
([Link])
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@WebServlet("/login")

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 77


Web Development with Java Lab – MCA Sem II

public class LoginServlet extends HttpServlet {


protected void doPost(
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String user =
[Link]("username");
String pass =
[Link]("password");
try {
[Link](
"[Link]"
);
Connection con =
[Link](
"jdbc:mysql://localhost:3306/login_db",
"root",
"123456"
);
PreparedStatement ps =
[Link](
"SELECT * FROM users WHERE username=? AND password=?"
);
[Link](1, user);
[Link](2, pass);
ResultSet rs =
[Link]();
if ([Link]()) {
[Link](
"username",
user
);
RequestDispatcher rd =
[Link](

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 78


Web Development with Java Lab – MCA Sem II

"welcome"
);
[Link](
request,
response
);
} else {
[Link](
"text/html"
);
PrintWriter out =
[Link]();
[Link](
"<h3 style='color:red;'>Invalid Username or Password</h3>"
);
RequestDispatcher rd =
[Link](
"[Link]"
);
[Link](
request,
response
);
}
[Link]();
} catch (Exception e) {
[Link]();
[Link]().println(
"<h3>Database Connection Error!</h3>"
);
}
}
}

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 79


Web Development with Java Lab – MCA Sem II

CODE:
([Link])
package [Link]
import [Link];
import [Link];
import [Link]
import [Link];
import [Link];
import [Link];
@WebServlet("/welcome")
public class WelcomeServlet extends HttpServlet {
protected void service(
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String user =
(String) [Link]("username");
[Link]("text/html");
[Link]().println(
"<h2>Welcome " + user + "</h2>"
);
}
}

OUTPUT:

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 80


Web Development with Java Lab – MCA Sem II

PRACTICAL NO. 12
Write a program to create a login form & print message using HTTP
session interface.

CODE:
([Link])
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String user = [Link]("username");
String pass = [Link]("password");
if([Link]("admin") && [Link]("1234")) {
HttpSession session = [Link]();
[Link]("username", user);
[Link]("welcome");
} else {
[Link]("text/html");
[Link]().println(
"<h3 style='color:red;'>Invalid Username or Password</h3>"
);
RequestDispatcher rd =
[Link]("[Link]");
[Link](request, response);
Bindhya Prakash Karkera | DY25SHSP0MCA054 | 81
Web Development with Java Lab – MCA Sem II

}
}
}

CODE:
([Link])
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@WebServlet("/welcome")
public class WelcomeServlet extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html");
HttpSession session =
[Link](false);
if(session != null &&
[Link]("username") != null) {
String user =
(String) [Link]("username");
[Link]().println(
"<h2>Welcome " + user + "</h2>"
);
[Link]().println(
"<br><a href='logout'>Logout</a>"
);
} else {
[Link]("[Link]");

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 82


Web Development with Java Lab – MCA Sem II

}
}
}

CODE:
([Link])
package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

@WebServlet("/logout")
public class LogoutServlet extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

HttpSession session =
[Link](false);
if(session != null) {
[Link]();
}
[Link]("[Link]");
}
}

CODE:
([Link])
<!DOCTYPE html>

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 83


Web Development with Java Lab – MCA Sem II

<html>
<head>
<meta charset="UTF-8">
<title>Login Page</title>
</head>
<body>
<h2>Login Form</h2>
<form action="login" method="post">
Username:
<input type="text" name="username" required>
<br><br>
Password:
<input type="password" name="password" required>
<br><br>
<input type="submit" value="Login">
</form>
</body>
</html>

OUTPUT:

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 84


Web Development with Java Lab – MCA Sem II

UNIT 3 – JAVA SERVER PAGES (JSP)


PRACTICAL NO. 01

Write a program to make a calculator (ADD, SUBTRACT,


MULTIPLY, DIVIDE) using JSP.

CODE:

([Link])

<%@ page language="java" contentType="text/html;charset=UTF-8" %>

<!DOCTYPE html>

<html>

<head>

<title>Calculator</title>

</head>

<body>

<h2>Simple Calculator</h2>

<form action="calc" method="post">

Number 1:

<input type="text" name="num1">

<br><br>

Number 2:

<input type="text" name="num2">

<br><br>

<input type="submit" name="operation" value="ADD">

<input type="submit" name="operation" value="SUBTRACT">

<input type="submit" name="operation" value="MULTIPLY">


Bindhya Prakash Karkera | DY25SHSP0MCA054 | 85
Web Development with Java Lab – MCA Sem II

<input type="submit" name="operation" value="DIVIDE">

</form>

<br>

<h3>

Result:

<%= [Link]("result") != null ?

[Link]("result") : "" %>

</h3>

</body>

</html>

CODE:

([Link])

package [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

@WebServlet("/calc")

public class CalculatorServlet extends HttpServlet {

protected void doPost(HttpServletRequest request,

HttpServletResponse response)
Bindhya Prakash Karkera | DY25SHSP0MCA054 | 86
Web Development with Java Lab – MCA Sem II

throws ServletException, IOException {

double n1 = [Link]([Link]("num1"));

double n2 = [Link]([Link]("num2"));

String op = [Link]("operation");

double result = 0;

if([Link]("ADD")) {

result = n1 + n2;

else if([Link]("SUBTRACT")) {

result = n1 - n2;

else if([Link]("MULTIPLY")) {

result = n1 * n2;

else if([Link]("DIVIDE")) {

if(n2 != 0) {

result = n1 / n2;

else {

[Link]("result",

"Cannot divide by zero");

RequestDispatcher rd =

[Link]("[Link]");

[Link](request, response);

return;
Bindhya Prakash Karkera | DY25SHSP0MCA054 | 87
Web Development with Java Lab – MCA Sem II

[Link]("result", result);

RequestDispatcher rd =

[Link]("[Link]");

[Link](request, response);

CODE:

([Link])

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="[Link]

xmlns:xsi="[Link]

xsi:schemaLocation="

[Link]

[Link]

version="3.1">

<welcome-file-list>

<welcome-file>[Link]</welcome-file>

</welcome-file-list>

</web-app>

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 88


Web Development with Java Lab – MCA Sem II

OUTPUT:

PRACTICAL NO. 2

Write a program to calculate the factorial of a given number using JSP.

CODE:

([Link])

<%@ page language="java" contentType="text/html;charset=UTF-8" %>

<!DOCTYPE html>

<html>

<head>

<title>Factorial Calculator</title>

</head>

<body>

<h2>Factorial Calculator</h2>

<form action="fact" method="post">

Enter Number:

<input type="text" name="num">

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 89


Web Development with Java Lab – MCA Sem II

<br><br>

<input type="submit" value="Calculate">

</form>

<br>

<h3>

Result:

<%= [Link]("result") != null ?

[Link]("result") : "" %>

</h3>

</body>

</html>

CODE:

([Link])

package [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

@WebServlet("/fact")

public class FactorialServlet extends HttpServlet {

protected void doPost(HttpServletRequest request,


Bindhya Prakash Karkera | DY25SHSP0MCA054 | 90
Web Development with Java Lab – MCA Sem II

HttpServletResponse response)

throws ServletException, IOException {

int num = [Link]([Link]("num"));

long fact = 1;

for(int i = 1; i <= num; i++) {

fact = fact * i;

[Link]("result", fact);

RequestDispatcher rd =

[Link]("[Link]");

[Link](request, response);

CODE:

([Link])

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="[Link]

xmlns:xsi="[Link]

xsi:schemaLocation="

[Link]

[Link]

version="3.1">

<welcome-file-list>

<welcome-file>[Link]</welcome-file>
Bindhya Prakash Karkera | DY25SHSP0MCA054 | 91
Web Development with Java Lab – MCA Sem II

</welcome-file-list>

</web-app>

OUTPUT:

PRACTICAL NO. 03

Write a program to reverse the string using JSP.

CODE:

([Link])

<%@ page language="java" contentType="text/html;charset=UTF-8" %>

<!DOCTYPE html>

<html>

<head>
Bindhya Prakash Karkera | DY25SHSP0MCA054 | 92
Web Development with Java Lab – MCA Sem II

<title>Reverse String</title>

</head>

<body>

<h2>Reverse String Program</h2>

<form action="reverse" method="post">

Enter String:

<input type="text" name="text">

<br><br>

<input type="submit" value="Reverse">

</form>

<br>

<h3>

Result:

<%= [Link]("result") != null ?

[Link]("result") : "" %>

</h3>

</body>

</html>

CODE:

([Link])

package [Link];

import [Link];

import [Link];

import [Link];
Bindhya Prakash Karkera | DY25SHSP0MCA054 | 93
Web Development with Java Lab – MCA Sem II

import [Link];

import [Link];

import [Link];

import [Link];

@WebServlet("/reverse")

public class ReverseServlet extends HttpServlet {

protected void doPost(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException {

String input = [Link]("text");

String reversed =

new StringBuilder(input).reverse().toString();

[Link]("result", reversed);

RequestDispatcher rd =

[Link]("[Link]");

[Link](request, response);

CODE:

([Link])

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="[Link]

xmlns:xsi="[Link]

xsi:schemaLocation="
Bindhya Prakash Karkera | DY25SHSP0MCA054 | 94
Web Development with Java Lab – MCA Sem II

[Link]

[Link]

version="3.1">

<welcome-file-list>

<welcome-file>[Link]</welcome-file>

</welcome-file-list>

</web-app>

OUTPUT:

PRACTICAL NO. 04

Write a program to create a JSP snippet using four scripting elements


(scriplet).

CODE:

([Link])

<%@ page language="java" contentType="text/html;charset=UTF-8" %>

<!DOCTYPE html>

<html>

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 95


Web Development with Java Lab – MCA Sem II

<head>

<title>JSP Scripting Elements</title>

</head>

<body>

<h2>JSP Scripting Elements Example</h2>

<!-- 1. Declaration -->

<%!

int a = 10;

int b = 20;

int add(int x, int y) {

return x + y;

%>

<!-- 2. Scriptlet -->

<%

int sum = add(a, b);

%>

<!-- 3. Expression -->

<h3>

Sum of a and b is:

<%= sum %>

</h3>

<!-- 4. Directive already used at top -->

</body>

</html>
Bindhya Prakash Karkera | DY25SHSP0MCA054 | 96
Web Development with Java Lab – MCA Sem II

CODE:

([Link])

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="[Link]

xmlns:xsi="[Link]

xsi:schemaLocation="

[Link]

[Link]

version="3.1">

<welcome-file-list>

<welcome-file>[Link]</welcome-file>

</welcome-file-list>

</web-app>

OUTPUT:

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 97


Web Development with Java Lab – MCA Sem II

PRACTICAL NO. 05

Write a program to create a JSP code using the include tag.

CODE:

([Link])

<!DOCTYPE html>

<html>

<body>

<h2 style="color:blue;">

Welcome to My Website

</h2>

<hr>

CODE:

([Link])

<hr>

<h4 style="color:green;">

Thank you for visiting!

</h4>

</body>

</html>

CODE:

([Link])

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 98


Web Development with Java Lab – MCA Sem II

<%@ page language="java"

contentType="text/html;charset=UTF-8" %>

<jsp:include page="[Link]" />

<h3>

This is main content of the page.

</h3>

<jsp:include page="[Link]" />

CODE:

([Link])

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="[Link]

xmlns:xsi="[Link]

xsi:schemaLocation="

[Link]

[Link]

version="3.1">

<welcome-file-list>

<welcome-file>[Link]</welcome-file>

</welcome-file-list>

</web-app>

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 99


Web Development with Java Lab – MCA Sem II

OUTPUT:

PRACTICAL NO. 06

Write a program to print ArrayIndexOutOfBound,


ArithmaticException, NullPointerException using isError Page &
errorPage.

CODE:

([Link])

<%@ page language="java"

contentType="text/html;charset=UTF-8"

errorPage="[Link]" %>

<!DOCTYPE html>

<html>

<body>

<h2>Exception Handling Demo</h2>

<form method="post">

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 100


Web Development with Java Lab – MCA Sem II

Enter Choice:

<br><br>

1 → ArrayIndexOutOfBoundsException

<br>

2 → ArithmeticException

<br>

3 → NullPointerException

<br><br>

<input type="text" name="type" required>

<br><br>

<input type="submit" value="Generate Exception">

</form>

<br>

<%

String input = [Link]("type");

if(input != null) {

int choice = [Link](input);

if(choice == 1) {

int arr[] = {1,2,3};

[Link](arr[10]);

else if(choice == 2) {

int x = 10 / 0;

[Link](x);

}
Bindhya Prakash Karkera | DY25SHSP0MCA054 | 101
Web Development with Java Lab – MCA Sem II

else if(choice == 3) {

String str = null;

[Link]([Link]());

else {

[Link]("<h3>Invalid Choice</h3>");

%>

</body>

</html>

CODE:

([Link])

<%@ page language="java"

contentType="text/html;charset=UTF-8"

isErrorPage="true" %>

<!DOCTYPE html>

<html>

<body>

<h2 style="color:red;">

Exception Occurred!

</h2>

<p>

<strong>Type:</strong>
Bindhya Prakash Karkera | DY25SHSP0MCA054 | 102
Web Development with Java Lab – MCA Sem II

<%= [Link]().getName() %>

</p>

<p>

<strong>Message:</strong>

<%= [Link]() %>

</p>

<br>

<a href="[Link]">

Go Back

</a>

</body>

</html>

OUTPUT:

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 103


Web Development with Java Lab – MCA Sem II

PRACTICAL NO. 07

Write a program in JSP code to use all page Directive attributes.

CODE:

([Link])

<%@ page

language="java"

contentType="text/html;charset=UTF-8"

pageEncoding="UTF-8"

import="[Link].*, [Link].*"

session="true"

buffer="8kb"

autoFlush="true"

info="This JSP demonstrates page directive attributes"

errorPage="[Link]"

isErrorPage="false"

%>

<!DOCTYPE html>

<html>

<head>

<title>JSP Page Directive Demo</title>

</head>

<body>

<h2>JSP Page Directive Example</h2>

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 104


Web Development with Java Lab – MCA Sem II

<%

Date date = new Date();

%>

<p>

Current Date & Time:

<%= date %>

</p>

<p>

Page Info:

<%= getServletInfo() %>

</p>

<p>

Session ID:

<%= [Link]() %>

</p>

</body>

</html>

CODE:

([Link])

<%@ page isErrorPage="true" %>

<!DOCTYPE html>

<html>

<body>

<h2 style="color:red;">
Bindhya Prakash Karkera | DY25SHSP0MCA054 | 105
Web Development with Java Lab – MCA Sem II

Error Occurred!

</h2>

<p>

<%= [Link]() %>

</p>

</body>

</html>

CODE:

([Link])

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="[Link]

xmlns:xsi="[Link]

xsi:schemaLocation="

[Link]

[Link]

version="3.1">

<welcome-file-list>

<welcome-file>[Link]</welcome-file>

</welcome-file-list>

</web-app>

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 106


Web Development with Java Lab – MCA Sem II

OUTPUT:

PRACTICAL NO. 08

Write a program in JSP to perform session tracking using Cookies.

CODE:

([Link])

<!DOCTYPE html>

<html>

<body>

<h2>Enter Your Name</h2>

<form action="[Link]" method="post">

Name:

<input type="text" name="username">

<br><br>

<input type="submit" value="Submit">

</form>

</body>

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 107


Web Development with Java Lab – MCA Sem II

</html>

CODE:

([Link])

<%@ page contentType="text/html; charset=UTF-8" %>

<%@ page import="[Link]" %>

<html>

<body>

<%

String name = [Link]("username");

if(name != null && ![Link]("")) {

Cookie c = new Cookie("user", name);

[Link](60 * 60);

[Link](c);

[Link]("<h3>Cookie created successfully!</h3>");

else {

[Link]("<h3>Please enter a valid name.</h3>");

%>

<br><br>

<a href="[Link]">

Go to Next Page

</a>

</body>
Bindhya Prakash Karkera | DY25SHSP0MCA054 | 108
Web Development with Java Lab – MCA Sem II

</html>

CODE:

([Link])

<%@ page contentType="text/html; charset=UTF-8" %>

<%@ page import="[Link]" %>

<html>

<body>

<h2>Welcome User</h2>

<%

Cookie cookies[] = [Link]();

String username = null;

if(cookies != null) {

for(int i = 0; i < [Link]; i++) {

if(cookies[i].getName().equals("user")) {

username = cookies[i].getValue();

if(username != null) {

[Link]("<h3>Hello, " + username + "</h3>");

else {

[Link]("<h3>No cookie found!</h3>");

}
Bindhya Prakash Karkera | DY25SHSP0MCA054 | 109
Web Development with Java Lab – MCA Sem II

%>

</body>

</html>

CODE:

([Link])

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="[Link]

xmlns:xsi="[Link]

xsi:schemaLocation="

[Link]

[Link]

version="3.1">

<welcome-file-list>

<welcome-file>[Link]</welcome-file>

</welcome-file-list>

</web-app>

OUTPUT:

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 110


Web Development with Java Lab – MCA Sem II

PRACTICAL NO. 09

Write a program in JSP to perform session tracking using HttpSession.

CODE:

([Link])

<!DOCTYPE html>

<html>

<body>

<h2>Enter Your Name</h2>

<form action="[Link]" method="post">

Name:

<input type="text" name="username">

<br><br>

<input type="submit" value="Submit">

</form>

</body>

</html>

CODE:

([Link])

<%@ page contentType="text/html; charset=UTF-8" %>

<html>

<body>

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 111


Web Development with Java Lab – MCA Sem II

<h2>Welcome User</h2>

<%

String username =

(String) [Link]("user");

if(username != null) {

[Link]("<h3>Hello, " + username + "</h3>");

else {

[Link]("<h3>Session not found!</h3>");

%>

</body>

</html>

CODE:

([Link])

<%@ page contentType="text/html; charset=UTF-8" %>

<html>

<body>

<%

String name = [Link]("username");

if(name != null && ![Link]("")) {

[Link]("user", name);

[Link]("<h3>Session created successfully!</h3>");

}
Bindhya Prakash Karkera | DY25SHSP0MCA054 | 112
Web Development with Java Lab – MCA Sem II

else {

[Link]("<h3>Please enter a valid name.</h3>");

%>

<br><br>

<a href="[Link]">

Go to Next Page

</a>

</body>

</html>

CODE:

([Link])

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="[Link]

xmlns:xsi="[Link]

xsi:schemaLocation="

[Link]

[Link]

version="3.1">

<welcome-file-list>

<welcome-file>[Link]</welcome-file>

</welcome-file-list>

</web-app>

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 113


Web Development with Java Lab – MCA Sem II

OUTPUT:

PRACTICAL NO. 10

Write a program in JSP to perform login functionality if login is


correctly redirected to another page with message Welcome User
otherwise revert back to login page again using database.

CODE:

([Link])

<html>

<body>

<h2>Login Page</h2>

<form action="[Link]" method="post">

Username:

<input type="text" name="uname">

<br><br>

Password:

<input type="password" name="pass">


Bindhya Prakash Karkera | DY25SHSP0MCA054 | 114
Web Development with Java Lab – MCA Sem II

<br><br>

<input type="submit" value="Login">

</form>

</body>

</html>

CODE:

([Link])

<%@ page import="[Link].*" %>

<html>

<body>

<%

String user = (String) [Link]("user");

if(user != null) {

%>

<h2>Welcome <%= user %> 🎉</h2>

<%

} else {

[Link]("[Link]");

%>

</body>

</html>

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 115


Web Development with Java Lab – MCA Sem II

CODE:

([Link])

<%@ page import="[Link].*" %>

<%

String uname = [Link]("uname");

String pass = [Link]("pass");

try {

[Link]("[Link]");

Connection con = [Link](

"jdbc:mysql://localhost:3306/jspdb",

"root",

"YOUR_PASSWORD"

);

PreparedStatement ps = [Link](

"SELECT * FROM users WHERE username=? AND password=?"

);

[Link](1, uname);

[Link](2, pass);

ResultSet rs = [Link]();

if([Link]()) {

[Link]("user", uname);

[Link]("[Link]");

} else {

[Link]("[Link]");
Bindhya Prakash Karkera | DY25SHSP0MCA054 | 116
Web Development with Java Lab – MCA Sem II

[Link]();

} catch(Exception e) {

[Link]("Error: " + e);

%>

CODE:

([Link])

<web-app>

<welcome-file-list>

<welcome-file>[Link]</welcome-file>

</welcome-file-list>

</web-app>

OUTPUT:

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 117


Web Development with Java Lab – MCA Sem II

PRACTICAL NO. 11

Write a program in JSP to perform Crud operation on emp(eid, ename,


sal, dept) with help of MySql database.

CODE:

([Link])

<%@ page import="[Link].*" %>

<%

Connection con = null;

try {

[Link]("[Link]");

con = [Link](

"jdbc:mysql://localhost:3306/mydatabase",

"root",

"123456"

);

} catch(Exception e) {

[Link](e);

%>

CODE:

([Link])

<html>

<body>
Bindhya Prakash Karkera | DY25SHSP0MCA054 | 118
Web Development with Java Lab – MCA Sem II

<h2>Employee CRUD System</h2>

<a href="[Link]">Insert Employee</a><br><br>

<a href="[Link]">View Employees</a><br><br>

</body>

</html>

CODE:

([Link])

<%@ include file="[Link]" %>

<html>

<body>

<h2>Insert Employee</h2>

<form method="post">

ID: <input type="text" name="eid"><br><br>

Name: <input type="text" name="ename"><br><br>

Salary: <input type="text" name="sal"><br><br>

Dept: <input type="text" name="dept"><br><br>

<input type="submit" value="Insert">

</form>

<%

if([Link]("eid") != null) {

int eid = [Link]([Link]("eid"));

String ename = [Link]("ename");

double sal = [Link]([Link]("sal"));

String dept = [Link]("dept");


Bindhya Prakash Karkera | DY25SHSP0MCA054 | 119
Web Development with Java Lab – MCA Sem II

PreparedStatement ps = [Link](

"INSERT INTO emp VALUES(?,?,?,?)"

);

[Link](1, eid);

[Link](2, ename);

[Link](3, sal);

[Link](4, dept);

[Link]();

[Link]("<h3>Inserted Successfully!</h3>");

%>

<br>

<a href="[Link]">View Employees</a>

</body>

</html>

CODE:

([Link])

<%@ include file="[Link]" %>

<html>

<body>

<h2>Employee List</h2>

<table border="1">

<tr>

<th>ID</th>
Bindhya Prakash Karkera | DY25SHSP0MCA054 | 120
Web Development with Java Lab – MCA Sem II

<th>Name</th>

<th>Salary</th>

<th>Dept</th>

<th>Action</th>

</tr>

<%

Statement st = [Link]();

ResultSet rs = [Link]("SELECT * FROM emp");

while([Link]()) {

%>

<tr>

<td><%= [Link](1) %></td>

<td><%= [Link](2) %></td>

<td><%= [Link](3) %></td>

<td><%= [Link](4) %></td>

<td>

<a href="[Link]?eid=<%= [Link](1) %>">Edit</a> |

<a href="[Link]?eid=<%= [Link](1) %>">Delete</a>

</td>

</tr>

<%

%>

</table>

<br>
Bindhya Prakash Karkera | DY25SHSP0MCA054 | 121
Web Development with Java Lab – MCA Sem II

<a href="[Link]">Add Employee</a>

</body>

</html>

CODE:

([Link])

<%@ include file="[Link]" %>

<%

int eid = [Link]([Link]("eid"));

PreparedStatement ps = [Link](

"DELETE FROM emp WHERE eid=?"

);

[Link](1, eid);

[Link]();

[Link]("[Link]");

%>

CODE:

([Link])

<%@ include file="[Link]" %>

<%

int eid = [Link]([Link]("eid"));

String name = "";

double sal = 0;

String dept = "";


Bindhya Prakash Karkera | DY25SHSP0MCA054 | 122
Web Development with Java Lab – MCA Sem II

PreparedStatement ps1 = [Link](

"SELECT * FROM emp WHERE eid=?"

);

[Link](1, eid);

ResultSet rs = [Link]();

if([Link]()) {

name = [Link](2);

sal = [Link](3);

dept = [Link](4);

%>

<html>

<body>

<h2>Update Employee</h2>

<form method="post">

Name:

<input type="text" name="ename" value="<%= name %>"><br><br>

Salary:

<input type="text" name="sal" value="<%= sal %>"><br><br>

Dept:

<input type="text" name="dept" value="<%= dept %>"><br><br>

<input type="submit" value="Update">

</form>

<%
Bindhya Prakash Karkera | DY25SHSP0MCA054 | 123
Web Development with Java Lab – MCA Sem II

if([Link]("ename") != null) {

String ename = [Link]("ename");

double salary = [Link]([Link]("sal"));

String d = [Link]("dept");

PreparedStatement ps2 = [Link](

"UPDATE emp SET ename=?, sal=?, dept=? WHERE eid=?"

);

[Link](1, ename);

[Link](2, salary);

[Link](3, d);

[Link](4, eid);

[Link]();

[Link]("[Link]");

%>

</body>

</html>

OUTPUT:

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 124


Web Development with Java Lab – MCA Sem II

UNIT 4 – SPRING BOOT AND RESTFUL WEB SERVICES


UNIT 5 – DATA PERSISTENCE, TRANSACTIONS AND
TESTING

PRACTICAL NO. 01

Implement Inversion of Control using Spring container with package


ioc and inside create classes and xml file.

CODE:

([Link])

<project xmlns="[Link]

xmlns:xsi="[Link]

xsi:schemaLocation="

[Link]

[Link]

<modelVersion>4.0.0</modelVersion>

<groupId>[Link]</groupId>

<artifactId>SpringIoCExample</artifactId>

<version>1.0-SNAPSHOT</version>

<dependencies>

<!-- Spring Context -->

<dependency>

<groupId>[Link]</groupId>

<artifactId>spring-context</artifactId>

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 125


Web Development with Java Lab – MCA Sem II

<version>5.3.30</version>

</dependency>

</dependencies>

</project>

CODE:

([Link])

package ioc;

public class MessageService {

public void sendMessage() {

[Link]("Message Sent using Spring IoC!");

CODE:

([Link])

package ioc;

public class Application {

private MessageService service;

public void setService(MessageService service) {

[Link] = service;

public void processMessage() {

[Link]();

}
Bindhya Prakash Karkera | DY25SHSP0MCA054 | 126
Web Development with Java Lab – MCA Sem II

CODE:

([Link])

package ioc;

import [Link];

import [Link];

public class MainApp {

public static void main(String[] args) {

ApplicationContext context =

new ClassPathXmlApplicationContext("[Link]");

Application app = (Application) [Link]("app");

[Link]();

CODE:

([Link])

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="[Link]

xmlns:xsi="[Link]

xsi:schemaLocation="

[Link]

[Link]

<!-- Bean Definition -->


Bindhya Prakash Karkera | DY25SHSP0MCA054 | 127
Web Development with Java Lab – MCA Sem II

<bean id="messageService" class="[Link]" />

<!-- Dependency Injection -->

<bean id="app" class="[Link]">

<property name="service" ref="messageService"/>

</bean>

</beans>

OUTPUT:

PRACTICAL NO. 02

Demonstrate Dependency Injection using constructor and setter


methods

CODE:

([Link])

<project xmlns="[Link]

xmlns:xsi="[Link]

xsi:schemaLocation="

[Link]

[Link]

<modelVersion>4.0.0</modelVersion>

<groupId>[Link]</groupId>

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 128


Web Development with Java Lab – MCA Sem II

<artifactId>di-demo</artifactId>

<version>0.0.1-SNAPSHOT</version>

<dependencies>

<!-- Spring Context -->

<dependency>

<groupId>[Link]</groupId>

<artifactId>spring-context</artifactId>

<version>5.3.30</version>

</dependency>

</dependencies>

</project>

CODE:

([Link])

package ioc;

public class Engine {

public void start() {

[Link]("Engine started");

CODE:

([Link])

package ioc;

public class Car {

private Engine engine;


Bindhya Prakash Karkera | DY25SHSP0MCA054 | 129
Web Development with Java Lab – MCA Sem II

public void setEngine(Engine engine) {

[Link] = engine;

public void drive() {

[Link]();

[Link]("Car running using Setter Injection");

CODE:

([Link])

package ioc;

public class CarConstructor {

private Engine engine;

public CarConstructor(Engine engine) {

[Link] = engine;

public void drive() {

[Link]();

[Link]("Car running using Constructor Injection");

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 130


Web Development with Java Lab – MCA Sem II

CODE:

([Link])

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="[Link]

xmlns:xsi="[Link]

xsi:schemaLocation="

[Link]

[Link]

<!-- Common Dependency -->

<bean id="engine" class="[Link]"/>

<!-- Setter Injection -->

<bean id="car" class="[Link]">

<property name="engine" ref="engine"/>

</bean>

<!-- Constructor Injection -->

<bean id="carConstructor" class="[Link]">

<constructor-arg ref="engine"/>

</bean>

</beans>

CODE:

([Link])

package ioc;

import [Link];

import [Link];
Bindhya Prakash Karkera | DY25SHSP0MCA054 | 131
Web Development with Java Lab – MCA Sem II

public class MainApp {

public static void main(String[] args) {

ApplicationContext context =

new ClassPathXmlApplicationContext("[Link]");

Car car = (Car) [Link]("car");

[Link]();

CarConstructor car2 =

(CarConstructor) [Link]("carConstructor");

[Link]();

OUTPUT:

PRACTICAL NO. 03

Write a program to demonstrate Dependency Injection using setter


methods.

CODE:

([Link])

<project xmlns="[Link]

xmlns:xsi="[Link]
Bindhya Prakash Karkera | DY25SHSP0MCA054 | 132
Web Development with Java Lab – MCA Sem II

xsi:schemaLocation="

[Link]

[Link]

<modelVersion>4.0.0</modelVersion>

<groupId>[Link]</groupId>

<artifactId>SetterDIExample</artifactId>

<version>1.0-SNAPSHOT</version>

<dependencies>

<!-- Spring Context -->

<dependency>

<groupId>[Link]</groupId>

<artifactId>spring-context</artifactId>

<version>5.3.30</version>

</dependency>

</dependencies>

</project>

CODE:

([Link])

package ioc;

public class Engine {

public void start() {

[Link]("Engine started...");

}
Bindhya Prakash Karkera | DY25SHSP0MCA054 | 133
Web Development with Java Lab – MCA Sem II

CODE:

([Link])

package ioc;

public class Car {

private Engine engine;

public void setEngine(Engine engine) {

[Link] = engine;

public void drive() {

[Link]();

[Link]("Car is running...");

CODE:

([Link])

package ioc;

import [Link];

import [Link];

public class MainApp {

public static void main(String[] args) {

ApplicationContext context =

new ClassPathXmlApplicationContext("[Link]");

Car car = (Car) [Link]("car");


Bindhya Prakash Karkera | DY25SHSP0MCA054 | 134
Web Development with Java Lab – MCA Sem II

[Link]();

CODE:

([Link])

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="[Link]

xmlns:xsi="[Link]

xsi:schemaLocation="

[Link]

[Link]

<!-- Engine Bean -->

<bean id="engine" class="[Link]"/>

<!-- Car Bean using Setter Injection -->

<bean id="car" class="[Link]">

<property name="engine" ref="engine"/>

</bean>

</beans>

OUTPUT:

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 135


Web Development with Java Lab – MCA Sem II

PRACTICAL NO. 04

Write a program to demonstrate Dependency Injection using


constructor and setter methods using annotations.

CODE:

([Link])

<project xmlns="[Link]

xmlns:xsi=[Link]

xsi:schemaLocation="

[Link]

[Link]

<modelVersion>4.0.0</modelVersion>

<groupId>[Link]</groupId>

<artifactId>AnnotationDIExample</artifactId>

<version>1.0-SNAPSHOT</version>

<dependencies>

<!-- Spring Context -->

<dependency>

<groupId>[Link]</groupId>

<artifactId>spring-context</artifactId>

<version>5.3.30</version>

</dependency>

</dependencies>

</project>

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 136


Web Development with Java Lab – MCA Sem II

CODE:

([Link])

package [Link];

import [Link];

@Component

public class Student {

private String name = "John";

public String getName() {

return name;

CODE:

([Link])

package [Link];

import [Link];

import [Link];

@Component

public class CollegeConstructor {

private Student student;

@Autowired

public CollegeConstructor(Student student) {

[Link] = student;

public void display() {


Bindhya Prakash Karkera | DY25SHSP0MCA054 | 137
Web Development with Java Lab – MCA Sem II

[Link]("Constructor Injection:");

[Link]("Student Name: " + [Link]());

CODE:

([Link])

package [Link];

import [Link];

import [Link];

@Component

public class CollegeSetter {

private Student student;

@Autowired

public void setStudent(Student student) {

[Link] = student;

public void display() {

[Link]("Setter Injection:");

[Link]("Student Name: " + [Link]());

CODE:

([Link])
Bindhya Prakash Karkera | DY25SHSP0MCA054 | 138
Web Development with Java Lab – MCA Sem II

package [Link];

import [Link];

import [Link];

@Configuration

@ComponentScan(basePackages = "[Link]")

public class AppConfig {

CODE:

([Link])

package [Link];

import [Link];

import [Link];

public class MainApp {

public static void main(String[] args) {

ApplicationContext context =

new AnnotationConfigApplicationContext([Link]);

CollegeConstructor cc =

[Link]([Link]);

[Link]();

CollegeSetter cs =

[Link]([Link]);

[Link]();

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 139


Web Development with Java Lab – MCA Sem II

OUTPUT:

PRACTICAL NO. 05

Write a program to Create a basic Spring Boot application using Spring


Initializer or STS and print “My First Spring Application”.

CODE:

([Link])

package [Link];

import [Link];

import [Link];

@SpringBootApplication

public class FirstappApplication {

public static void main(String[] args) {

[Link]([Link], args);

[Link]("My First Spring Application");

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 140


Web Development with Java Lab – MCA Sem II

OUTPUT:

PRACTICAL NO. 06

Write a program to build a simple application with layered architecture


of spring boot without a database. Use concept of Collection interface

CODE:

([Link])

package [Link];

public class Student {

private int id;

private String name;

private String course;

public Student() {

public Student(int id, String name, String course) {

[Link] = id;

[Link] = name;

[Link] = course;

}
Bindhya Prakash Karkera | DY25SHSP0MCA054 | 141
Web Development with Java Lab – MCA Sem II

public int getId() {

return id;

public void setId(int id) {

[Link] = id;

public String getName() {

return name;

public void setName(String name) {

[Link] = name;

public String getCourse() {

return course;

public void setCourse(String course) {

[Link] = course;

CODE:

([Link])

package [Link];

public class Student {

private int id;


Bindhya Prakash Karkera | DY25SHSP0MCA054 | 142
Web Development with Java Lab – MCA Sem II

private String name;

private String course;

public Student() {

public Student(int id, String name, String course) {

[Link] = id;

[Link] = name;

[Link] = course;

public int getId() {

return id;

public void setId(int id) {

[Link] = id;

public String getName() {

return name;

public void setName(String name) {

[Link] = name;

public String getCourse() {

return course;

public void setCourse(String course) {


Bindhya Prakash Karkera | DY25SHSP0MCA054 | 143
Web Development with Java Lab – MCA Sem II

[Link] = course;

CODE:

([Link])

package [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

@Service

public class StudentService {

@Autowired

private StudentRepository repository;

public List<Student> getAllStudents() {

return [Link]();

public Student getStudentById(int id) {

return [Link](id);

public Student addStudent(Student student) {

return [Link](student);

}
Bindhya Prakash Karkera | DY25SHSP0MCA054 | 144
Web Development with Java Lab – MCA Sem II

public Student updateStudent(int id, Student student) {

return [Link](id, student);

public boolean deleteStudent(int id) {

return [Link](id);

CODE:

([Link])

package [Link];

import [Link];

import [Link];

import [Link].*;

import [Link];

import [Link];

@RestController

@RequestMapping("/students")

public class StudentController {

@Autowired

private StudentService service;

@GetMapping

public List<Student> getAllStudents() {

return [Link]();

}
Bindhya Prakash Karkera | DY25SHSP0MCA054 | 145
Web Development with Java Lab – MCA Sem II

@GetMapping("/{id}")

public Student getStudent(@PathVariable int id) {

return [Link](id);

@PostMapping

public Student addStudent(@RequestBody Student student) {

return [Link](student);

@PutMapping("/{id}")

public Student updateStudent(@PathVariable int id,

@RequestBody Student student) {

return [Link](id, student);

@DeleteMapping("/{id}")

public String deleteStudent(@PathVariable int id) {

boolean deleted = [Link](id);

if (deleted) {

return "Student Deleted";

} else {

return "Student Not Found";

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 146


Web Development with Java Lab – MCA Sem II

CODE:

([Link])

package [Link];

import [Link];

import [Link];

@SpringBootApplication

public class StudentAppApplication {

public static void main(String[] args) {

[Link]([Link], args);

[Link]("Student Application Started");

OUTPUT:

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 147


Web Development with Java Lab – MCA Sem II

PRACTICAL NO. 07

Write a program to build a simple application with layered architecture


of spring boot with database eg. dbemp Table emp (eid, ename, sal,
dept)

CODE:

([Link])

[Link]=jdbc:mysql://localhost:3306/dbemp?useSSL=false&allowPublicKe
yRetrieval=true&serverTimezone=UTC

[Link]=root

[Link]=root

[Link]-auto=update

[Link]-sql=true

[Link]=[Link]

[Link]=9090

CODE:

([Link])

package [Link];

import [Link].*;

@Entity

@Table(name = "emp")

public class Emp {

@Id

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 148


Web Development with Java Lab – MCA Sem II

@GeneratedValue(strategy = [Link])

private Integer eid;

private String ename;

private double sal;

private String dept;

public Emp() {

public Emp(Integer eid, String ename, double sal, String dept) {

[Link] = eid;

[Link] = ename;

[Link] = sal;

[Link] = dept;

public Integer getEid() {

return eid;

public void setEid(Integer eid) {

[Link] = eid;

public String getEname() {

return ename;

public void setEname(String ename) {

[Link] = ename;

}
Bindhya Prakash Karkera | DY25SHSP0MCA054 | 149
Web Development with Java Lab – MCA Sem II

public double getSal() {

return sal;

public void setSal(double sal) {

[Link] = sal;

public String getDept() {

return dept;

public void setDept(String dept) {

[Link] = dept;

CODE:

([Link])

package [Link];

import [Link];

import [Link];

import [Link];

@Repository

public interface EmpRepository extends JpaRepository<Emp, Integer> {

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 150


Web Development with Java Lab – MCA Sem II

CODE:

([Link])

package [Link];

import [Link];

import [Link];

public interface EmpService {

Emp saveEmp(Emp emp);

List<Emp> getAllEmp();

Emp getEmpById(int id);

Emp updateEmp(int id, Emp emp);

void deleteEmp(int id);

CODE:

([Link])

package [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

@Service

public class EmpServiceImpl implements EmpService {

@Autowired
Bindhya Prakash Karkera | DY25SHSP0MCA054 | 151
Web Development with Java Lab – MCA Sem II

private EmpRepository repo;

@Override

public Emp saveEmp(Emp emp) {

return [Link](emp);

@Override

public List<Emp> getAllEmp() {

return [Link]();

@Override

public Emp getEmpById(int id) {

return [Link](id).orElse(null);

@Override

public Emp updateEmp(int id, Emp emp) {

Emp existing = [Link](id).orElse(null);

if (existing != null) {

[Link]([Link]());

[Link]([Link]());

[Link]([Link]());

return [Link](existing);

return null;

@Override
Bindhya Prakash Karkera | DY25SHSP0MCA054 | 152
Web Development with Java Lab – MCA Sem II

public void deleteEmp(int id) {

[Link](id);

CODE:

([Link])

package [Link];

import [Link];

import [Link];

import [Link].*;

import [Link];

import [Link];

@RestController

@RequestMapping("/api/emp")

public class EmpController {

@Autowired

private EmpService service;

@PostMapping

public Emp createEmp(@RequestBody Emp emp) {

return [Link](emp);

@GetMapping

public List<Emp> getAll() {

return [Link]();
Bindhya Prakash Karkera | DY25SHSP0MCA054 | 153
Web Development with Java Lab – MCA Sem II

@GetMapping("/{id}")

public Emp getById(@PathVariable int id) {

return [Link](id);

@PutMapping("/{id}")

public Emp updateEmp(@PathVariable int id,

@RequestBody Emp emp) {

return [Link](id, emp);

@DeleteMapping("/{id}")

public String deleteEmp(@PathVariable int id) {

[Link](id);

return "Employee deleted successfully";

CODE:

( [Link])

package [Link];

import [Link];

import [Link];

@SpringBootApplication

public class DbempApplication {

public static void main(String[] args) {


Bindhya Prakash Karkera | DY25SHSP0MCA054 | 154
Web Development with Java Lab – MCA Sem II

[Link]("DBEMP Application Started");

[Link]([Link], args);

OUTPUT:

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 155


Web Development with Java Lab – MCA Sem II

PRACTICAL NO. 08

Write a program to build application to handle Exception Handling in


Spring Boot

CODE:

([Link])

package [Link];

public class User {

private int id;

private String name;

public User(int id, String name) {

[Link] = id;

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 156


Web Development with Java Lab – MCA Sem II

[Link] = name;

public int getId() {

return id;

public String getName() {

return name;

CODE:

([Link])

package [Link];

public class UserNotFoundException extends RuntimeException {

public UserNotFoundException(String message) {

super(message);

CODE:

([Link])

package [Link];

import [Link];

import [Link];

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 157


Web Development with Java Lab – MCA Sem II

import [Link];

import [Link];

import [Link];

@Service

public class UserService {

private static List<User> users = new ArrayList<>();

static {

[Link](new User(1, "Amit"));

[Link](new User(2, "Sara"));

public User getUserById(int id) {

return [Link]()

.filter(u -> [Link]() == id)

.findFirst()

.orElseThrow(() ->

new UserNotFoundException(

"User not found with id: " + id));

CODE:

([Link])

package [Link];

import [Link];

import [Link].*;
Bindhya Prakash Karkera | DY25SHSP0MCA054 | 158
Web Development with Java Lab – MCA Sem II

import [Link];

import [Link];

@RestController

@RequestMapping("/users")

public class UserController {

@Autowired

private UserService userService;

@GetMapping("/{id}")

public User getUser(@PathVariable int id) {

return [Link](id);

CODE:

([Link])

package [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link].*;

@ControllerAdvice

public class GlobalExceptionHandler {

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 159


Web Development with Java Lab – MCA Sem II

@ExceptionHandler([Link])

public ResponseEntity<Object> handleUserNotFound(

UserNotFoundException ex) {

Map<String, Object> body = new HashMap<>();

[Link]("timestamp", [Link]());

[Link]("message", [Link]());

[Link]("status", HttpStatus.NOT_FOUND.value());

return new ResponseEntity<>(body,

HttpStatus.NOT_FOUND);

@ExceptionHandler([Link])

public ResponseEntity<Object> handleOtherExceptions(

Exception ex) {

Map<String, Object> body = new HashMap<>();

[Link]("timestamp", [Link]());

[Link]("message", "Something went wrong");

[Link]("error", [Link]());

return new ResponseEntity<>(body,

HttpStatus.INTERNAL_SERVER_ERROR);

CODE:

([Link])

package [Link];
Bindhya Prakash Karkera | DY25SHSP0MCA054 | 160
Web Development with Java Lab – MCA Sem II

import [Link];

import [Link];

@SpringBootApplication

public class ExceptiondemoApplication {

public static void main(String[] args) {

[Link]("Exception Handling App Started");

[Link](

[Link],

args);

OUTPUT:

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 161


Web Development with Java Lab – MCA Sem II

PRACTICAL NO. 09
Write a program to build a simple application of spring boot with
database eg.
dbemp. Table emp (eid, ename, sal, dept) and perform testing using
Junit.

CODE:

([Link])

package [Link];
Bindhya Prakash Karkera | DY25SHSP0MCA054 | 162
Web Development with Java Lab – MCA Sem II

import [Link].*;

@Entity

@Table(name = "emp")

public class Emp {

@Id

@GeneratedValue(strategy = [Link])

private Integer eid;

private String ename;

private double sal;

private String dept;

public Emp() {

public Emp(Integer eid, String ename,

double sal, String dept) {

[Link] = eid;

[Link] = ename;

[Link] = sal;

[Link] = dept;

public Integer getEid() {

return eid;

public void setEid(Integer eid) {

[Link] = eid;

}
Bindhya Prakash Karkera | DY25SHSP0MCA054 | 163
Web Development with Java Lab – MCA Sem II

public String getEname() {

return ename;

public void setEname(String ename) {

[Link] = ename;

public double getSal() {

return sal;

public void setSal(double sal) {

[Link] = sal;

public String getDept() {

return dept;

public void setDept(String dept) {

[Link] = dept;

CODE:

([Link])

[Link]=EmpSpringBoot

[Link]=9393

[Link]=jdbc:mysql://localhost:3306/dbemp
Bindhya Prakash Karkera | DY25SHSP0MCA054 | 164
Web Development with Java Lab – MCA Sem II

[Link]=root

[Link]=root

[Link]-auto=update

[Link]-sql=true

[Link]=[Link].MySQL8Dialect

CODE:

([Link])

package [Link];

import [Link];

import [Link];

public interface EmpRepository

extends JpaRepository<Emp, Integer> {

CODE:

([Link])

package [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

@Service

public class EmpService {


Bindhya Prakash Karkera | DY25SHSP0MCA054 | 165
Web Development with Java Lab – MCA Sem II

@Autowired

private EmpRepository repo;

public Emp saveEmp(Emp e) {

return [Link](e);

public List<Emp> getAllEmp() {

return [Link]();

public Emp getEmpById(int id) {

return [Link](id).orElse(null);

public void deleteEmp(int id) {

[Link](id);

CODE:

([Link])

package [Link];

import [Link];

import [Link];

import [Link].*;

import [Link];

import [Link];

@RestController
Bindhya Prakash Karkera | DY25SHSP0MCA054 | 166
Web Development with Java Lab – MCA Sem II

@RequestMapping("/emp")

public class EmpController {

@Autowired

private EmpService service;

@PostMapping("/add")

public Emp addEmp(@RequestBody Emp e) {

return [Link](e);

@GetMapping("/all")

public List<Emp> getAll() {

return [Link]();

@GetMapping("/{id}")

public Emp getById(@PathVariable int id) {

return [Link](id);

@DeleteMapping("/{id}")

public String delete(@PathVariable int id) {

[Link](id);

return "Deleted successfully";

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 167


Web Development with Java Lab – MCA Sem II

CODE:

([Link])

package [Link];

import [Link];

import [Link];

@SpringBootApplication

public class DbemApplication {

public static void main(String[] args) {

[Link]("JUnit Project Started");

[Link](

[Link],

args);

OUTPUT:

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 168


Web Development with Java Lab – MCA Sem II

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 169


Web Development with Java Lab – MCA Sem II

UNIT 6 – REACT JS FRONTEND

PRACTICAL NO. 01

Write a React Program using Components and JSX.

CODE:

([Link])

function Welcome() {

return (

<div>

<h1>Welcome to React JS</h1>

<h2>My First React Program</h2>

<p>This is JSX Example</p>

</div>

);

export default Welcome;

CODE:

([Link])

import Welcome from './Welcome';

function App() {

return (

<div>

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 170


Web Development with Java Lab – MCA Sem II

<Welcome />

</div>

);

export default App;

OUTPUT:

PRACTICAL NO. 02

Write a React Program using State in Class Components.

CODE:

([Link])

import React, { Component } from 'react';

class Counter extends Component {

constructor() {

super();
Bindhya Prakash Karkera | DY25SHSP0MCA054 | 171
Web Development with Java Lab – MCA Sem II

[Link] = {

count: 0

};

increaseCount = () => {

[Link]({

count: [Link] + 1

});

};

render() {

return (

<div>

<h1>React State Example</h1>

<h2>Count: {[Link]}</h2>

<button onClick={[Link]}>

Increase

</button>

</div>

);

export default Counter;

CODE:

([Link])
Bindhya Prakash Karkera | DY25SHSP0MCA054 | 172
Web Development with Java Lab – MCA Sem II

import Counter from './Counter';


function App() {
return (
<div>
<Counter />
</div>
);
}

export default App;

OUTPUT:

PRACTICAL NO. 03

Write a React Program using Props to print student information.

CODE:

([Link])

function Student(props) {
return (
<div>
<h1>Student Information</h1>

<h2>Name: {[Link]}</h2>

<h2>Age: {[Link]}</h2>

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 173


Web Development with Java Lab – MCA Sem II

<h2>Course: {[Link]}</h2>
</div>
);
}

export default Student;

OUTPUT:

PRACTICAL NO. 04

Write a React Program for Event Handling.

CODE:

([Link])

function EventDemo() {

function showMessage() {

alert("Hello Button Clicked!");

return (

<div>

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 174


Web Development with Java Lab – MCA Sem II

<h1>React Event Handling</h1>

<button onClick={showMessage}>

Click Me

</button>

</div>

);

export default EventDemo;

CODE:

([Link])

import EventDemo from './EventDemo';

function App() {

return (

<div>

<EventDemo />

</div>

);

export default App;

OUTPUT:

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 175


Web Development with Java Lab – MCA Sem II

PRACTICAL NO. 05

Write a React Program for Forms Handling using useState and


useEffect.

CODE:

([Link])

import React, { useState, useEffect } from 'react';

function FormDemo() {

const [name, setName] = useState("");

const [course, setCourse] = useState("");

useEffect(() => {

alert("Form Component Loaded");

}, []);

const handleSubmit = (event) => {

[Link]();

alert(

"Name: " + name +

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 176


Web Development with Java Lab – MCA Sem II

"\nCourse: " + course

);

};

return (

<div>

<h1>React Form Handling</h1>

<form onSubmit={handleSubmit}>

<label>Name:</label>

<br />

<input

type="text"

value={name}

onChange={(e) =>

setName([Link])

/>

<br /><br />

<label>Course:</label>

<br />

<input

type="text"

value={course}

onChange={(e) =>

setCourse([Link])

}
Bindhya Prakash Karkera | DY25SHSP0MCA054 | 177
Web Development with Java Lab – MCA Sem II

/>

<br /><br />

<button type="submit">

Submit

</button>

</form>

</div>

);

export default FormDemo;

CODE:

([Link])

import FormDemo from './FormDemo';

function App() {

return (

<div>

<FormDemo />

</div>

);

export default App;

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 178


Web Development with Java Lab – MCA Sem II

OUTPUT:

PRACTICAL NO. 06

Write a React Program using Lists using array mapping.

CODE:

([Link])

function ListDemo() {

const students = [

"Amit",

"Rahul",

"Sara",

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 179


Web Development with Java Lab – MCA Sem II

"Neha"

];

return (

<div>

<h1>Student List</h1>

<ul>

{[Link]((student, index) => (

<li key={index}>

{student}

</li>

))}

</ul>

</div>

);

export default ListDemo;

CODE:

([Link])

import ListDemo from './ListDemo';

function App() {

return (

<div>

<ListDemo />
Bindhya Prakash Karkera | DY25SHSP0MCA054 | 180
Web Development with Java Lab – MCA Sem II

</div>

);

export default App;

OUTPUT:

PRACTICAL NO. 07

Write a React Program using Conditional Rendering.

CODE:

([Link])

import React, { useState } from 'react';

function ConditionalDemo() {

const [isLoggedIn, setIsLoggedIn] = useState(false);

return (

<div>

<h1>Conditional Rendering Example</h1>

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 181


Web Development with Java Lab – MCA Sem II

isLoggedIn ?

<h2>Welcome User</h2>

<h2>Please Login</h2>

<button

onClick={() => setIsLoggedIn(true)}

>

Login

</button>

</div>

);

export default ConditionalDemo;

CODE:

([Link])

import ConditionalDemo from './ConditionalDemo';

function App() {

return (

<div>

<ConditionalDemo />

</div>

);

export default App;


Bindhya Prakash Karkera | DY25SHSP0MCA054 | 182
Web Development with Java Lab – MCA Sem II

OUTPUT:

PRACTICAL NO. 08

Write a React Program for REST API Integration.

CODE:

([Link])

import React, { useEffect, useState } from 'react';

function ApiDemo() {

const [users, setUsers] = useState([]);

useEffect(() => {

fetch('[Link]

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 183


Web Development with Java Lab – MCA Sem II

.then((response) => [Link]())

.then((data) => {

setUsers(data);

});

}, []);

return (

<div>

<h1>REST API Integration</h1>

<ul>

{[Link]((user) => (

<li key={[Link]}>

{[Link]}

</li>

))}

</ul>

</div>

);

export default ApiDemo;

CODE:

([Link])

import ApiDemo from './ApiDemo';

function App() {

return (
Bindhya Prakash Karkera | DY25SHSP0MCA054 | 184
Web Development with Java Lab – MCA Sem II

<div>

<ApiDemo />

</div>

);

export default App;

OUTPUT:

PRACTICAL NO. 10

Write a React Program for Search Filter to search particular keyword


form Array set.

CODE:

([Link])

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 185


Web Development with Java Lab – MCA Sem II

import React, { useState } from 'react';

function SearchFilter() {

const students = [

"Diya",

"Bindhya",

"Deba",

"Bigi",

"Saumen",

"Shravani"

];

const [search, setSearch] = useState("");

const filteredStudents = [Link]((student) =>

[Link]().includes([Link]())

);

return (

<div>

<h1>Search Filter Example</h1>

<input

type="text"

placeholder="Search Student"

value={search}

onChange={(e) => setSearch([Link])}

<ul>

{[Link]((student, index) => (


Bindhya Prakash Karkera | DY25SHSP0MCA054 | 186
Web Development with Java Lab – MCA Sem II

<li key={index}>

{student}

</li>

))}

</ul>

</div>

);

export default SearchFilter;

CODE:

([Link])

import SearchFilter from './SearchFilter';

function App() {

return (

<div>

<SearchFilter />

</div>

);

export default App;

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 187


Web Development with Java Lab – MCA Sem II

OUTPUT:

PRACTICAL NO. 10

Write a React Program for To-Do List Application.

CODE:

([Link])

import React, { useState } from 'react';

function TodoApp() {

const [task, setTask] = useState("");

const [tasks, setTasks] = useState([]);

const addTask = () => {


Bindhya Prakash Karkera | DY25SHSP0MCA054 | 188
Web Development with Java Lab – MCA Sem II

if (task !== "") {

setTasks([...tasks, task]);

setTask("");

};

return (

<div>

<h1>To-Do List Application</h1

<input

type="text"

placeholder="Enter Task"

value={task}

onChange={(e) => setTask([Link])}

/>

<button onClick={addTask}>

Add

</button>

<ul>

{[Link]((item, index) => (

<li key={index}>

{item}

</li>

))}

</ul>

</div>
Bindhya Prakash Karkera | DY25SHSP0MCA054 | 189
Web Development with Java Lab – MCA Sem II

);

export default TodoApp;

CODE:

([Link])

import TodoApp from './TodoApp';

function App() {

return (

<div>

<TodoApp />

</div>

);

export default App;

OUTPUT:

PRACTICAL NO. 11

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 190


Web Development with Java Lab – MCA Sem II

Write a React Program for connecting database in spring boot and


frontend in React.

CODE:

([Link])

package [Link];

import [Link].*;

@Entity

public class Student {

@Id

@GeneratedValue(strategy = [Link])

private int id;

private String name;

private String course;

public Student() {

public Student(int id, String name, String course) {

[Link] = id;

[Link] = name;

[Link] = course;

public int getId() {

return id;

public void setId(int id) {

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 191


Web Development with Java Lab – MCA Sem II

[Link] = id;

public String getName() {

return name;

public void setName(String name) {

[Link] = name;

public String getCourse() {

return course;

public void setCourse(String course)

[Link] = course;

CODE:

([Link])

package [Link];

import [Link];

import [Link];

public interface StudentRepository

extends JpaRepository<Student, Integer> {

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 192


Web Development with Java Lab – MCA Sem II

CODE:

([Link])

package [Link];

import [Link];

import [Link];

import [Link].*;

import [Link];

import [Link];

@CrossOrigin(origins = "[Link]

@RestController

public class StudentController {

@Autowired

private StudentRepository repo;

@GetMapping("/students")

public List<Student> getStudents() {

return [Link]();

@PostMapping("/students")

public Student addStudent(

@RequestBody Student student) {

return [Link](student);

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 193


Web Development with Java Lab – MCA Sem II

CODE:

([Link])

package [Link];

import [Link];

import [Link];

@SpringBootApplication

public class StudentbackendApplication {

public static void main(String[] args) {

[Link](

[Link],

args

);

CODE:

([Link])

import React, { useEffect, useState } from 'react';

function StudentList() {

const [students, setStudents] = useState([]);

useEffect(() => {

fetch('[Link]

.then((response) => [Link]())

.then((data) => {

setStudents(data);

});
Bindhya Prakash Karkera | DY25SHSP0MCA054 | 194
Web Development with Java Lab – MCA Sem II

}, []);

return (

<div>

<h1>Student List</h1>

<ul>

{[Link]((student) => (

<li key={[Link]}>

{[Link]}

{[Link]}

</li>

))}

</ul>

</div>

);

export default StudentList;

CODE:

([Link])

import StudentList from './StudentList';

function App() {

return (

<div>

<StudentList />
Bindhya Prakash Karkera | DY25SHSP0MCA054 | 195
Web Development with Java Lab – MCA Sem II

</div>

);

export default App;

OUTPUT:

Bindhya Prakash Karkera | DY25SHSP0MCA054 | 196

You might also like