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

My Java Practical File-2

The document contains a program that throws a custom exception if the user enters 0 when prompted to enter a number. It catches the custom exception using a try-catch block and prints the exception message. Any other exceptions are caught generically and the message is printed. Finally, a finally block prints a message that it is executed regardless of exceptions.

Uploaded by

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

My Java Practical File-2

The document contains a program that throws a custom exception if the user enters 0 when prompted to enter a number. It catches the custom exception using a try-catch block and prints the exception message. Any other exceptions are caught generically and the message is printed. Finally, a finally block prints a message that it is executed regardless of exceptions.

Uploaded by

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

Harlal Institute Of Management & Tchnology

Address:(8 Institutional area Knowledge Park I greater Noida


Uttar Pradesh)
201310

Estd.1998

A
Practical file of Java Programming and Dynamic Website Design
Subject Code:506

COURSE: Bachelor’s Of Computer Application (BCA)

Submitted To :- Submitted By :-
Narendra Upadhyay Sir Abhinay Rana

(BCA Vth Semester)


Roll No:210916106001
INDEX

S.NO. TITTLE NAME PAGE NO.


1. Write a program to display prime
number
2. Write a program to display factorial
3. Write a program to count the total
number of characters in a string
4. Write a program to copy all elements
of one array into another array
5. Write a program to create a class called
vehicle with a method called drive ().
Create a subclass called car that
overrides the drive() method to print “
Repairing a car”.
6. Write a program to create a user defined
Package
7. Write a program that throws an
exception and catch it using a try-catch
8. Write a program to create and start
multiple threads that a increment a
shared counter variable concurrently
9. Write a program to create a basic Applet
10. Write a program to create shape and fill
color in shape using Applet
11. Write a program to create a Buttons,
Canvas, Checkbox, Radio Buttons using
AWT control
12. Write a program to compare a given
string to the specified character
sequence
13. Write a program to print the result of
removing duplicates from a given string
14. Write a java program for handling mouse
event and key events
15. Write a java program that connect to a
database using JDBC
16. Write a java program to connect to a
database using JDBC and insert values
into it
17. Write a java program to connect to a
database using JDBC and delete values
from it
18. Write a java servlet program to handle
user form
19. Write a java servlet applications to print
the current date and time
20. Write a java servlet application to
demonstrate the session tracking in
servlet
21. Write a java servlet program to select
the record from the database
22. Write a JSP application to demonstrate
the mathematical operation
Program – 1
Write a program to display Prime Number

import java.util.Scanner;

public class PrimeNumbers {


public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);


System.out.print("Enter the upper limit: ");

int limit = scanner.nextInt();


System.out.println("Prime numbers up to " + limit + ":");
for (int num = 2; num <= limit; num++) {
if (isPrime(num)) {

System.out.print(num + " ");

}
}
}
// Function to check if a number is prime
private static boolean isPrime(int number) {
if (number <= 1) {

return false;

}
for (int i = 2; i <= Math.sqrt(number); i++) {
if (number % i == 0) {
return false;
}
}
return true;

}
}

Output:
Enter the upper limit: 20
Prime numbers up to 20:
2 3 5 7 11 13 17 19
Program – 2
Write a program to display factorial

import java.util.Scanner;

public class Factorial {


public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);


System.out.print("Enter a number: ");

int number = scanner.nextInt();

long factorial = 1;

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


factorial *= i;
}
System.out.println("Factorial of " + number + " is: " + factorial);
}
}

Output:
Enter a number: 5
Factorial of 5 is: 120
Program – 3
Write a program to count the total number of characters in a string

import java.util.Scanner;

public class CharacterCount {


public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);


System.out.print("Enter a string: ");

String inputString = scanner.nextLine();


int characterCount = countCharacters(inputString);
System.out.println("Total number of characters: " + characterCount);
}
// Function to count characters in a string

private static int countCharacters(String str) {

return str.length();
}
}

Output:
Enter a string: Hello World
Total number of characters: 11
Program – 4
Write a program to copy all elements of one array into another array

