0% found this document useful (0 votes)
48 views37 pages

Akshay Lab Practical

The document contains multiple Java programming exercises including a Bank Account class for managing user accounts, a Circle class for calculating area and circumference using inheritance, and examples of implementing multiple interfaces and using ArrayLists. It also includes a shopping cart implementation using Vectors, a To-Do list using hashing, and demonstrates multi-threading concepts. Each section provides code snippets and sample outputs for better understanding.

Uploaded by

piraj44478
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)
48 views37 pages

Akshay Lab Practical

The document contains multiple Java programming exercises including a Bank Account class for managing user accounts, a Circle class for calculating area and circumference using inheritance, and examples of implementing multiple interfaces and using ArrayLists. It also includes a shopping cart implementation using Vectors, a To-Do list using hashing, and demonstrates multi-threading concepts. Each section provides code snippets and sample outputs for better understanding.

Uploaded by

piraj44478
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
You are on page 1/ 37

Java Lab Practical

Name: Akshay Sanjay Gunjal


Roll No: 24222
Div: B

1. Define a class Bank Account to perform the withdraw and balance enquiry operation.
create a object to manage accounts for multiple users.

import java.util.Scanner;

class BankAccount {
String accountHolder;
double balance;
BankAccount(String holder, double initialBalance)
{ accountHolder = holder;
balance = initialBalance;
}

void deposit(double amount)


{ if (amount > 0) {
balance += amount;
System.out.println("Deposited: " + amount + " New balance: " + balance);
} else {
System.out.println("Deposit amount must be positive.");
}
}
void withdraw(double amount)
{ if (amount > 0) {
if (amount <= balance)
{ balance -= amount;
System.out.println("Withdrew: " + amount + ". New balance: " + balance);
} else {
System.out.println("Insufficient funds.");
}
} else {
System.out.println("Withdrawal amount must be positive.");
}
}
double getBalance()
{ return balance;
}

public String toString() {


return "Account Holder: " + accountHolder + ", Balance: " + balance;
}
public static void main(String[] args)
{ Scanner input = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = input.nextLine();

System.out.print("Enter initial balance: ");


double initialBalance = input.nextDouble();
BankAccount userAccount = new BankAccount(name, initialBalance);
int menuChoice;
do {
System.out.println("\nMenu:");
System.out.println("1. Deposit Amount");
System.out.println("2. Withdraw Amount");
System.out.println("3. Display Information");
System.out.println("4. Exit");
System.out.print("Please enter your choice: ");
menuChoice = input.nextInt();

switch (menuChoice)
{ case 1:
System.out.print("Enter amount to deposit: ");
double depositAmount = input.nextDouble();
userAccount.deposit(depositAmount);
break;
case 2:
System.out.print("Enter amount to withdraw: ");
double withdrawAmount = input.nextDouble();
userAccount.withdraw(withdrawAmount);
break;
case 3:
System.out.println(userAccount);
break;
case 4:
System.out.println("Exiting...");
break;
default:
System.out.println("Invalid choice. Please try again.");
}
} while (menuChoice != 4);

input.close(); // Close the scanner resource


}
}

Output:

Enter your name: Akshay Gunjal


Enter initial balance: 2000

Menu:
1. Deposit Amount
2. Withdraw Amount
3. Display Information
4. Exit
Please enter your choice: 1
Enter amount to deposit: 1000
Deposited: 1000 New balance:3000

Menu:
1. Deposit Amount
2. Withdraw Amount
3. Display Information
4. Exit
Please enter your choice: 2
Enter amount to withdraw: 2000
Withdrew: 2000 New balance:1000

Menu:
1. Deposit Amount
2. Withdraw Amount
3. Display Information
4. Exit
Please enter your choice: 3
Account Holder: Akshay Gunjal, Balance: 1000

2. Program to calculate area and circumference of circle using multilevel inheritance.

import java.util.Scanner;
class Circle
{
double radius;
public void inputRadius()
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the radius of the circle: ");
radius = sc.nextDouble();
}
}
class Area extends Circle
{
public double calculateArea()
{
return Math.PI * radius * radius;
}
}

class Circumference extends Area


