0% found this document useful (0 votes)
11 views

OOS Pract File

The document contains solutions to 8 programming problems in Java. It provides code snippets to implement a stack, bank account, multi-threading, file handling and more. The solutions also include classes, objects, inheritance and applets.

Uploaded by

ManeeshMahajan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

OOS Pract File

The document contains solutions to 8 programming problems in Java. It provides code snippets to implement a stack, bank account, multi-threading, file handling and more. The solutions also include classes, objects, inheritance and applets.

Uploaded by

ManeeshMahajan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

HARCOURT BUTLER TECHNICAL UNIVERSITY

NAWABGANJ KANPUR

OBJECT ORIENTED SYSTEM (ECS-354)


Practical file
Session:2022-23

Submitted to: Submitted by:


Prabhat Verma Sir Shubham Singh
Computer Science & Engineering dept. 200108059
3rd. IT
1. Write a program in Java, to implements the Stack data Structure.
Sol.
public class Stack {
private int[] arr;
private int top;
private int capacity;

public Stack(int size) {


arr = new int[size];
capacity = size;
top = -1;
}

public void push(int x) {


if (isFull()) {
System.out.println("Stack is full.");
System.exit(1);
}
arr[++top] = x;
}

public int pop() {


if (isEmpty()) {
System.out.println("Stack is empty.");
System.exit(1);
}
return arr[top--];
}
public boolean isEmpty() {
return top == -1;
}

public boolean isFull() {


return top == capacity - 1;
}
}

2. Write a program in Java to implement a simple Bank Account.


Sol.
public class BankAccount {
private String accountNumber;
private double balance;

public BankAccount(String accountNumber, double balance) {


this.accountNumber = accountNumber;
this.balance = balance;
}

public void deposit(double amount) {


balance += amount;
}

public void withdraw(double amount) {


if (amount > balance) {
System.out.println("Insufficient balance.");
return;
}
balance -= amount;
}

public String getAccountNumber() {


return accountNumber;
}

public double getBalance() {


return balance;
}
}

3. Write a program in Java showing the action from three threads using a suitable
example.
Sol.
public class ThreadExample implements Runnable {
private String message;

public ThreadExample(String message) {


this.message = message;
}

public void run() {


System.out.println(Thread.currentThread().getName() + " starting.");
for (int i = 0; i < 5; i++) {
System.out.println(message);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Thread interrupted.");
}
}
System.out.println(Thread.currentThread().getName() + " exiting.");
}

public static void main(String[] args) {


Thread t1 = new Thread(new ThreadExample("Thread 1"));
Thread t2 = new Thread(new ThreadExample("Thread 2"));
Thread t3 = new Thread(new ThreadExample("Thread 3"));
t1.start();
t2.start();
t3.start();
}
}

