KEMBAR78
Advanced JAVA and J2EE - PartALabPrograms | PDF | Computing | Software Engineering
0% found this document useful (0 votes)
52 views26 pages

Advanced JAVA and J2EE - PartALabPrograms

The document contains a series of Java programming exercises covering various topics such as converting numbers to words, finding second maximum and minimum values, performing operations on ArrayLists, and manipulating strings. Each exercise includes detailed code examples along with explanations of the logic and functionality. The document serves as a practical guide for advanced Java and J2EE lab programs.

Uploaded by

akshayamith887
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)
52 views26 pages

Advanced JAVA and J2EE - PartALabPrograms

The document contains a series of Java programming exercises covering various topics such as converting numbers to words, finding second maximum and minimum values, performing operations on ArrayLists, and manipulating strings. Each exercise includes detailed code examples along with explanations of the logic and functionality. The document serves as a practical guide for advanced Java and J2EE lab programs.

Uploaded by

akshayamith887
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/ 26

Advanced JAVA and J2EE​ ​ ​ LAB Programs Explained

PART A
1. Write a program to convert numbers into words using Enumerations with
constructors, methods and instance variables.(INPUT RANGE-0 TO 99999) EX: 36
THIRTY SIX
Code:
import java.util.*;
public class Enumeration {
private enum Units {
ZERO(""), ONE("ONE"), TWO("TWO"), THREE("THREE"), FOUR("FOUR"), FIVE("FIVE"), SIX("SIX"),
SEVEN("SEVEN"), EIGHT("EIGHT"), NINE("NINE");

private final String word;

Units(String word) {
this.word = word;
}
public String getWord() {
return word;
}
}

private enum Teens {


TEN("TEN"), ELEVEN("ELEVEN"), TWELVE("TWELVE"), THIRTEEN("THIRTEEN"),
FOURTEEN("FOURTEEN"),
FIFTEEN("FIFTEEN"), SIXTEEN("SIXTEEN"), SEVENTEEN("SEVENTEEN"), EIGHTEEN("EIGHTEEN"),
NINETEEN("NINETEEN");

private final String word;

Teens(String word) {
this.word = word;
}
public String getWord() {
return word;
}
}

private enum Tens {


TWENTY("TWENTY"), THIRTY("THIRTY"), FORTY("FORTY"), FIFTY("FIFTY"), SIXTY("SIXTY"),
SEVENTY("SEVENTY"), EIGHTY("EIGHTY"), NINETY("NINETY");
private final String word;

Tens(String word) {
this.word = word;
}

public String getWord() {


return word;
}
}

public static void main(String[] args) {


System.out.println("Enter the number:");
Scanner sc = new Scanner(System.in);
int number = sc.nextInt();
System.out.println(convertToWords(number));
}

public static String convertToWords(int number) {


if (number == 0) {
return "ZERO";
}

if (number < 0 || number > 99999) {


return "Number out of range";
}

String word = "";


if (number / 1000 > 0) {
word += convertToWords(number / 1000) + " THOUSAND ";
number %= 1000;
}

if (number / 100 > 0) {


word += Units.values()[number / 100].getWord() + " HUNDRED ";
number %= 100;
}

if (number >= 20) {


word += Tens.values()[(number / 10) - 2].getWord() + " ";
number %= 10;
} else if (number >= 10) {
word += Teens.values()[number - 10].getWord() + " ";
number = 0;
}
if (number > 0) {
word += Units.values()[number].getWord();
}
return word.trim();
}
}
/*
Example:

Program Trace with Input 3:


1.​ Input: User enters 3.
2.​ Initial Checks:
●​ number == 0: false
●​ number < 0 || number > 99999: false
3.​ Initialization: word = ""
4.​ Thousands Conversion: Skip (condition false)
5.​ Hundreds Conversion: Skip (condition false)
6.​ Tens and Teens Conversion: Skip both (conditions false)
7.​ Units Conversion:
●​ word += Units.values()[3].getWord(): word = "THREE"
8.​ Return: Return "THREE"
9.​ Output: Print "THREE"

Program Trace with Input 2345:


1.​ Input: User enters 2345.
2.​ Initial Checks:
●​ number == 0: false
●​ number < 0 || number > 99999: false
3.​ Initialization: word = ""
4.​ Thousands Conversion:
●​ Call convertToWords(2):
●​ 2 == 0: false
●​ 2 < 0 || 2 > 99999: false
●​ Initialize word = ""
●​ Skip thousands, hundreds, tens, and teens
●​ word = "TWO"
●​ Return "TWO"
●​ word = "TWO THOUSAND "
●​ number = 2345 % 1000 = 345
5.​ Hundreds Conversion:
●​ word += Units.values()[3].getWord() = "THREE"
●​ word = "TWO THOUSAND THREE HUNDRED "
●​ number = 345 % 100 = 45
6.​ Tens Conversion:
●​ word += Tens.values()[(45 / 10) - 2].getWord() = "FORTY"
●​ word = "TWO THOUSAND THREE HUNDRED FORTY "
●​ number = 45 % 10 = 5
7.​ Units Conversion:
●​ word += Units.values()[5].getWord() = "FIVE"
●​ word = "TWO THOUSAND THREE HUNDRED FORTY FIVE"
8.​ Return: Return "TWO THOUSAND THREE HUNDRED FORTY FIVE"
9.​ Output: Print "TWO THOUSAND THREE HUNDRED FORTY FIVE"

Program Trace with Input 100:


1.​ Input: User enters 100.
2.​ Initial Checks:
●​ number == 0: false
●​ number < 0 || number > 99999: false
3.​ Initialization: word = ""
4.​ Thousands Conversion: Skip (condition false)
5.​ Hundreds Conversion:
●​ word += Units.values()[1].getWord() = "ONE"
●​ word = "ONE HUNDRED "
●​ number = 100 % 100 = 0
6.​ Tens and Teens Conversion: Skip both (conditions false)
7.​ Units Conversion: Skip (number is 0)
8.​ Return: Return "ONE HUNDRED"
9.​ Output: Print "ONE HUNDRED"
*/