{
public double calculateCircumference()
{
return 2 * Math.PI * radius;
}
}
public class CircleCalculation
{
public static void main(String[] args)
{
Circumference circle = new Circumference();
circle.inputRadius();
double area = circle.calculateArea();
System.out.println("Area of the circle is: " + area);
double circumference = circle.calculateCircumference();
System.out.println("Circumference of the circle is: " + circumference);
}
}

Output:

Enter the radius of the circle: 18


Area of the circle is: 1017.88
Circumference of the circle is: 113.09734

3. Implement Multiple interface in a single class to achive multiple inheritance.

interface Animal
{ void eat();
interface Bird
{ void fly();
}
}
class Bat implements Animal, Animal.Bird
{ @Override
public void eat() {
System.out.println("The bat eats insects.");
}

@Override
public void fly()
{ System.out.println("The bat can fly.");
}
}
public class MultipleInheritanceExample
{ public static void main(String[] args) {
Bat bat = new Bat();
bat.eat();
bat.fly();
}
}

Output :
The bat eats insects
The bat can fly
4. Implement menu driven program using an ArrayList.

import java.util.ArrayList;
import java.util.Scanner;

Public class MenuDrivenArrayList


{ public static void main(String[] args)
{
ArrayList<String> list = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
int choice;

do {
System.out.println("\nMenu:");
System.out.println("1. Add Element");
System.out.println("2. Remove Element");
System.out.println("3. Display Elements");
System.out.println("4. Search Element");
System.out.println("5. Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();
scanner.nextLine();

switch (choice)
{ case 1:
System.out.print("Enter element to add: ");
String element = scanner.nextLine();
list.add(element);
System.out.println("Element added successfully.");
break;

case 2:
System.out.print("Enter element to remove: ");
String removeElement = scanner.nextLine();
if (list.remove(removeElement))
{ System.out.println("Element removed
successfully.");
} else {
System.out.println("Element not found.");
}
break;
case 3:
System.out.println("Elements in the list: " + list);
break;

case 4:
System.out.print("Enter element to search: ");
String searchElement = scanner.nextLine();
if (list.contains(searchElement))
{ System.out.println("Element found in the list.");
} else {
System.out.println("Element not found.");
}
break;

case 5:
System.out.println("Exiting program...");
break;

default:
System.out.println("Invalid choice! Please try again.");
}
} while (choice != 5);

scanner.close();
}
}

Output:
Menu:
1. Add Element
2. Remove Element
3. Display Elements
4. Search Element
5. Exit
Enter your choice: 1
Enter element to add: 50
Element added successfully.
Menu:
1.Add Element
2.Remove Element
3.Display Elements
4.Search Element
5.Exit
Enter your choice: 1
Enter element to add: 60
Element added successfully.

Menu:
1.Add Element
2.Remove Element
3.Display Elements
4.Search Element
5.Exit
Enter your choice: 1
Enter element to add: 70
Element added successfully.

Menu:
1.Add Element
2.Remove Element
3.Display Elements
4.Search Element
5.Exit
Enter your choice: 2
Enter element to
remove :60
Element removed successfully.

5. Implement shopping cart using Vector.

import java.util.Vector;

class Item {
String name;
double price;
int quantity;

public Item(String name, double price, int quantity)


{ this.name = name;
this.price = price;
this.quantity = quantity;
}

public double getTotalPrice()


{ return price * quantity;
}

@Override
public String toString() {
return name + " - Rs" + price + " x " + quantity + " = Rs" + getTotalPrice();
}
}

class ShoppingCart {
private Vector<Item> cart;

public ShoppingCart()
{ cart = new Vector<>();
}

public void addItem(String name, double price, int quantity) {


cart.add(new Item(name, price, quantity));
}

public void removeItem(String name) {


cart.removeIf(item -> item.name.equalsIgnoreCase(name));
}

public void displayCart()


{ if (cart.isEmpty()) {
System.out.println("Your cart is empty.");
return;
}
System.out.println("Shopping Cart:");
double total = 0;
for (Item item : cart)
{ System.out.println(item);
total += item.getTotalPrice();
}
System.out.println("Total Cost: Rs" + total);
}
}

public class ShoppingCartDemo {


public static void main(String[] args)
{ ShoppingCart cart = new ShoppingCart();
cart.addItem("Apple", 0.99, 3);
cart.addItem("Banana", 0.59, 5);
cart.displayCart();

System.out.println("\nRemoving Banana from cart...");


cart.removeItem("Banana");
cart.displayCart();
}
}
Output:
Shopping Cart:
Apple - Rs0.95 x 2 = Rs1.9
Banana - Rs0.55 x 6 = Rs3.3
Total Cost: Rs5.2
Removing Banana from cart...
Shopping Cart:
Apple - Rs0.95 x 2 = Rs1.9
Total Cost: Rs1.9
6. Implement To-Do list using hashing
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

class Task {
String description;
boolean isCompleted;

public Task(String description)


{ this.description =
description; this.isCompleted
= false;
}
public void markCompleted()
{ this.isCompleted = true;
}

@Override
public String toString() {
return "[ " + (isCompleted ? "✓" : "✗") + " ] " + description;
}
}

public class ToDoList {


private HashMap<Integer, Task> tasks;
private int taskIdCounter;

public ToDoList() {
tasks = new HashMap<>();
taskIdCounter = 1;
}

public void addTask(String description)


{ tasks.put(taskIdCounter, new Task(description));
System.out.println("Task added with ID: " + taskIdCounter);
taskIdCounter++;
}

public void removeTask(int taskId)


{ if (tasks.containsKey(taskId)) {
tasks.remove(taskId);
System.out.println("Task " + taskId + " removed.");
} else {
System.out.println("Task ID not found.");
}
}
public void markTaskCompleted(int taskId)
{ if (tasks.containsKey(taskId)) {
tasks.get(taskId).markCompleted();
System.out.println("Task " + taskId + " marked as completed.");
} else {
System.out.println("Task ID not found.");
}
}

public void viewTasks()


{ if (tasks.isEmpty()) {
System.out.println("No tasks available.");
} else {
for (Map.Entry<Integer, Task> entry : tasks.entrySet())
{ System.out.println("ID: " + entry.getKey() + " " + entry.getValue());
}
}
}

public static void main(String[] args)


{ ToDoList toDoList = new ToDoList();
Scanner scanner = new Scanner(System.in);

while (true) {
System.out.println("\nTo-Do List Menu:");
System.out.println("1. Add Task");
System.out.println("2. Remove Task");
System.out.println("3. Mark Task as Completed");
System.out.println("4. View Tasks");
System.out.println("5. Exit");
System.out.print("Choose an option: ");

int choice = scanner.nextInt();


scanner.nextLine(); // Consume newline

switch (choice)
{ case 1:
System.out.print("Enter task description: ");
String description = scanner.nextLine();
toDoList.addTask(description);
break;
case 2:
System.out.print("Enter task ID to remove: ");
int removeId = scanner.nextInt();
toDoList.removeTask(removeId);
break;
case 3:
System.out.print("Enter task ID to mark as completed: ");
int completeId = scanner.nextInt();
toDoList.markTaskCompleted(completeId);
break;
case 4:
toDoList.viewTasks();
break;
case 5:
System.out.println("Exiting To-Do List...");
scanner.close();
return;
default:
System.out.println("Invalid choice. Please select again.");
}
}
}
}
Output:
To-Do List Menu:
1. Add Task
2. Remove Task
3. Mark Task as Completed
4. View Tasks
5. Exit
Choose an option: 1
Enter task description: sleep
Task added with ID: 1

To-Do List Menu:


1. Add Task
2. Remove Task
3. Mark Task as Completed
4. View Tasks
5. Exit

7. Write a program to Create Multiple Threads and Running Simultaneously

class MyThread extends Thread


{ private String threadName;

public MyThread(String name)


{ this.threadName = name;
}
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(threadName + " is running... Iteration: " + i);
try {
Thread.sleep(500); // Simulates some processing delay
} catch (InterruptedException e)
{ System.out.println(threadName + " was interrupted.");
}
}
System.out.println(threadName + " has finished execution.");
}
}
class MyRunnable implements Runnable
{ private String threadName;

public MyRunnable(String name)


{ this.threadName = name;
}

@Override
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(threadName + " (Runnable) is running... Iteration: " + i);
try {
Thread.sleep(700);
} catch (InterruptedException e)
{ System.out.println(threadName + " was interrupted.");
}
}
System.out.println(threadName + " (Runnable) has finished execution.");
}
}