4. Write a program of threads in Java showing inter leaving of actions from two threads: t1
& t2 synchronizing on a shared object. Let t1 print message Ping and t2 prints message
Pong. Take as command line arguments the following inputs to the program:
Sleep interval for thread t1Sleep interval for thread t2Messages per cycle Number of
Cycles.
Sol.
public class PingPong implements Runnable {
private Object lock;
private String message;
private int sleepInterval;
private int messagesPerCycle;
public PingPong(Object lock, String message, int sleepInterval, int messagesPerCycle) {
this.lock = lock;
this.message = message;
this.sleepInterval = sleepInterval;
this.messagesPerCycle = messagesPerCycle;
}

public void run() {


try {
for (int i = 0; i < messagesPerCycle; i++) {
synchronized (lock) {
System.out.println(message);
lock.notify();
lock.wait();
}
Thread.sleep(sleepInterval);
}
} catch (InterruptedException e) {
System.out.println("Thread interrupted.");
}
}

public static void main(String[] args) {


if (args.length != 4) {
System.out.println("Usage: java PingPong sleepIntervalForT1 sleepIntervalForT2
messagesPerCycle numberOfCycles");
System.exit(1);
}
Object lock = new Object();
int sleepIntervalT1 = Integer.parseInt(args[0]);
int sleepIntervalT2 = Integer.parseInt(args[1]);
int messagesPerCycle = Integer.parseInt(args[2]);
int numberOfCycles = Integer.parseInt(args[3]);
Thread t1 = new Thread(new PingPong(lock, "Ping ->", sleepIntervalT1, messagesPerCycle));
Thread t2 = new Thread(new PingPong(lock, "<- Pong", sleepIntervalT2,
messagesPerCycle));
t1.start();
t2.start();
try {
Thread.sleep((messagesPerCycle * numberOfCycles * Math.max(sleepIntervalT1,
sleepIntervalT2)) + 1000);
} catch (InterruptedException e) {
System.out.println("Thread interrupted.");
}
System.exit(0);
}

5. Write a program in Java which converts a text file into all capital letters.
Sol.
import java.io.*;

public class CapitalizeTextFile {


public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Usage: java CapitalizeTextFile filename");
System.exit(1);
}
String filename = args[0];
File file = new File(filename);
if (!file.exists()) {
System.out.println("File not found.");
System.exit(1);
}
try (BufferedReader reader = new BufferedReader(new FileReader(file));
BufferedWriter writer = new BufferedWriter(new FileWriter("capitalized.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
writer.write(line.toUpperCase());
writer.newLine();
}
System.out.println("File capitalized successfully.");
} catch (IOException e) {
System.out.println("Error occurred while capitalizing file.");
}
}
}

6. Write a program to create a sequential file that could store details about five products.
Details include product code, cost, no. Of items available and number of items available
and are provided through keyboard.
Sol.
import java.io.*;
import java.util.Scanner;

public class ProductFile {


public static void main(String[] args) {
try (PrintWriter writer = new PrintWriter(new FileWriter("products.txt"))) {
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < 5; i++) {
System.out.println("Enter product code:");
String code = scanner.nextLine();
System.out.println("Enter cost:");
double cost = Double.parseDouble(scanner.nextLine());
System.out.println("Enter number of items:");
int numberOfItems = Integer.parseInt(scanner.nextLine());
System.out.println("Enter number of items available:");
int numberOfItemsAvailable = Integer.parseInt(scanner.nextLine());
writer.println(code + " " + cost + " " + numberOfItems + " " +
numberOfItemsAvailable);
}
System.out.println("Product details written to file successfully.");
} catch (IOException e) {
System.out.println("Error occurred while writing product details to file.");
}
}
}

7. Create a Person class with private instance variables for Person’s name and birth date.
Add appropriate accessor methods to access the variables. Then create a subclass
CollegeGraduate with private instance variables for the student’s GPA and year of
graduation and appropriate accessors for these variables. Don’t forget to include
appropriate constructors for your classes. Then create a class with a main() method that
manages your classes.
Sol.
public class Person {
private String name;
private String birthDate;

public Person(String name, String birthDate) {


this.name = name;
this.birthDate = birthDate;
}

public String getName() {


return name;
}

public String getBirthDate() {


return birthDate;
}
}

public class CollegeGraduate extends Person {


private double gpa;
private int yearOfGraduation;

public CollegeGraduate(String name, String birthDate, double gpa, int yearOfGraduation) {


super(name, birthDate);
this.gpa = gpa;
this.yearOfGraduation = yearOfGraduation;
}

public double getGpa() {


return gpa;
}

public int getYearOfGraduation() {


return yearOfGraduation;
}
}
public class PersonManager {
public static void main(String[] args) {
CollegeGraduate graduate = new CollegeGraduate("John", "01/01/2000", 3.8, 2022);
System.out.println("Name: " + graduate.getName());
System.out.println("Birth Date: " + graduate.getBirthDate());
System.out.println("GPA: " + graduate.getGpa());
System.out.println("Year of Graduation: " + graduate.getYearOfGraduation());
}
}

8. Develop an applet that receives three numeric values from the user and displays the
largest of the three on the screen. Write a HTML page that embeds this applet.
Sol.

import java.applet.Applet;
import java.awt.*;