import java.util.Arrays;

public class ArrayCopy {


public static void main(String[] args) {

// Source array
int[] sourceArray = {1, 2, 3, 4, 5};
// Create a destination array with the same length as the source array
int[] destinationArray = new int[sourceArray.length];

// Copy elements from source to destination array


for (int i = 0; i < sourceArray.length; i++) {
destinationArray[i] = sourceArray[i];
}
// Display the contents of both arrays
System.out.println("Source Array: " + Arrays.toString(sourceArray));
System.out.println("Destination Array: " + Arrays.toString(destinationArray));
}
}

Output:
Source Array: [1, 2, 3, 4, 5]

Destination Array: [1, 2, 3, 4, 5]


Program – 5
Write a program to create a class called vehicle with a method called
drive (). Create a subclass called car that overrides the drive() method
to print “ Repairing a car ”.

// Base class

class Vehicle {

// Method in the base class


void drive() {
System.out.println("Driving a vehicle");
}
}

// Subclass inheriting from Vehicle


class Car extends Vehicle {
// Override the drive() method in the subclass
@Override
void drive() {
System.out.println("Repairing a car");
}
}
public class VehicleApp {
public static void main(String[] args) {

// Create an instance of the Car class


Car myCar = new Car();
// Call the drive() method on the Car instance
myCar.drive();

}
}

Output:
Repairing a car

Program – 6
Write a program to create a user defined Package

1. Create a directory named myPackage (this will be the package name).


2. Inside the myPackage directory, create a file named MyClass.java with the following
content:

// File: myPackage/MyClass.java

package myPackage; // Specify the package name


public class MyClass {

public void displayMessage() {


System.out.println("This is a message from MyClass in myPackage");
}
}
Create another file outside the myPackage directory (in the same directory where you will
compile and run the program) with a class that uses MyClass. Let's name this file
MainClass.java:

// File: MainClass.java
import myPackage.MyClass; // Import the user-defined package
public class MainClass {
public static void main(String[] args) {

// Create an instance of MyClass from the user-defined package


MyClass myObject = new MyClass();

// Call a method from MyClass


myObject.displayMessage();
}
}
Now, compile and run the program. Ensure that both files are in the same directory. Open a
terminal and execute the following commands:

javac myPackage/MyClass.java
javac MainClass.java

java MainClass

Output:
This is a message from MyClass in myPackage
Program – 7
Write a program that throws an exception and catch it using a try-
catch .

import java.util.Scanner;

public class ExceptionHandlingExample {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
System.out.print("Enter a number: ");
int number = scanner.nextInt();
if (number == 0) {
// Throw a custom exception if the user enters 0
throw new CustomException("Cannot divide by zero!");
}
int result = 10 / number;

System.out.println("Result of division: " + result);

} catch (CustomException e) {
System.out.println("Custom Exception caught: " + e.getMessage());
} catch (Exception e) {

// Catch any other exceptions


System.out.println("Exception caught: " + e.getMessage());

} finally {
// This block will be executed regardless of whether an exception occurred or not
System.out.println("Finally block executed");
}
}

}
// Custom exception class

class CustomException extends Exception {


public CustomException(String message) {
super(message);

}
}

Output:
1. Entering a non-zero number:

Enter a number: 2
Result of division: 5
Finally block executed
2. Entering 0 (to trigger the custom exception):
Enter a number: 0

Custom Exception caught: Cannot divide by zero!


Finally block executed
Program – 8
Write a program to create and start multiple threads that a increment
a shared counter variable concurrently

public class ConcurrentCounterExample {


public static void main(String[] args) {

// Create an instance of the shared Counter class


Counter counter = new Counter();

// Number of threads to create


int numThreads = 5;
// Create and start multiple threads
for (int i = 0; i < numThreads; i++) {
Thread thread = new Thread(new CounterIncrementer(counter));
thread.start();
}
// Wait for all threads to finish
try {
Thread.sleep(2000); // Adjust the sleep time based on the expected completion time of
threads
} catch (InterruptedException e) {
e.printStackTrace();
}
// Display the final counter value

System.out.println("Final Counter Value: " + counter.getValue());


}
}