public class MultiThreadDemo {


public static void main(String[] args)
{ System.out.println("Main thread starting...");

// Creating threads using Thread class


MyThread thread1 = new MyThread("Thread-1");
MyThread thread2 = new MyThread("Thread-2");

// Creating threads using Runnable interface


Thread thread3 = new Thread(new MyRunnable("Thread-3"));
Thread thread4 = new Thread(new MyRunnable("Thread-4"));

// Starting all threads


thread1.start();
thread2.start();
thread3.start();
thread4.start();
System.out.println("Main thread execution completed.");
}
}

Output:
Main thread starting...
Main thread execution completed.
Thread-4 (Runnable) is running... Iteration: 1
Thread-2 is running... Iteration: 1
Thread-3 (Runnable) is running... Iteration: 1
Thread-1 is running... Iteration: 1
Thread-2 is running... Iteration: 2
Thread-1 is running... Iteration: 2
Thread-3 (Runnable) is running... Iteration: 2
Thread-4 (Runnable) is running... Iteration: 2
Thread-1 is running... Iteration: 3
Thread-2 is running... Iteration: 3
Thread-4 (Runnable) is running... Iteration: 3
Thread-3 (Runnable) is running... Iteration: 3
Thread-1 is running... Iteration: 4
Thread-2 is running... Iteration: 4
Thread-2 is running... Iteration: 5
8. Write a program to Demonstrate Thread Lifecycle (New, Runnable, Blocked, Waiting,
Terminated
class DemoThread implements Runnable
{ private final Object lock;

public DemoThread(Object lock)


{ this.lock = lock;
}

@Override
public void run()
{ try {
System.out.println(Thread.currentThread().getName() + " is in RUNNABLE state.");
Thread.sleep(1000); // TIMED_WAITING state

synchronized (lock) {
System.out.println(Thread.currentThread().getName() + " has entered BLOCKED state
(waiting for lock).");
Thread.sleep(1000); // Still holding lock
System.out.println(Thread.currentThread().getName() + " is now in RUNNABLE state
again.");
}

synchronized (lock) {
System.out.println(Thread.currentThread().getName() + " is now WAITING.");
lock.wait(); // Moves to WAITING state
}
} catch (InterruptedException e)
{ e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " has TERMINATED.");
}
}

public class ThreadLifecycleDemo


{ public static void main(String[] args)
{
Object lock = new Object();
Thread thread1 = new Thread(new DemoThread(lock), "Thread-1");
Thread thread2 = new Thread(new DemoThread(lock), "Thread-2");
System.out.println(thread1.getName() + " is in NEW state.");
thread1.start();
thread2.start();

try {
Thread.sleep(500);
System.out.println(thread1.getName() + " state: " + thread1.getState()); // Expected:
TIMED_WAITING

Thread.sleep(1000);
System.out.println(thread2.getName() + " state: " + thread2.getState()); // Expected:
BLOCKED

Thread.sleep(2000);
synchronized (lock) {
lock.notifyAll(); // Notify waiting threads
}
} catch (InterruptedException e)
{ e.printStackTrace();
}

try {
thread1.join();
thread2.join();
} catch (InterruptedException e)
{ e.printStackTrace();
}

System.out.println(thread1.getName() + " final state: " + thread1.getState()); // Expected:


TERMINATED
System.out.println(thread2.getName() + " final state: " + thread2.getState()); // Expected:
TERMINATED
}
}
Output:
Thread-1 is in NEW state.
Thread-1 is in RUNNABLE state.
Thread-2 is in RUNNABLE state.
Thread-1 state: TIMED_WAITING
Thread-1 has entered BLOCKED state (waiting for lock).
Thread-2 state: BLOCKED
Thread-1 is now in RUNNABLE state again.
Thread-1 is now WAITING.
Thread-2 has entered BLOCKED state (waiting for lock).
Thread-2 is now in RUNNABLE state again.
Thread-2 is now WAITING.
Thread-2 has TERMINATED.
Thread-1 has TERMINATED.
Thread-1 final state: TERMINATED
Thread-2 final state: TERMINATED

9. Write a program to Handle Multiple Exceptions in One Catch Block

public class MultipleExceptionsDemo


{ public static void main(String[] args)
{
try {
// Example 1: ArithmeticException (divide by zero)
int result = 10 / 0; // This will throw ArithmeticException

// Example 2: ArrayIndexOutOfBoundsException
int[] numbers = { 1, 2, 3 };
System.out.println(numbers[5]); // Accessing invalid index

// Example 3: NumberFormatException
int num = Integer.parseInt("abc"); // Trying to parse invalid number

} catch (ArithmeticException | ArrayIndexOutOfBoundsException |


NumberFormatException e)
{
System.out.println("Exception occurred: " + e.getClass().getSimpleName());
System.out.println("Error message: " + e.getMessage());
} finally {
System.out.println("Execution completed.");
}
}
}
Output:
Exception occurred: ArithmeticException
Error message: / by zero
Execution completed.
10. Write a program to create a servlet using creating servlet.

index.html
<!DOCTYPE html>
<!--
Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this
license
Click nbfs://nbhost/SystemFileSystem/Templates/JSP_Servlet/Html.html to edit this template
-->
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h1>hello world</h1>
<div><h2>TODO write content<h2></div>
</body>
</html>
FirstSercvlet.java
package com.servlets;
import java.io.IOException;
import javax.servlet.*;

public class FirstServlet implements Servlet


{
ServletConfig conf;

public void init(ServletConfig conf)


{
this.conf=conf;
System.out.println("Creating Object --");
}

@Override
public void service(ServletRequest req, ServletResponse resp)throws ServletException,
IOException
{
System.out.println("Servicinf");

@Override
public void destroy()
{
System.out.println("Destroying Object --");
}

@Override
public ServletConfig getServletConfig()
{
return this.conf;
}

@Override
public String getServletInfo()
{
return "We have created this servlet";
}
}

Web.xml

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

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">

<servlet>
<servlet-name>first</servlet-name>
<servlet-class>com.servlets.FirstServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>first</servlet-name>
<url-pattern>/web</url-pattern>
</servlet-mapping>

<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>

Output:

hello world

TODO write content


11. Write a program to Create servlet using HTTP Servlet. create a registration form.
Submit form data to servlet also print display data on browser

RegisterServlet.java

package com.practice;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
import javax.servlet.http.*;

public class RegisterServlet extends HttpServlet


{

public void doPost(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1>registration Page</h1>");

String name1=request.getParameter("user_name");
String password1=request.getParameter("user_password");
String email1=request.getParameter("user_email");
String gender1=request.getParameter("user_gender");

String condi1 =request.getParameter("condition");


if(condi1.equals("checked"))
{
out.println("<h2> Name : "+name1 + "<h2>");
out.println("<h2> Password : "+password1 + "<h2>");
out.println("<h2> Email ID : "+email1 + "<h2>");
out.println("<h2> Gender : "+gender1 + "<h2>");
}
else
{
out.println("Please Click Agree");
}
}
}

Index.html

<html>
<head>
<link rel="stylesheet" href="style.css" type="text/css"/>
<title>Form page </title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div class ="container">
<h1>My form</h1>

<form id="myform" action="RegisterServlet" method="post">


<table>
<tr>
<td>Enter Your name</td><!-- comment -->
<td> <input type="text" name="user_name" /> </td>
</tr>

<tr>
<td>Enter Password</td><!-- comment -->
<td> <input type ="password" name="user_password" /></td>
</tr>

<tr>
<td>Enter Your Email</td><!-- comment -->
<td> <input type="email" name="user_email" /> </td>
</tr>

<tr>
<td>Select Gender</td><!-- comment -->
<td> <input type="radio" name="user_gender" value="Male">male
<input type="radio" name="user_gender" value="Female">Female </td>
</tr>
<tr>
<td>
<input type="checkbox" value="checked" name="condition" />
</td>
<td>
Agree
</td>
</tr>

<tr>
<td>
<button type="submit">Register</button>
<button type="reset">Reset</button>
</td>
</tr>

</table>
</form>
</div>
</body>
</html>

Web.xml

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

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">

<servlet>
<servlet-name>registere</servlet-name>
<servlet-class>com.practice.RegisterServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>registere</servlet-name>
<url-pattern>/RegisterServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>

Output:

My form
Enter Your name Akshay Gunjal

Enter Password *********

Enter Your Email [email protected]


Select Gender male Female

Agree

Register Reset

registration Page

Name : Akshay Gunjal

Password : Akshay123

Email ID : [email protected]

Gender : Male
12. Write a Java Servlet program to demonstrate the use of cookies in a web application.

CookieServlet.java

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieServlet extends HttpServlet {


protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();

// Creating a new cookie


Cookie userCookie = new Cookie("username", "JohnDoe");
userCookie.setMaxAge(60 * 60); // 1 hour
response.addCookie(userCookie);

out.println("<h3>Cookie has been set!</h3>");


out.println("<a href='DisplayCookieServlet'>View Cookie</a>");
}
}

DisplayCookieServlet.java

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DisplayCookieServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();

Cookie[] cookies = request.getCookies();


if (cookies != null) {
for (Cookie cookie : cookies) {
out.println("<h3>Cookie Name: " + cookie.getName() + ", Value: " +
cookie.getValue() + "</h3>");
}
} else {
out.println("<h3>No cookies found!</h3>");
}
}
}

Output :

Cookie has been set!


Cookie Name: username, Value: mahi
13. Write a Program in JSP to Accept Two Numbers from User and Display Their Sum

sum.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-
8"%>
<html>
<head><title>Sum of Two Numbers</title></head>
<body>
<form method="post">
Enter Number 1: <input type="text" name="num1"><br>
Enter Number 2: <input type="text" name="num2"><br>
<input type="submit" value="Calculate Sum">
</form>

<%
String n1 = request.getParameter("num1");
String n2 = request.getParameter("num2");

if(n1 != null && n2 != null && !n1.isEmpty() && !n2.isEmpty())


{ int sum = Integer.parseInt(n1) + Integer.parseInt(n2);
out.println("<h3>Sum: " + sum + "</h3>");
}
%>
</body>
</html>

Output :
Enter Number 1: 60
Enter Number 2: 10
Sum: 70
14. Write a program to implement JSP tags

jsp_tags.jsp

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>


<html>
<head><title>JSP Tags Example</title></head>
<body>
<h2>JSP Tags Example</h2>

<%-- Declaration Tag --%>


<%!
int multiply(int a, int b)
{ return a * b;
}
%>

<%-- Scriptlet Tag --%>


<%
int result = multiply(4, 5);
%>
<p>Multiplication Result: <%= result %></p>

<%-- Expression Tag --%>


<p>Today's Date: <%= new java.util.Date() %></p>

<%-- JSTL Tag --%>


<c:set var="name" value="Nikhil" />
<p>Hello, <c:out value="${name}" /></p>
</body>
</html>

Output :
Multiplication Result: 20
Date: 15-March-2025
Hello, Akshay
15. Write a program to create a registration form using JSP. Store data in the database.
Also displays registration details on the web page.

MySQL Command:

create database mydb;

use mydb;

create table users (


id int auto_increment primary key,
name varchar(30) not null,
email varchar(30) not null unique,
password varchar(20) not null
);

register.jsp

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


8"%>
<html>
<head>
<title>User Registration</title>
</head>
<body>
<h2>Registration Form</h2>
<form action="register_process.jsp" method="post">
Name: <input type="text" name="name" required><br><br>
Email: <input type="email" name="email" required><br><br>
Password: <input type="password" name="password" required><br><br>
<input type="submit" value="Register">
</form>
</body>
</html>

register_process.jsp

<%@ page import="java.sql.*" %>


<%@ page import="java.io.*" %>
<%
String name = request.getParameter("name");
String email = request.getParameter("email");
String password = request.getParameter("password");

if (name != null && email != null && password != null)


{ try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3307/mydb",
"root", "Nikhil@167#");

PreparedStatement ps = con.prepareStatement("INSERT INTO users (name, email,


password) VALUES (?, ?, ?)");
ps.setString(1, name);
ps.setString(2, email);
ps.setString(3, password);
int result = ps.executeUpdate();
if (result > 0) {
out.println("<h3>Registration Successful!</h3>");
out.println("<a href='display_users.jsp'>View Registered Users</a>");
} else {
out.println("<h3>Registration Failed!</h3>");
}
con.close();
} catch (Exception e) {
out.println("<h3>Error: " + e.getMessage() + "</h3>");
}
}
%>
display_user.jsp