public class LargestNumberApplet extends Applet {


private TextField textField1;
private TextField textField2;
private TextField textField3;
private Label resultLabel;
@Override
public void init() {
setLayout(new GridLayout(4, 2));
Label label1 = new Label("Enter first number:");
textField1 = new TextField();
Label label2 = new Label("Enter second number:");
textField2 = new TextField();
Label label3 = new Label("Enter third number:");
textField3 = new TextField();
resultLabel = new Label();
Button button = new Button("Find largest number");
button.addActionListener(e -> {
int num1 = Integer.parseInt(textField1.getText());
int num2 = Integer.parseInt(textField2.getText());
int num3 = Integer.parseInt(textField3.getText());
int largest = Math.max(Math.max(num1, num2), num3);
resultLabel.setText("Largest number: " + largest);
});
add(label1);
add(textField1);
add(label2);
add(textField2);
add(label3);
add(textField3);
add(button);
add(resultLabel);
}
}
HTML page to embed the applet:
<!DOCTYPE html>
<html>
<head>
<title>Largest Number Applet</title>
</head>
<body>
<h1>Largest Number Applet</h1>
<hr>
<applet code="LargestNumberApplet.class" width="300" height="200">
</applet>
</body>
</html>

9. Write an applet which draws a human face with ovals and arcs.
Sol.
import java.applet.Applet;
import java.awt.*;

public class FaceApplet extends Applet {


@Override
public void paint(Graphics g) {
g.setColor(Color.YELLOW);
g.fillOval(50, 50, 200, 200);
g.setColor(Color.BLACK);
g.drawOval(80, 100, 30, 30);
g.drawOval(180, 100, 30, 30);
g.fillOval(95, 110, 10, 10);
g.fillOval(195, 110, 10, 10);
g.drawArc(100, 160, 100, 50, 180, 180);
}
}

HTML page to embed the applet:

<!DOCTYPE html>
<html>
<head>
<title>Face Applet</title>
</head>
<body>
<h1>Face Applet</h1>
<hr>
<applet code="FaceApplet.class" width="300" height="300">
</applet>
</body>
</html>

10. Write servlets that accepts user preferences (color, hobby etc.) from user, saves it as
cookie onuser machine and reads the cookie from the user machine.
Sol.
import java.io.IOException;
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 PreferencesServlet extends HttpServlet {


private static final long serialVersionUID = 1L;

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {
String color = request.getParameter("color");
String hobby = request.getParameter("hobby");
String movie = request.getParameter("movie");

// Save user preferences as cookies


Cookie colorCookie = new Cookie("color", color);
colorCookie.setMaxAge(60 * 60 * 24 * 365);
response.addCookie(colorCookie);

Cookie hobbyCookie = new Cookie("hobby", hobby);


hobbyCookie.setMaxAge(60 * 60 * 24 * 365);
response.addCookie(hobbyCookie);

Cookie movieCookie = new Cookie("movie", movie);


movieCookie.setMaxAge(60 * 60 * 24 * 365);
response.addCookie(movieCookie);

response.sendRedirect("preferences.jsp");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// Read user preferences from cookies
Cookie[] cookies = request.getCookies();
String color = null, hobby = null, movie = null;

if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("color")) {
color = cookie.getValue();
} else if (cookie.getName().equals("hobby")) {
hobby = cookie.getValue();
} else if (cookie.getName().equals("movie")) {
movie = cookie.getValue();
}
}
}

// Pass user preferences to JSP page


request.setAttribute("color", color);
request.setAttribute("hobby", hobby);
request.setAttribute("movie", movie);
request.getRequestDispatcher("preferences.jsp").forward(request, response);
}
}

11. Write an AWT application with checkbox such that all cable TV channels will be
displayedfrom the selected category.
Sol.
import java.awt.*;
import java.awt.event.*;

public class TVChannels extends Frame implements ItemListener {


private Checkbox news, sports, movies;
private Label selectedCategory;
private List channels;

public TVChannels() {
setTitle("TV Channels");
setSize(400, 300);
setLayout(new FlowLayout());

news = new Checkbox("News");


sports = new Checkbox("Sports");
movies = new Checkbox("Movies");

selectedCategory = new Label("Selected Category:");

channels = new List(10);

// add channels to the list


channels.add("CNN");
channels.add("BBC");
channels.add("ESPN");
channels.add("Fox Sports");
channels.add("HBO");
channels.add("Star Movies");
add(news);
add(sports);
add(movies);
add(selectedCategory);
add(channels);

news.addItemListener(this);
sports.addItemListener(this);
movies.addItemListener(this);
}

public void itemStateChanged(ItemEvent e) {


channels.removeAll(); // clear the list

// add channels based on selected category


if (news.getState()) {
channels.add("CNN");
channels.add("BBC");
}

if (sports.getState()) {
channels.add("ESPN");
channels.add("Fox Sports");
}

if (movies.getState()) {
channels.add("HBO");
channels.add("Star Movies");
}

// update the label to show selected category


selectedCategory.setText("Selected Category: ");

if (news.getState()) {
selectedCategory.setText(selectedCategory.getText() + " News ");
}

if (sports.getState()) {
selectedCategory.setText(selectedCategory.getText() + " Sports ");
}

if (movies.getState()) {
selectedCategory.setText(selectedCategory.getText() + " Movies ");
}
}

public static void main(String[] args) {


TVChannels tv = new TVChannels();
tv.setVisible(true);
}
}