2. Find the second maximum and second minimum in a set of numbers using auto
boxing and unboxing.
Code:
import java.util.Arrays;
import java.util.Scanner;
public class SecondMinMaxFinder {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
int n = scanner.nextInt();
//Creates an array of Integer objects to store the numbers (uses auto-boxing to convert int to
Integer).
Integer[] numbers = new Integer[n];
//Prompts the user to enter the number of elements and reads the input.
System.out.println("Enter the elements:");
for (int i = 0; i < n; i++) {
numbers[i] = scanner.nextInt();
}
//Calls the findSecondMinMax method to find and print the second minimum and maximum
numbers.
findSecondMinMax(numbers);
//Closes the Scanner object to release the resource.
scanner.close();
}
public static void findSecondMinMax(Integer[] numbers) {
//Sorts the array in ascending order.
Arrays.sort(numbers);
// Find Second minimum
int secondMin = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (!numbers[i].equals(numbers[i - 1])) {
secondMin = numbers[i];
break;
}
}
// Find Second maximum
int secondMax = numbers[numbers.length - 1];
for (int i = numbers.length - 2; i >= 0; i--) {
if (!numbers[i].equals(numbers[i + 1])) {
secondMax = numbers[i];
break;
}
}
System.out.println("Second minimum: " + secondMin);
System.out.println("Second maximum: " + secondMax);
}
}
/*
This Java program finds the second smallest and second largest numbers in a set of
user-input numbers using auto-boxing and unboxing.
import java.util.Arrays;
import java.util.Scanner;
●​ Arrays: Provides utility methods for array manipulation.
●​ Scanner: Allows reading input from the user.
*/

3. Write a menu driven program to create an Arraylist and perform the following
operations
I.​ Adding elements.
II.​ Sorting elements.
III.​ Replace an element with another.
IV.​ Removing an element.
V.​ Displaying all the elements.
VI.​ Adding an element between two elements.
Code:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