// Shared Counter class


class Counter {
private int value = 0;

// Synchronized method to increment the counter

public synchronized void increment() {


value++;
}

// Getter method for the counter value


public int getValue() {
return value;
}
}
// Runnable class to increment the counter

class CounterIncrementer implements Runnable {


private Counter counter;

public CounterIncrementer(Counter counter) {


this.counter = counter;
}

@Override
public void run() {
for (int i = 0; i < 1000; i++) {
counter.increment();
}

}
}

Output:
Final Counter Value: 5000
Program – 9
Write a program to create a basic Applet

import java.applet.Applet;
import java.awt.Graphics;

public class BasicApplet extends Applet {


@Override
public void paint(Graphics g) {

// Draw a simple message on the applet window


g.drawString("Hello, this is a basic applet!", 20, 20);
}
}

Output:
Hello, this is a basic applet
Program – 10
Write a program to create shape and fill color in shape using Applet

import java.applet.Applet;
import java.awt.Color;

import java.awt.Graphics;

public class ShapeApplet extends Applet {


@Override
public void paint(Graphics g) {
// Draw a rectangle and fill it with a color

g.setColor(Color.blue); // Set the fill color to blue

g.fillRect(50, 50, 100, 80); // Draw a filled rectangle


// Draw a border around the rectangle
g.setColor(Color.black); // Set the border color to black

g.drawRect(50, 50, 100, 80); // Draw a border around the rectangle


}
}

Output:
Program – 11
Write a program to create a Buttons, Canvas, Checkbox, Radio Buttons
using AWT control

: Button -

import java.awt.*;

import java.awt.event.*;

public class ButtonDemo extends Frame

Button b1, b2;

ButtonDemo ()

b1 = new Button ("OK");

b2 = new Button ("CANCEL");

this.setLayout (null);

b1.setBounds (100, 100, 80, 40);;

b2.setBounds (200, 100, 80, 40);

this.add (b1);
this.add (b2);

this.setVisible (true);

this.setSize (300, 300);

this.setTitle ("button");

this.addWindowListener (new WindowAdapter ()

public void windowClosing (WindowEvent we)

System.exit (0);

});

public static void main (String args[])

new ButtonDemo ();

Output:
: Canvas –

import java.awt.*;

import java.awt.event.*;

public class CanvasDemo

private Frame mainFrame;

private Label headerLabel;

private Label statusLabel;

private Panel controlPanel;

public CanvasDemo ()

prepareGUI ();

}
public static void main (String[]args)

CanvasDemo awtControlDemo = new CanvasDemo ();

awtControlDemo.showCanvasDemo ();

private void prepareGUI ()

mainFrame = new Frame ("Java AWT Examples");

mainFrame.setSize (400, 400);

mainFrame.setLayout (new GridLayout (3, 1));

mainFrame.addWindowListener (new WindowAdapter ()

public void windowClosing (WindowEvent windowEvent)

System.exit (0);

});

headerLabel = new Label ();

headerLabel.setAlignment (Label.CENTER);

statusLabel = new Label ();


statusLabel.setAlignment (Label.CENTER);

statusLabel.setSize (350, 100);

controlPanel = new Panel ();

controlPanel.setLayout (new FlowLayout ());

mainFrame.add (headerLabel);

mainFrame.add (controlPanel);

mainFrame.add (statusLabel);

mainFrame.setVisible (true);

private void showCanvasDemo ()

headerLabel.setText ("Control in action: Canvas");

controlPanel.add (new MyCanvas ());

mainFrame.setVisible (true);

class MyCanvas extends Canvas

public MyCanvas ()

setBackground (Color.GRAY);
setSize (300, 300);

public void paint (Graphics g)

Graphics2D g2;

g2 = (Graphics2D) g;

g2.drawString ("It is a custom canvas area", 70,


70);