12. Create a simple Swing based applet that displays two buttons. Each time a button is
clicked, amessage is displayed that states which button was clicked.
Sol.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class ButtonClickApplet extends JApplet implements ActionListener {


JButton button1, button2;
JLabel label;

public void init() {


setLayout(new FlowLayout());

button1 = new JButton("Button 1");


button1.addActionListener(this);
add(button1);

button2 = new JButton("Button 2");


button2.addActionListener(this);
add(button2);

label = new JLabel("Click a button to see the message.");


add(label);
}

public void actionPerformed(ActionEvent ae) {


if(ae.getSource() == button1) {
label.setText("Button 1 was clicked.");
}
else if(ae.getSource() == button2) {
label.setText("Button 2 was clicked.");
}
}
}

13. Create JSP code that uses a persistant cookie (i.e. a cookie with an expiration date in
the future) to keep track of how many times the client computer has visited the page. Use
setMaxAge method to remain on the client’s computer for one month. Display the number
ofpage hits (i.e. cookie’s value) every time the page loads.
Sol.
<%@ page import="java.util.*" %>
<%
// Get the page hit count from the cookie
int count = 0;
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
if (cookies[i].getName().equals("pageHitCount")) {
count = Integer.parseInt(cookies[i].getValue());
break;
}
}
}

// Increment the page hit count and update the cookie


count++;
Cookie cookie = new Cookie("pageHitCount", Integer.toString(count));
cookie.setMaxAge(2592000); // set the cookie to last for one month (in seconds)
response.addCookie(cookie);
%>
<!DOCTYPE html>
<html>
<head>
<title>JSP Page Hit Counter</title>
</head>
<body>
<h1>Welcome to my website</h1>
<p>You have visited this page <%= count %> times.</p>
</body>
</html>

14. Write JSP program that asks user his favourite color as request parameter and sets it
as thebackground color of the page or sets the background color white if the parameter
value is null.
Sol.
<!DOCTYPE html>
<html>
<head>
<title>Favorite Color</title>
</head>
<body <% if(request.getParameter("color") != null) { %>
style="background-color: <%= request.getParameter("color") %>;"
<% } else { %>
style="background-color: white;"
<% } %>>
<h1>What's your favorite color?</h1>
<form method="get">
<label>Color:</label>
<input type="text" name="color">
<button type="submit">Submit</button>
</form>
</body>
</html>

15. Write a program in Java to show the mouse click event. The program should change
thebackground colour of window randomly at each mouse click.
Sol.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class MouseClickEventDemo extends JFrame {

private JPanel contentPane;


private Random random;

public MouseClickEventDemo() {
setTitle("Mouse Click Event Demo");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = new JPanel();
contentPane.setPreferredSize(new Dimension(300, 300));
contentPane.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
contentPane.setBackground(getRandomColor());
}
});
setContentPane(contentPane);
pack();
setVisible(true);
random = new Random();
}

private Color getRandomColor() {


int r = random.nextInt(256);
int g = random.nextInt(256);
int b = random.nextInt(256);
return new Color(r, g, b);
}

public static void main(String[] args) {


new MouseClickEventDemo();
}

Lab Assignment: 1
Model a “Traffic Signal System for a City Traffic Crossroad Circle” using Object Oriented
Methodology. Traffic Signal may be designed as a Class. Design Class Diagram and
implement the class in Java. You may use Java Graphics library to make a Visual Model of
Traffic System to simulate the real one.
Sol.
the class diagram for our TrafficSignal class:
+ +
| TrafficSignal |
+ +
| +currentSignal: SignalColor |
| +eastWestSignal: SignalColor |
| +northSouthSignal: SignalColor |
+ +
| +changeSignal(): void |
| +getEastWestSignal(): SignalColor |
| +getNorthSouthSignal(): SignalColor |
+ +