public class ArrayListOperations {

public static void main(String[] args) {


ArrayList<Integer> arrayList = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
int choice;

do {
System.out.println("\n--- MENU ---");
System.out.println("1. Add elements");
System.out.println("2. Sort elements");
System.out.println("3. Replace an element");
System.out.println("4. Remove an element");
System.out.println("5. Display all elements");
System.out.println("6. Add an element between two elements");
System.out.println("7. Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();

switch (choice) {
case 1:
addElements(arrayList, scanner);
break;
case 2:
sortElements(arrayList);
break;
case 3:
replaceElement(arrayList, scanner);
break;
case 4:
removeElement(arrayList, scanner);
break;
case 5:
displayElements(arrayList);
break;
case 6:
addBetweenElements(arrayList, scanner);
break;
case 7:
System.out.println("Exiting...");
break;
default:
System.out.println("Invalid choice!");
}
} while (choice != 7);

scanner.close();
}

private static void addElements(ArrayList<Integer> arrayList, Scanner scanner) {


System.out.print("Enter the number of elements to add: ");
int n = scanner.nextInt();
System.out.println("Enter the elements:");
for (int i = 0; i < n; i++) {
arrayList.add(scanner.nextInt());
}
System.out.println("Elements added successfully.");
}

private static void sortElements(ArrayList<Integer> arrayList) {


if (arrayList.isEmpty()) {
System.out.println("The ArrayList is empty. There are no elements to sort.");
return;
}
Collections.sort(arrayList);
System.out.println("Elements sorted successfully.");
}

private static void replaceElement(ArrayList<Integer> arrayList, Scanner scanner) {


if (arrayList.isEmpty()) {
System.out.println("The ArrayList is empty. There are no elements to replace.");
return;
}
System.out.print("Enter the index of the element to replace: ");
int index = scanner.nextInt();
System.out.print("Enter the new element: ");
int newValue = scanner.nextInt();
arrayList.set(index, newValue);
System.out.println("Element replaced successfully.");
}

private static void removeElement(ArrayList<Integer> arrayList, Scanner scanner) {


if (arrayList.isEmpty()) {
System.out.println("The ArrayList is empty. There are no elements to remove.");
return;
}
System.out.print("Enter the index of the element to remove: ");
int index = scanner.nextInt();
arrayList.remove(index);
System.out.println("Element removed successfully.");
}

private static void displayElements(ArrayList<Integer> arrayList) {


if (arrayList.isEmpty()) {
System.out.println("The ArrayList is empty.");
return;
}
System.out.println("Elements in the ArrayList:");
for (Integer element : arrayList) {
System.out.print(element + " ");
}
System.out.println();
}

private static void addBetweenElements(ArrayList<Integer> arrayList, Scanner scanner) {


if (arrayList.isEmpty()) {
System.out.println("The ArrayList is empty. There are no elements to add between.");
return;
}
System.out.print("Enter the index where you want to add the element: ");
int index = scanner.nextInt();
if (index < 0 || index > arrayList.size()) {
System.out.println("Invalid index. Please enter a valid index.");
return;
}
System.out.print("Enter the new element: ");
int newValue = scanner.nextInt();
arrayList.add(index, newValue);
System.out.println("Element added successfully.");
}
}

/*
1.​ Setup:
●​ An empty ArrayList named arrayList is created to store integers.
●​ A Scanner object is created to read user input.
●​ The program enters a loop where it displays a menu of options and processes
the user's choice.
2.​ Menu Options:
●​ The menu has seven options:
1.​ Add elements to the ArrayList.
2.​ Sort the elements in the ArrayList.
3.​ Replace an element in the ArrayList.
4.​ Remove an element from the ArrayList.
5.​ Display all elements in the ArrayList.
6.​ Add an element at a specific position in the ArrayList.
7.​ Exit the program.
3.​ Loop Until Exit:
●​ The program keeps showing the menu and performing actions based on the
user's choice until the user selects the "Exit" option.

Explanation of Each Method


1.​ addElements:
●​ Prompts the user to enter the number of elements they want to add.
●​ Reads that many integers from the user and adds them to the ArrayList.
●​ Displays a success message.
2.​ sortElements:
●​ Checks if the ArrayList is empty. If it is, it displays a message saying there are
no elements to sort.
●​ Otherwise, it sorts the ArrayList in ascending order using Collections.sort()
and displays a success message.
3.​ replaceElement:
●​ Checks if the ArrayList is empty. If it is, it displays a message saying there are
no elements to replace.
●​ Prompts the user to enter the index of the element they want to replace.
●​ Validates the index to ensure it is within the bounds of the ArrayList.
●​ If the index is valid, it prompts the user for the new value and replaces the
element at the specified index with the new value.
●​ Displays a success message.
4.​ removeElement:
●​ Checks if the ArrayList is empty. If it is, it displays a message saying there are
no elements to remove.
●​ Prompts the user to enter the index of the element they want to remove.
●​ Validates the index to ensure it is within the bounds of the ArrayList.
●​ If the index is valid, it removes the element at that index.
●​ Displays a success message.
5.​ displayElements:
●​ Checks if the ArrayList is empty. If it is, it displays a message saying the
ArrayList is empty.
●​ Otherwise, it prints all the elements in the ArrayList.
6.​ addBetweenElements:
●​ Checks if the ArrayList is empty. If it is, it displays a message saying there are
no elements to add between.
●​ Prompts the user to enter the index where they want to add the new element.
●​ Validates the index to ensure it is within the bounds of the ArrayList.
●​ If the index is valid, it prompts the user for the new value and inserts it at the
specified position.
●​ Displays a success message.

*/

4. Write a java program to find words with even number of characters in a string,
then swap the pair of characters in those words and also toggle the characters in a
given string
EX: Good Morning everyone
Output: oGdo vereoyen
gOOD mORNING EVERYONE
Code:
import java.util.Scanner;
public class StringManipulations {
// Method to toggle the case of each character
public static String toggleCharacters(String str) {
StringBuilder result = new StringBuilder();
// Iterating through each character in ‘str’
for (char ch : str.toCharArray()) {
if (Character.isUpperCase(ch)) {
result.append(Character.toLowerCase(ch));
} else if (Character.isLowerCase(ch)) {
result.append(Character.toUpperCase(ch));
} else {
result.append(ch);
}
}
return result.toString();
}

public static String swapCharactersInEvenLengthWords(String str) {


StringBuilder result = new StringBuilder();
String[] words = str.split("\\s+");
for (String word : words) {
if (word.length() % 2 == 0) {
for (int i = 0; i < word.length() - 1; i += 2) {
result.append(word.charAt(i + 1)).append(word.charAt(i));
}
}
result.append(" ");
}
return result.toString().trim();
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.println("Enter input string:");


String input = scanner.nextLine();

String result1 = swapCharactersInEvenLengthWords(input);


String result2 = toggleCharacters(input);
System.out.println("Output 1: " + result1);
System.out.println("Output 2: " + result2);
scanner.close();
}
}
/*
for (char ch : str.toCharArray()) {
if (Character.isUpperCase(ch)) {
result.append(Character.toLowerCase(ch));
} else if (Character.isLowerCase(ch)) {
result.append(Character.toUpperCase(ch));
} else {
result.append(ch);
}
}
1.​ Initialization:
●​ str.toCharArray() converts the input string into a character array.
●​ for (char ch : str.toCharArray()) iterates through each character (ch) in this array.

2.​ Character Processing:


●​ If the character is uppercase:
if (Character.isUpperCase(ch)) {
result.append(Character.toLowerCase(ch));
}
●​ Character.isUpperCase(ch): Checks if ch is an uppercase letter (e.g., 'A', 'B', 'C').
●​ Character.toLowerCase(ch): Converts the uppercase character ch to its
corresponding lowercase character (e.g., 'A' to 'a').
●​ result.append(Character.toLowerCase(ch)): Appends the lowercase character to the
result StringBuilder.
3. ​ If the character is lowercase:
else if (Character.isLowerCase(ch)) {
result.append(Character.toUpperCase(ch));
}
●​ Character.isLowerCase(ch): Checks if ch is a lowercase letter (e.g., 'a', 'b', 'c').
●​ Character.toUpperCase(ch): Converts the lowercase character ch to its corresponding
uppercase character (e.g., 'a' to 'A').
●​ result.append(Character.toUpperCase(ch)): Appends the uppercase character to the
result StringBuilder.
●​ If the character is neither uppercase nor lowercase:

else {
result.append(ch);
}
●​ This branch handles characters that are neither uppercase nor lowercase, such as digits,
punctuation, spaces, etc.
●​ result.append(ch): Appends the character as it is to the result StringBuilder.
—-------------------------------------
public static String swapCharactersInEvenLengthWords(String str) {
StringBuilder result = new StringBuilder();
String[] words = str.split("\\s+");
for (String word : words) {
if (word.length() % 2 == 0) {
for (int i = 0; i < word.length() - 1; i += 2) {
result.append(word.charAt(i + 1)).append(word.charAt(i));
}
} else {
result.append(word);
}
result.append(" ");
}
return result.toString().trim();
}
1.​ Initialize StringBuilder:
●​ StringBuilder result = new StringBuilder();
●​ This will hold the final modified string.
2.​ Split the Input String into Words:
●​ String[] words = str.split("\\s+");
●​ This splits the input string into words based on one or more whitespace characters.
3.​ Process Each Word:
●​ for (String word : words) {
●​ Loop through each word in the words array.
4.​ Check for Even Length:
●​ if (word.length() % 2 == 0) {
●​ Check if the word has an even number of characters.
5.​ Swap Adjacent Characters in Even Length Words:
●​ for (int i = 0; i < word.length() - 1; i += 2) {
●​ Loop through the characters of the word, two at a time.
●​ result.append(word.charAt(i + 1)).append(word.charAt(i));
●​ Swap the characters at positions i and i + 1 and append them to result.
6.​ Handle Odd Length Words:
●​ If the word has an odd length, append it to result without modification.
●​ else { result.append(word); }
7.​ Append Space After Each Word:
●​ result.append(" ");
●​ Add a space after each word to separate them.
8.​ Trim the Final Result:
●​ return result.toString().trim();
●​ Convert StringBuilder to a string and trim any trailing spaces.

Example
Let's take the input string: "hello world abc defgh"
1.​ Split the String:
●​ words = ["hello", "world", "abc", "defgh"]
2.​ Process Each Word:
●​ "hello" (odd length):
●​ Append as is: "hello "
●​ "world" (odd length):
●​ Append as is: "hello world "
●​ "abc" (odd length):
●​ Append as is: "hello world abc "
●​ "defghi" (even length):
●​ Swap characters:
●​ First swap: 'e' and 'd' -> "ed"
●​ Second swap: 'g' and 'f' -> "gf"
●​ Third swap: 'i' and h' -> "ih"
●​ Append: "hello world abc edgfih "
3.​ Final Result:
●​ Trim trailing space: "hello world abc edgfih"

Output
●​ For the input "hello world abc defghi", the output will be "hello world abc edgfih".
*/
5. Write a Servlet program that accepts the age and name and displays if the user is
eligible for voting or not

Code:
//index.html page in Web Pages folder
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Voting Eligibility Checker</title>
<style>
h2 {
color: blue;
}
label {
font-weight: bold;
}
input[type="text"],
input[type="number"] {
width: 200px;
}
input[type="submit"] {
margin: auto;
padding: 10px 20px;
cursor: pointer;
font-size: 16px;
border-radius: 5px;
}
form {
width: 400px;
padding: 10px;
background-color: lightgreen;
border: 2px solid black;
}
.message {
font-size: 18px;
font-weight: bold;
}
.message.green {
color: green;
}
.message.red {
color: red;
}
</style>
</head>
<body>
<form action="voting" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br><br>
<label for="age">Age:</label>
<input type="number" id="age" name="age" required><br><br>
<input type="submit" value="Check Voting Eligibility">
</form>
<div class="message" id="messagePlaceholder"><!-- Message will be displayed here --></div>
</body>
</html>

//VotingServlet.java servlet file in Source Packages folder


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

@WebServlet("/voting")
public class VotingServlet extends HttpServlet {

protected void processRequest(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();

// Retrieve user inputs from the form


String name = request.getParameter("name");
String ageParam = request.getParameter("age");

// Parse age parameter to integer


int age = Integer.parseInt(ageParam);

// Check eligibility for voting


String message;
String messageColor;
if (age >= 18) {
message = "Congratulations, " + name + "! You are eligible to vote.";
messageColor = "green";
} else {
message = "Sorry, " + name + ". You are not eligible to vote yet.";
messageColor = "red";
}

// Display the result


out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Voting Eligibility</title>");
out.println("<style>");
out.println("body { font-family: Arial, sans-serif; }");
out.println(".message { font-size: 18px; font-weight: bold; }");
out.println(".message.green { color: green; }");
out.println(".message.red { color: red; }");
out.println("</style>");
out.println("</head>");
out.println("<body>");
out.println("<h2>Voting Eligibility Checker</h2>");
out.println("<p class=\"message " + messageColor + "\">" + message + "</p>");
//out.println("<p class=\"message " + messageColor + "\">" + message + "</p>");
out.println("<a href=\"index.html\">Home</a>");
out.println("</body>");
out.println("</html>");
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
public String getServletInfo() {
return "Short description";
}
}
/*
This program consists of an HTML page (index.html) and a Java servlet (VotingServlet) that work
together to check if a user is eligible to vote based on their age.

Index.html File
This is a simple HTML page with a form to input the user's name and age, and a submit button to
send the data to the servlet.
●​ Form: It contains input fields for the user's name and age.
●​ Submit Button: When clicked, it sends the form data to the servlet (VotingServlet) for
processing.
●​ Message Placeholder: This is an empty <div> element with the class message. The message
about voting eligibility will be displayed here dynamically.

the <form action="voting"> attribute specifies the URL or endpoint to which the form data will be
submitted when the form is submitted.

VotingServlet.java
This is a Java servlet that handles the request sent from the HTML form, processes the user's input,
and sends back a response indicating if the user is eligible to vote.

Explanation of Key Parts:


1.​ Annotations (@WebServlet("/voting")): This annotation maps the servlet to the URL pattern
/voting, meaning it will handle requests sent to http://localhost:8080/yourAppName/voting.
2.​ doPost Method: This method is invoked when the form is submitted via POST request. It calls
processRequest method to handle the request.
3.​ processRequest Method: This method processes the user's input, checks if the age is greater
than or equal to 18, and generates an appropriate message.
●​ Retrieving Form Data: It retrieves the name and age parameters from the request.
●​ Parsing Age: It converts the age parameter from String to integer.
●​ Checking Eligibility: It checks if the age is greater than or equal to 18. If yes, it sets a
message congratulating the user; otherwise, it sets a message indicating the user is
not eligible to vote.
●​ The if statement checks if the user's age (age) is greater than or equal to 18, which is
the legal voting age in many countries.
●​ If the condition is true (i.e., the user is eligible to vote), it sets the message variable
to a congratulatory message, including the user's name, and assigns the
messageColor variable the value "green".
●​ If the condition is false (i.e., the user is not eligible to vote), it sets the message
variable to a message indicating that the user is not eligible to vote yet, including the
user's name, and assigns the messageColor variable the value "red".
●​ Inside the <body> tag, it outputs the heading "Voting Eligibility Checker" (<h2>).
●​ The voting eligibility message (message) is displayed inside a paragraph (<p>). The
CSS class message is applied to style the text, and an additional class (green or red) is
applied based on the messageColor variable, determining whether the text color
should be green or red.
●​ Finally, it includes a link (<a>) to the home page (index.html).

●​ Sending Response: It constructs an HTML response dynamically using PrintWriter


and sends it back to the client. The response includes the message about voting
eligibility and a link to go back to the home page.
4.​ HTML Response: The response sent back includes HTML code to display the result in a nicely
formatted manner. It includes CSS styles for message colors (green for eligible, red for
ineligible).
5.​ doGet Method: This method is overridden to call processRequest for GET requests as well,
ensuring both GET and POST requests are handled similarly.

Summary:
●​ HTML Page (index.html): Provides a user interface to input name and age.
●​ Java Servlet (VotingServlet): Processes the form data, checks eligibility, and sends back a
response indicating if the user is eligible to vote.
When a user enters their name and age in the form and submits it, the servlet receives the data,
processes it, and sends back a response dynamically, informing the user about their voting eligibility.

*/

6. Write a JSP program to print the first 10 Fibonacci and 10 prime numbers.
Code:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h2>Fibonacci Numbers:</h2>
<%
// Calculate and print the first 10 Fibonacci numbers
int n = 10;
int a = 0, b = 1;
out.println(a + "&nbsp;&nbsp;");
out.println(b + "&nbsp;&nbsp;");
for (int i = 2; i < n; i++) {
int next = a + b;
out.println(next + "&nbsp;&nbsp;c");
a = b;
b = next;
}
%>

<h2>Prime Numbers:</h2>
<%
// Calculate and print the first 10 prime numbers
int count = 0;
int num = 2;
while (count < 10) {
boolean isPrime = true;
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
out.println(num + " ");
count++;
}
num++;
}
%>
</body>
</html>

/*
<%
// Calculate and print the first 10 Fibonacci numbers
int n = 10;
int a = 0, b = 1;
out.println(a + "&nbsp;&nbsp;");
out.println(b + "&nbsp;&nbsp;");
for (int i = 2; i < n; i++) {
int next = a + b;
out.println(next + "&nbsp;&nbsp;");
a = b;
b = next;
}
%>
1.​ Variables Initialization:
●​ int n = 10;: Specifies that we want the first 10 Fibonacci numbers.
●​ int a = 0, b = 1;: Initializes the first two Fibonacci numbers.
2.​ Printing the First Two Numbers:
●​ out.println(a + "&nbsp;&nbsp;");: Prints 0 followed by two non-breaking spaces.
●​ out.println(b + "&nbsp;&nbsp;");: Prints 1 followed by two non-breaking spaces.
3.​ Loop to Generate and Print Fibonacci Numbers:
●​ for (int i = 2; i < n; i++) {: Starts a loop from 2 to n-1 (8 iterations).
●​ int next = a + b;: Calculates the next Fibonacci number.
●​ out.println(next + "&nbsp;&nbsp;");: Prints the next Fibonacci number followed by
two non-breaking spaces.
●​ a = b;: Updates a to the previous b.
●​ b = next;: Updates b to the current next.

<h2>Prime Numbers:</h2>
<%
// Calculate and print the first 10 prime numbers
int count = 0;
int num = 2;
while (count < 10) {
boolean isPrime = true;
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
out.println(num + " ");
count++;
}
num++;
}
%>
1.​ Variables Initialization:
●​ int count = 0;: Counter to keep track of how many prime numbers have been found.
●​ int num = 2;: Starting number to check for prime numbers.
2.​ While Loop to Find Prime Numbers:
●​ while (count < 10) {: Loops until 10 prime numbers are found.
●​ boolean isPrime = true;: Assumes the current number is prime.
3.​ Inner Loop to Check Primality:
●​ for (int i = 2; i <= Math.sqrt(num); i++) {: Loops from 2 to the square root of num.
●​ if (num % i == 0) {: Checks if num is divisible by i.
●​ isPrime = false;: If divisible, num is not a prime number.
●​ break;: Exits the loop if a divisor is found.
4.​ Checking and Printing Prime Numbers:
●​ if (isPrime) {: If num is prime.
●​ out.println(num + " ");: Prints the prime number followed by a space.
●​ count++;: Increments the prime number count.
5.​ Increment the Number:
●​ num++;: Moves to the next number to check for primality.
*/

7. Write a JSP Program to design a shopping cart to add items, remove items and to
display items from the cart using Sessions.
Code:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Shopping Cart</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
h2, h3 {
color: #333;
}
table {
width: 100%;
border-collapse: collapse;
margin-top: 20px;
}
table, th, td {
border: 1px solid #ddd;
}
th, td {
padding: 10px;
text-align: left;
}
th {
background-color: #f2f2f2;
}
a{
text-decoration: none;
color: #333;
}
a:hover {
text-decoration: underline;
}
.form-container {
margin-top: 20px;
}
input[type="text"] {
width: 200px;
padding: 5px;
}
input[type="submit"] {
padding: 5px 10px;
cursor: pointer;
border: 1px solid #333;
background-color: #f2f2f2;
}
input[type="submit"]:hover {
background-color: #ddd;
}
</style>
</head>
<body>
<h2>Shopping Cart</h2>

<%-- Check if the session exists --%>


<% if (session.getAttribute("cart") == null) { %>
<%-- Initialize the cart if it doesn't exist --%>
<% session.setAttribute("cart", new java.util.ArrayList<String>()); %>
<% } %>

<%-- Add item to cart --%>


<% if (request.getParameter("addItem") != null) {
String item = request.getParameter("item");
((java.util.ArrayList<String>) session.getAttribute("cart")).add(item);
} %>
<%-- Remove item from cart --%>
<% if (request.getParameter("removeItem") != null) {
String itemToRemove = request.getParameter("itemToRemove");
((java.util.ArrayList<String>) session.getAttribute("cart")).remove(itemToRemove);
} %>

<%-- Display items in cart --%>


<h3>Items in Cart:</h3>
<table>
<tr>
<th>Item</th>
<th>Action</th>
</tr>
<% for (String item : (java.util.ArrayList<String>) session.getAttribute("cart")) { %>
<tr>
<td><%= item %></td>
<td><button><a href="?removeItem=true&itemToRemove=<%= item
%>">Remove</a></button></td>
</tr>
<% } %>
</table>

<%-- Form to add items to cart --%>


<div class="form-container">
<h3>Add Item to Cart:</h3>
<form method="post">
Item: <input type="text" name="item" required>
<input type="submit" name="addItem" value="Add to Cart">
</form>
</div>
</body>
</html>

/*
JSP tags and their purposes:
1.​ <% %>: Scriptlet Tags
●​ These tags are used to embed Java code directly into the JSP page.
●​ Anything written inside these tags is treated as Java code and executed on the server
side.
●​ Example: <% int x = 10; %>.

2.​ <%= %>: Expression Tags


●​ Expression tags are used to output the result of a Java expression directly into the
HTML page.
●​ They are often used to display dynamic content, such as variables or method return
values.
●​ Example: <%= x %> will output the value of the variable "x".
3.​ <%@ %>: Directive Tags
●​ Directive tags are used to provide instructions to the JSP container about how to
process the JSP page.
●​ They are used to include external resources, set page directives, import packages,
and more.
●​ Example: <%@ page language="java" contentType="text/html" %>.
4.​ <%! %>: Declaration Tags
●​ Declaration tags are used to declare variables and methods that are accessible
throughout the JSP page.
●​ Unlike scriptlet tags, the code inside declaration tags is placed outside the service
method and is treated as a class member.
●​ Example: <%! int y = 20; %>
5. ​ Comment tag: <%-- and --%>
*/

8. Write a Java Servlet program to Download a file and display it on the screen( A
link has to be provided in HTML, when the link is clicked the corresponding file has
to be displayed on screen).
Code:
/*This is a simple HTML file that contains a link to download a file.*/
//index.html file in Web Pages Folder
<!DOCTYPE html>
<html>
<head>
<title>File Download</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h3>Below is the link to download the File</h3>
<a href="FileDownloader?filename=myfile.txt">Download My CV</a>
</body>
</html>
/* An anchor element that creates a hyperlink to the servlet FileDownloader, with a query
parameter filename=mycv.txt.
*/
//FileDownloader.java Servlet File in Source Package Folder
import java.io.FileInputStream;
import java.io.OutputStream;
import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

public class FileDownloader extends HttpServlet {


protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Set the content type of the response to text/html with UTF-8 encoding
response.setContentType("text/html;charset=UTF-8");
// Retrieve the filename parameter from the request
String fname = request.getParameter("filename");
// Set the content type of the response to plain text
response.setContentType("text/plaintext");
// Set the Content-Disposition header to indicate a file attachment with the provided filename
response.setHeader("Content-Disposition", "attachment;filename=\"" + fname + "\"");
// The server gets ready to send the file data to the browser through the output stream.
OutputStream os = response.getOutputStream();
FileInputStream fis = new FileInputStream("c:\\bca\\myfile.txt");
int i = 0;
while ((i = fis.read()) != -1) {
os.write(i);
}
fis.close();
os.close();
}

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
public String getServletInfo() {
return "Short description";
}
}

/*
response.setHeader("Content-Disposition", "attachment;filename=\"" + fname + "\"");
●​ Purpose: This line tells the browser how to handle the file that is being sent from the server.
●​ Content-Disposition: This is a header in the HTTP response that gives instructions about how
the content should be handled.
●​ attachment: This part of the header tells the browser that the content should be
downloaded as a file, rather than displayed directly in the browser.
●​ filename="fname": This part of the header suggests a name for the file when it is
downloaded. fname is a variable containing the actual name of the file. For example, if
fname is "mycv.txt", the browser will suggest saving the file as mycv.txt.

*/

You might also like