<%@ page import="java.sql.*" %>


<html>
<head>
<title>Registered Users</title>
</head>
<body>
<h2>List of Registered Users</h2>
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
</tr>
<%
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3307/mydb",
"root", "Nikhil@167#");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT id, name, email FROM users");

while (rs.next())
{ out.println("<tr>");
out.println("<td>" + rs.getInt("id") + "</td>");
out.println("<td>" + rs.getString("name") + "</td>");
out.println("<td>" + rs.getString("email") + "</td>");
out.println("</tr>");
}

con.close();
} catch (Exception e) {
out.println("<h3>Error: " + e.getMessage() + "</h3>");
}
%>
</table>
</body>
</html>

Web.xml
<web-app>
<servlet>
<servlet-name>JSP</servlet-name>
<jsp-file>/register.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>JSP</servlet-name>
<url-pattern>/register</url-pattern>
</servlet-mapping>
</web-app>
Output :
Name: Akshay Gunjal
Email: [email protected]
Password: *******
Registration Successful!

Select * from users;


id name email
1 Akshay Gunjal [email protected]
16. Write a program to create a feedback form using JSP and store responses in a
database.

MySQL Command :
create database feedback_db;
use feedback_db;
create table feedback(id int auto_increment primary key, name varchar(30),email
varchar(30),message text);