+ +
| SignalColor |
+ +
| -color: Color |
+ +
| +SignalColor(color: Color) |
| +getColor(): Color |
+ +

the implementation of the TrafficSignal class in Java, using the Java Graphics library to
draw the traffic signal:
import javax.swing.*;
import java.awt.*;

public class TrafficSignal extends JPanel {


private SignalColor currentSignal;
private SignalColor eastWestSignal;
private SignalColor northSouthSignal;

public TrafficSignal() {
this.currentSignal = SignalColor.RED;
this.eastWestSignal = SignalColor.RED;
this.northSouthSignal = SignalColor.GREEN;
}

public void changeSignal() {


switch (currentSignal) {
case RED:
currentSignal = SignalColor.GREEN;
eastWestSignal = SignalColor.GREEN;
northSouthSignal = SignalColor.RED;
break;
case GREEN:
currentSignal = SignalColor.YELLOW;
break;
case YELLOW:
currentSignal = SignalColor.RED;
eastWestSignal = SignalColor.RED;
northSouthSignal = SignalColor.GREEN;
break;
}
repaint();
}

public SignalColor getEastWestSignal() {


return eastWestSignal;
}

public SignalColor getNorthSouthSignal() {


return northSouthSignal;
}

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLACK);
g.fillRect(0, 0, getWidth(), getHeight());

int diameter = getHeight() / 3;


int x = getWidth() / 2 - diameter / 2;
int y = getHeight() / 6 - diameter / 2;
g.setColor(currentSignal.getColor());
g.fillOval(x, y, diameter, diameter);

x = getWidth() / 2 - diameter / 2;
y = getHeight() / 2 - diameter / 2;
g.setColor(eastWestSignal.getColor());
g.fillOval(x, y, diameter, diameter);

x = getWidth() / 2 - diameter / 2;
y = getHeight() / 6 * 5 - diameter / 2;
g.setColor(northSouthSignal.getColor());
g.fillOval(x, y, diameter, diameter);
}

public static void main(String[] args) {


JFrame frame = new JFrame("Traffic Signal");
TrafficSignal trafficSignal = new TrafficSignal();
frame.add(trafficSignal);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 400);
frame.setVisible(true);

while (true) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
trafficSignal.changeSignal();
}
}
}
enum SignalColor {
RED(Color.RED), YELLOW(Color.YELLOW), GREEN(Color.GREEN);

private final Color color;

SignalColor(Color color) {
this.color = color;
}

public Color getColor() {


return color;
}
}
Lab Assignment: 2

Write a JSP program which displays a webpage containing arrival of new items within a
particular month in the different branches of a retail company.
Sol.

ItemServlet.java:

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;

public class ItemServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

Connection conn = null;


Statement stmt = null;
ResultSet rs = null;

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

// Establish a connection to the database


conn = DriverManager.getConnection("jdbc:mysql://localhost/your_database_name",
"your_database_username", "your_database_password");

// Get the selected month from the form data


String selectedMonth = request.getParameter("selectedMonth");

// Create a SQL statement to retrieve the items from the database based on the selected
month
String sql = "SELECT * FROM items WHERE MONTH(arrival_date) = ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, selectedMonth);
rs = ps.executeQuery();

// Create an ArrayList to hold the items


ArrayList<Item> items = new ArrayList<Item>();

// Loop through the ResultSet and add each item to the ArrayList
while (rs.next()) {
Item item = new Item();
item.setItemId(rs.getInt("item_id"));
item.setItemName(rs.getString("item_name"));
item.setArrivalDate(rs.getDate("arrival_date"));
item.setBranchName(rs.getString("branch_name"));
item.setItemCategory(rs.getString("item_category"));
items.add(item);
}

// Store the items list in the request scope


request.setAttribute("items", items);

// Forward the request to the JSP file


RequestDispatcher dispatcher = request.getRequestDispatcher("itemList.jsp");
dispatcher.forward(request, response);

} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
// Close the database resources
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
itemList.jsp:

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


pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Arrival of New Items</title>
</head>
<body>
<h1>Arrival of New Items</h1>
<form action="ItemServlet" method="get">
<label for="selectedMonth">Select a month:</label>
<input type="month" id="selectedMonth" name="selectedMonth">
<input type="submit" value="Submit">
</form>
<hr>
<c:if test="${not empty items}">
<table>
<thead>
<tr>
<th>Item ID</th>
<th>Item Name</th>
<th>Arrival Date</th>
<th>Branch Name</th>
<th> Item Category</th>
</tr>
</thead>
<tbody>
<c:forEach var="item" items="${items}">
<tr>
<td>${item.itemId}</td>
<td>${item.itemName}</td>
<td>${item.arrivalDate}</td>
<td>${item.branchName}</td>
<td>${item.itemCategory}</td>
</tr>
</c:forEach>
</tbody>
</table>
</c:if>
</body>
</html>

Item.java:
public class Item {

private int itemId;


private String itemName;
private Date arrivalDate;
private String branchName;
private String itemCategory;

public int getItemId() {


return itemId;
}
public void setItemId(int itemId) {
this.itemId = itemId;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public Date getArrivalDate() {
return arrivalDate;
}
public void setArrivalDate(Date arrivalDate) {
this.arrivalDate = arrivalDate;
}
public String getBranchName() {
return branchName;
}
public void setBranchName(String branchName) {
this.branchName = branchName;
}
public String getItemCategory() {
return itemCategory;
}
public void setItemCategory(String itemCategory) {
this.itemCategory = itemCategory;
}
}

Lab Assignment: 3

Write a program using Servlet and JDBC for developing an online submission of an
examination form. You are required to create a database comprising of the following
fields:-
I. Student Name
II. Enrollment No.
III. Course Code (s)
IV. Regional Center Code
V. E- mail Id.

Sol.
we will create a form to take input from the user:
exam-form.jsp:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Exam Form Submission</title>
</head>
<body>
<h1>Exam Form Submission</h1>
<form method="post" action="submit-form">
<label for="name">Student Name:</label>
<input type="text" id="name" name="name" required><br><br>

<label for="enrollment">Enrollment No.:</label>


<input type="text" id="enrollment" name="enrollment" required><br><br>

<label for="course">Course Code:</label>


<input type="text" id="course" name="course" required><br><br>

<label for="center">Regional Center Code:</label>


<input type="text" id="center" name="center" required><br><br>

<label for="email">E-mail Id:</label>


<input type="email" id="email" name="email" required><br><br>

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


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

Next, we will create a servlet to handle form submission and insert the data into the database:
ExamFormServlet.java:
import java.io.IOException;
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("/submit-form")
public class ExamFormServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

// JDBC driver name and database URL


private static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
private static final String DB_URL = "jdbc:mysql://localhost:3306/examformdb";

// Database credentials
private static final String USER = "username";
private static final String PASS = "password";

// SQL statement to insert data into the database


private static final String INSERT_QUERY = "INSERT INTO examform (name, enrollment,
course, center, email) VALUES (?, ?, ?, ?, ?)";

protected void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

// Get the form data


String name = request.getParameter("name");
String enrollment = request.getParameter("enrollment");
String course = request.getParameter("course");
String center = request.getParameter("center");
String email = request.getParameter("email");

// Insert the data into the database


try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
PreparedStatement stmt = conn.prepareStatement(INSERT_QUERY)) {

stmt.setString(1, name);
stmt.setString(2, enrollment);
stmt.setString(3, course);
stmt.setString(4, center);
stmt.setString(5, email);

int rows = stmt.executeUpdate();

if (rows > 0) {
response.getWriter().println("Form submitted successfully!");
} else {
response.getWriter().println("Failed to submit form!");
}

} catch (SQLException e) {
response.getWriter().println("Database error: " + e.getMessage());
}
}
}

We also need to create a database with the required fields:


examformdb.sql:
CREATE DATABASE examformdb;

USE examformdb;

CREATE TABLE exam_form (


id INT PRIMARY KEY AUTO_INCREMENT,
student_name VARCHAR(255) NOT NULL,
enrollment_no VARCHAR(20) NOT NULL,
course_code VARCHAR(20) NOT NULL,
regional_center_code VARCHAR(20) NOT NULL,
email VARCHAR(255) NOT NULL
);

You might also like