Output:

: Check box –

import java.awt.*;
import java.awt.event.*;

import java.applet.*;

/* <applet code="CheckboxDemo" width=250 height=200> </applet> */

public class CheckboxDemo extends Applet implements ItemListener

String msg = "";

Checkbox winXP, winVista, solaris, mac;

public void init ()

winXP = new Checkbox ("Windows XP", null, true);

winVista = new Checkbox ("Windows Vista");

solaris = new Checkbox ("Solaris");

mac = new Checkbox ("Mac OS");

add (winXP);

add (winVista);

add (solaris);

add (mac);

winXP.addItemListener (this);
winVista.addItemListener (this);

solaris.addItemListener (this);

mac.addItemListener (this);

public void itemStateChanged (ItemEvent ie)

repaint ();

// Display current state of the check boxes.

public void paint (Graphics g)

msg = "Current state: ";

g.drawString (msg, 6, 80);

msg = " Windows XP: " + winXP.getState ();

g.drawString (msg, 6, 100);

msg = " Windows Vista: " + winVista.getState ();

g.drawString (msg, 6, 120);

msg = " Solaris: " + solaris.getState ();

g.drawString (msg, 6, 140);


msg = " Mac OS: " + mac.getState ();

g.drawString (msg, 6, 160);

Output:

: Radio Button –

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

/* <applet code="CBGroup" width=250 height=200> </applet> */

public class RadiobuttonDemo extends Applet implements ItemListener

{
String msg = "";

Checkbox winXP, winVista, solaris, mac;

CheckboxGroup cbg;

public void init ()

cbg = new CheckboxGroup ();

winXP = new Checkbox ("Windows XP", cbg, true);

winVista = new Checkbox ("Windows Vista", cbg, false);

solaris = new Checkbox ("Solaris", cbg, false);

mac = new Checkbox ("Mac OS", cbg, false);

add (winXP);

add (winVista);

add (solaris);

add (mac);

winXP.addItemListener (this);

winVista.addItemListener (this);

solaris.addItemListener (this);

mac.addItemListener (this);

}
public void itemStateChanged (ItemEvent ie)

repaint ();

// Display current state of the check boxes.

public void paint (Graphics g)

msg = "Current selection: ";

msg += cbg.getSelectedCheckbox ().getLabel ();

g.drawString (msg, 6, 100);

Output:
Program – 12
Write a program to compare a given string to the specified character
sequence

public class StringComparisonExample {


public static void main(String[] args) {

// Given string
String inputString = "Hello, World!";
// Specified character sequence
String specifiedSequence = "hello";
// Case-sensitive comparison
boolean caseSensitiveResult = compareStringsCaseSensitive(inputString,
specifiedSequence);
System.out.println("Case-sensitive comparison result: " + caseSensitiveResult);

// Case-insensitive comparison

boolean caseInsensitiveResult = compareStringsCaseInsensitive(inputString,


specifiedSequence);
System.out.println("Case-insensitive comparison result: " + caseInsensitiveResult);

}
// Method for case-sensitive comparison

private static boolean compareStringsCaseSensitive(String str1, String str2) {


return str1.equals(str2);
}
// Method for case-insensitive comparison

private static boolean compareStringsCaseInsensitive(String str1, String str2) {


return str1.equalsIgnoreCase(str2);

}
}

Output:
Case-sensitive comparison result: false
Case-insensitive comparison result: true

Program – 13
Write a program to print the result of removing duplicates from a
given string

import java.util.LinkedHashSet;

public class RemoveDuplicatesExample {


public static void main(String[] args) {
// Given string with duplicates
String inputString = "programming";
// Remove duplicates using LinkedHashSet

String result = removeDuplicates(inputString);

// Print the result


System.out.println("Original String: " + inputString);
System.out.println("String after removing duplicates: " + result);
}

// Method to remove duplicates from a string

private static String removeDuplicates(String str) {

char[] chars = str.toCharArray();


// LinkedHashSet maintains the order of characters while removing duplicates
LinkedHashSet<Character> uniqueChars = new LinkedHashSet<>();
for (char c : chars) {
uniqueChars.add(c);
}
// Reconstruct the string without duplicates

StringBuilder result = new StringBuilder();


for (char c : uniqueChars) {
result.append(c);
}

return result.toString();

}
}