feedbackForm.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Feedback Form</title>
</head>
<body>
<h2>Feedback Form</h2>
<form action="FeedbackServlet" method="post">
Name: <input type="text" name="name" required><br><br>
Email: <input type="email" name="email" required><br><br>
Message:<br><textarea name="message" rows="5" cols="30"
required></textarea><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

FeedbackServelet.java
package com.jdbc;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/FeedbackServlet")
public class FeedbackServlet extends HttpServlet
{ @Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// Retrieve form data
String name = request.getParameter("name");
String email = request.getParameter("email");
String message = request.getParameter("message");

// Database connection details


String jdbcURL = "jdbc:mysql://localhost:3307/feedback_db";
String dbUser = "root";
String dbPassword = "Nikhil@167#";

Connection connection = null;


PreparedStatement preparedStatement = null;

response.setContentType("text/html");
PrintWriter out = response.getWriter();

try {
// Load JDBC driver
Class.forName("com.mysql.jdbc.Driver");

// Establish connection
connection = DriverManager.getConnection(jdbcURL, dbUser, dbPassword);

// Insert feedback into database


String sql = "INSERT INTO feedback (name, email, message) VALUES (?, ?, ?)";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, name);
preparedStatement.setString(2, email);
preparedStatement.setString(3, message);

int rowsInserted = preparedStatement.executeUpdate();


if (rowsInserted > 0) {
out.println("<h3>Thank you for your feedback!</h3>");
} else {
out.println("<h3>Failed to submit feedback. Please try again.</h3>");
}
} catch (ClassNotFoundException | SQLException e)
{ e.printStackTrace();
out.println("<h3>Error occurred while processing your feedback.</h3>");
} finally
{ try {
if (preparedStatement != null) preparedStatement.close();
if (connection != null) connection.close();
} catch (SQLException e)
{ e.printStackTrace();
}
}
}
}

Output:
Feedback Form
Name: Akshay Gunjal

Email: [email protected]

Message: Working

Database :
Select * from feedback;
id name email message
1 Akshay Gunjal [email protected] Working

You might also like