Output:
Original String: programming
String after removing duplicates: progamin
Program – 14
Write a java program for handling mouse event and key events

import java.awt.*;
import java.awt.event.*;

public class MouseEventKeyEventExample extends Frame implements MouseListener,


KeyListener {
public MouseEventKeyEventExample() {

// Set frame properties


setTitle("Mouse and Key Event Example");
setSize(300, 200);
setVisible(true);
// Register mouse and key listeners

addMouseListener(this);
addKeyListener(this);

// Enable focus on the frame to receive key events


setFocusable(true);

// Set the default close operation


addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {

System.exit(0);
}
});
}
// MouseListener methods
public void mouseClicked(MouseEvent e) {
System.out.println("Mouse Clicked at (" + e.getX() + ", " + e.getY() + ")");
}

public void mousePressed(MouseEvent e) {


System.out.println("Mouse Pressed at (" + e.getX() + ", " + e.getY() + ")");
}
public void mouseReleased(MouseEvent e) {
System.out.println("Mouse Released at (" + e.getX() + ", " + e.getY() + ")");

public void mouseEntered(MouseEvent e) {


System.out.println("Mouse Entered");
}
public void mouseExited(MouseEvent e) {

System.out.println("Mouse Exited");
}
// KeyListener methods
public void keyTyped(KeyEvent e) {
System.out.println("Key Typed: " + e.getKeyChar());
}
public void keyPressed(KeyEvent e) {
System.out.println("Key Pressed: " + e.getKeyChar());
}

public void keyReleased(KeyEvent e) {


System.out.println("Key Released: " + e.getKeyChar());

}
public static void main(String[] args) {
new MouseEventKeyEventExample();
}
}

Output:
1. Mouse Click:

Mouse Clicked at (100, 50)


2. Mouse Press:

Mouse Pressed at (100, 50)


3. Mouse Release:
Mouse Released at (100, 50)
4. Mouse Enter:
Mouse Entered

5. Mouse Exit:
Mouse Exited

6. Key Type:
Key Typed: a
7. Key Press:

Key Pressed: a
8. Key Release:
Key Released: a
Program – 15
Write a java program that connect to a database using JDBC

import java.sql.Connection;

import java.sql.DriverManager;
import java.sql.SQLException;

public class DatabaseConnectionExample {


public static void main(String[] args) {

// JDBC URL, username, and password of MySQL server


String url = "jdbc:mysql://localhost:3306/your_database_name";
String user = "your_username";
String password = "your_password";
// Attempt to establish a connection

try (Connection connection = DriverManager.getConnection(url, user, password)) {


System.out.println("Connected to the database!");
// You can perform database operations here
} catch (SQLException e) {
System.err.println("Connection failed. Check the error details below:");
e.printStackTrace();

}
}
}

Output:
1. Successful Connection:
Connected to the database!
2. Connection Failure:

Connection failed. Check the error details below:

[SQLException Details]

Program – 16
Write a java program to connect to a database using JDBC and insert
values into it

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

import java.sql.SQLException;

public class InsertDataExample {


public static void main(String[] args) {

// JDBC URL, username, and password of MySQL server


String url = "jdbc:mysql://localhost:3306/your_database_name";
String user = "your_username";
String password = "your_password";

// Data to be inserted
String dataToInsert = "Hello, Database!";
// SQL query to insert data
String insertQuery = "INSERT INTO your_table_name (column_name) VALUES (?)";
// Attempt to establish a connection

try (Connection connection = DriverManager.getConnection(url, user, password);


PreparedStatement preparedStatement = connection.prepareStatement(insertQuery)) {
// Set the value to be inserted
preparedStatement.setString(1, dataToInsert);
// Execute the insertion query
int rowsAffected = preparedStatement.executeUpdate();
if (rowsAffected > 0) {
System.out.println("Data inserted successfully!");
} else {
System.out.println("Failed to insert data.");

}
} catch (SQLException e) {
System.err.println("Database operation failed. Check the error details below:");
e.printStackTrace();
}

}
}

Output:
1. Successful Insertion:
Data inserted successfully!
2. Failed Insertion:

Failed to insert data.


3. Connection Failure:

Database operation failed. Check the error details below:


[SQLException Details]

Program – 17
Write a java program to connect to a database using JDBC and delete
values from it

import java.sql.Connection;
import java.sql.DriverManager;

import java.sql.PreparedStatement;
import java.sql.SQLException;
public class DeleteDataExample {
public static void main(String[] args) {

// JDBC URL, username, and password of MySQL server


String url = "jdbc:mysql://localhost:3306/your_database_name";
String user = "your_username";
String password = "your_password";
// Data to be deleted

String dataToDelete = "Hello, Database!";


// SQL query to delete data

String deleteQuery = "DELETE FROM your_table_name WHERE column_name = ?";


// Attempt to establish a connection
try (Connection connection = DriverManager.getConnection(url, user, password);
PreparedStatement preparedStatement = connection.prepareStatement(deleteQuery)) {
// Set the value to be deleted

preparedStatement.setString(1, dataToDelete);

// Execute the deletion query


int rowsAffected = preparedStatement.executeUpdate();

if (rowsAffected > 0) {
System.out.println("Data deleted successfully!");
} else {
System.out.println("No matching data found for deletion.");
}
} catch (SQLException e) {

System.err.println("Database operation failed. Check the error details below:");

e.printStackTrace();

}
}
}

Output:
1. Successful Deletion:
Data deleted successfully!

2. No Matching Data for Deletion:


No matching data found for deletion.

3. Connection Failure:
Database operation failed. Check the error details below:
[SQLException Details]
Program – 18
Write a java servlet program to handle user form

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/userFormHandler")
public class UserFormHandlerServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
IOException {
// Set the content type of the response

response.setContentType("text/html");

// Get user input from the form


String userName = request.getParameter("username");
String userEmail = request.getParameter("email");

// Process the user input (in this example, just displaying it)
String outputMessage = "Hello, " + userName + "! Your email is: " + userEmail;

// Display the output message in the response


PrintWriter out = response.getWriter();

out.println("User Form Handling");


out.println(" + outputMessage + ");
}
}

<!DOCTYPE html>
<html>
<head>

<title>User Form</title>
</head>

<body>
<form action="/yourWebAppName/userFormHandler" method="post">

<label for="username">Username:</label>
<input type="text" id="username" name="username" required><br>
<label for="email">Email:</label>

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


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

Output:
User Form Handling
Hello, [username]! Your email is: [useremail]
Note: Replace [username] and [useremail] with the actual values entered by the user in the
form.
Program – 19
Write a java servlet applications to print the current date and time

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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

// Set the content type of the response


response.setContentType("text/html");
// Get the current date and time
Date currentDate = new Date();

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


String formattedDateTime = dateFormat.format(currentDate);

// Display the current date and time in the response


PrintWriter out = response.getWriter();
out.println("Current Date and Time");

out.println(" + formattedDateTime + ");


}
}

Output:
Current Date and Time

2024-01-26 15:30:00

Program – 20
Write a java servlet application to demonstrate the session tracking in
servlet

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

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

// Set the content type of the response


response.setContentType("text/html");
// Get or create a session

HttpSession session = request.getSession();


// Get the current visit count from the session

Integer visitCount = (Integer) session.getAttribute("visitCount");


// If visitCount is null, it's the first visit; set it to 1
if (visitCount == null) {
visitCount = 1;
} else {
// If visitCount is not null, increment it
visitCount++;
}
// Store the updated visitCount in the session
session.setAttribute("visitCount", visitCount);

// Display the visit count in the response


PrintWriter out = response.getWriter();
out.println("Session Tracking Demo");
out.println("Number of visits: " + visitCount + "");
}
}

Output:
Session Tracking Demo

Number of visits: 1

Session Tracking Demo

Number of visits: 2

Program – 21
Write a java servlet program to select the record from the database

import java.io.IOException;

import java.io.PrintWriter;
import java.sql.Connection;

import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

@WebServlet("/selectFromDatabase")

public class SelectFromDatabaseServlet extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws


IOException {

// Set the content type of the response


response.setContentType("text/html");
// JDBC URL, username, and password of MySQL server
String url = "jdbc:mysql://localhost:3306/your_database_name";

String user = "your_username";


String password = "your_password";
// SQL query to select records
String selectQuery = "SELECT * FROM your_table_name";
try (Connection connection = DriverManager.getConnection(url, user, password);
PreparedStatement preparedStatement = connection.prepareStatement(selectQuery);
ResultSet resultSet = preparedStatement.executeQuery()) {

// Display the selected records in the response


PrintWriter out = response.getWriter();
out.println("Selected Records from Database");
while (resultSet.next()) {

// Assuming there are columns like "column1", "column2" in your table


String column1Value = resultSet.getString("column1");
String column2Value = resultSet.getString("column2");
out.println("Column1: " + column1Value + ", Column2: " + column2Value + " ");

}
out.println(" ");
} catch (SQLException e) {
System.err.println("Database operation failed. Check the error details below:");
e.printStackTrace();

}
}
}

Output:
Selected Records from Database
Column1: Value1, Column2: ValueA
<p>Column1: Value2, Column2: ValueB

<!-- ... Additional rows based on the database records -->


Program – 22
Write a JSP application to demonstrate the mathematical operation

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


<!DOCTYPE html>
<html>
<head>

<meta charset="UTF-8">
<title>Mathematical Operations</title>
</head>

<body>
<h2>Mathematical Operations</h2>
<form action="mathOperations.jsp" method="post">
Enter first number: <input type="text" name="num1"><br>

Enter second number: <input type="text" name="num2"><br>


<input type="submit" value="Add" name="operation">
<input type="submit" value="Subtract" name="operation">
<input type="submit" value="Multiply" name="operation">

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


</form>
<%-- JSP Scriptlet to perform mathematical operations based on user input --%>
<%
// Retrieve user input

String num1Str = request.getParameter("num1");


String num2Str = request.getParameter("num2");

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


// Check if numbers are provided and not empty
if (num1Str != null && num2Str != null && !num1Str.isEmpty() && !num2Str.isEmpty()) {

try {

// Convert string inputs to double


double num1 = Double.parseDouble(num1Str);
double num2 = Double.parseDouble(num2Str);
double result = 0;
// Perform the selected mathematical operation
switch (operation) {
case "Add":
result = num1 + num2;
break;
case "Subtract":

result = num1 - num2;


break;
case "Multiply":
result = num1 * num2;

break;

case "Divide":
if (num2 != 0) {
result = num1 / num2;
} else {
out.println("<p style='color: red;'>Error: Cannot divide by zero.</p>");

}
break;
}
// Display the result
out.println("<p>Result of " + operation + " operation: " + result + "</p>");
} catch (NumberFormatException e) {

out.println("<p style='color: red;'>Error: Invalid number format.</p>");


}
}
%>
</body>

</html>

Output:
1. Addition (e.g., entering 5 and 3):
Result of Add operation: 8.0
2. Subtraction (e.g., entering 7 and 2):
Result of Subtract operation: 5.0

3. Multiplication (e.g., entering 4 and 6):


Result of Multiply operation: 24.0
4. Division (e.g., entering 10 and 2):

Result of Divide operation: 5.0


5. Error (e.g., entering non-numeric values):
<p style='color: red;'>Error: Invalid number format.</p>
6. Error (e.g., attempting to divide by zero):
<p style='color: red;'>Error: Cannot divide by zero.</p>

You might also like