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

Advanced Java Lab Manual (1)

The document is a laboratory manual for the Advanced Java course (BIS402) at JSS Academy of Technical Education, Bengaluru. It outlines the course vision, mission, educational objectives, specific outcomes, and program outcomes, along with a detailed lesson plan and practical exercises. The manual includes various Java programming tasks such as using ArrayLists, string operations, Swing applications, and database connectivity using JDBC.
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)
2 views

Advanced Java Lab Manual (1)

The document is a laboratory manual for the Advanced Java course (BIS402) at JSS Academy of Technical Education, Bengaluru. It outlines the course vision, mission, educational objectives, specific outcomes, and program outcomes, along with a detailed lesson plan and practical exercises. The manual includes various Java programming tasks such as using ArrayLists, string operations, Swing applications, and database connectivity using JDBC.
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/ 33

JSS MAHAVIDYAPEETHA

JSS ACADEMY OF TECHNICAL EDUCATION, BENGALURU-60


DEPARTMENT OF INFORMATION SCIENCE AND
ENGINEERING
JSSATE Campus, Dr. Vishnuvardhana Main Road, Bengaluru – 560060

IV SEMESTER
ADVANCED JAVA LABORATORY LAB MANUAL

[BIS402]

Compiled By:

Dr. Nethravathi B Mr. Chetan R


Associate Professor, Assistant Professor,
Dept of Information Science & Dept of Information Science &
Engineering, JSSATEB Engineering, JSSATEB

Mrs. Punitha M
Assistant Professor,
Dept of Information Science & Engineering, JSSATEB

Signature of Faculty Signature of HOD


JSS MAHAVIDYAPEETHA

JSS ACADEMY OF TECHNICAL EDUCATION, BENGALURU-60


DEPARTMENT OF INFORMATION SCIENCE AND
ENGINEERING

VISION
To emerge as a centre for achieving academic excellence, by producing competent professionals
to meet the global challenges in the field of Information science and Technology.

MISSION
M1: To prepare the students as competent professionals to meet the advancements in the
industry and academia by imparting quality technical education.

M2: To enrich the technical ability of students to face the world with confidence, commitment,
and teamwork
.
M3: To inculcate and practice strong techno-ethical values to serve the society.

Program Educational Objectives (PEOs):


PEO1: To demonstrate analytical and technical problem-solving abilities.

PEO2: To be conversant in the developments of Information Science and Engineering, leading


towards the employability and higher studies.

PEO3: To engage in research and development leading to new innovations and products.

Program Specific Outcomes (PSOs):


PSO1: Apply the mathematical concepts for solving engineering problems by using appropriate
programming constructs
.
PSO2: Adaptability to software development methodologies.

PSO3: Demonstrate the knowledge towards the domain specific initiatives of Information
Science and Engineering.
Program Outcomes (POs):
Information Science and Engineering Graduates will be able to:

PO1 Apply the knowledge of mathematics, science, engineering fundamentals, and an


Engineering specialization to the solution of complex engineering problems.
PO2 Identify, formulate, review research literature, and analyze complex engineering
problems reaching substantiated conclusions using first principles of mathematics,
natural sciences, and engineering sciences.
PO3 Design solutions for complex engineering problems and design system components or
processes that meet the specified needs with appropriate consideration for the
public health and safety, and the cultural, societal, and environmental
considerations.
PO4 Use research-based knowledge and research methods including design of experiments,
analysis and interpretation of data, and synthesis of the information to provide valid
conclusions.
PO5 Create, select, and apply appropriate techniques, resources, and modern engineering and
IT tools including prediction and modeling to complex engineering activities with an
understanding of the limitations.
PO6 Apply reasoning informed by the contextual knowledge to assess societal, health, safety,
legal and cultural issues, and the consequent responsibilities relevant to the
professional engineering practice.
PO7 Understand the impact of the professional engineering solutions in societal and
environmental contexts, and demonstrate the knowledge of, and need for sustainable
development.
PO8 Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
PO9 Function effectively as an individual, and as a member or leader in diverse teams, and
in multidisciplinary settings.
PO10 Communicate effectively on complex engineering activities with the engineering
community and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give and
receive clear instructions.
PO11 Demonstrate knowledge and understanding of the engineering and management
principles and apply these to one’s own work, as a member and leader in a team, to
manage projects and in multidisciplinary environments.
PO12 Recognize the need for and have the preparation and ability to engage in independent
and life-long learning in the broadest context of technological change.
Lesson plan

Course Name: ADVANCED JAVA Course Code: BIS402 Sem/Sec: 4


Contact Hrs: 2 Total Hrs.: 20
Hours/Week
SEE Marks: NA CIE Marks:25 Exam Duration: NA

Course Outcomes:
At the end of the course, students will be able to

CO# CO Statement BLL


CO1 Apply appropriate collection class/interface to solve the given problem. L3

CO2 Utilize the concepts of String operations in Java. L3

CO3 Apply the concepts of Swings to build Java applications. L3

CO4 Develop web based applications using Java servlets and JSP. L3

CO5 Develop database applications using JDBC concepts. L3

Pre-requisites: OOPs with Java concepts, Basic programming concepts


Course overview: Understanding the fundamentals of collection framework, Demonstrate the
fundamental concepts of String operations and Swing applications, Design and develop web applications
using Java servlets and JSP, Apply database interaction through Java database Connectivity
Pedagogical/Innovative methods planned: Demonstration of simple projects on database
connectivity, Group assignment for J2EE projects
Clas Reference
Topics to be covered
s No. material and CO
Implement a java program to demonstrate creating an ArrayList, adding
1 elements, removing elements, sorting elements of ArrayList. Also T1 CO1
illustrate the use of toArray() method.
Develop a program to read random numbers between a given range that T1 CO1
2 are multiples of 2 and 5, sort the numbers according to tens place using
comparator.
Implement a java program to illustrate storing user defined classes in T1 CO1
3
collection.
Implement a java program to illustrate the use of different types of string T1 CO2
4 class constructors.
Implement a java program to illustrate the use of different types of T1 CO2
5 character extraction, string comparison, string search and string
modification methods.
Implement a java program to illustrate the use of different types of T1 CO2
6
StringBuffer methods
Demonstrate a swing event handling application that creates 2 buttons T1 CO3
7 Alpha and Beta and displays the text “Alpha pressed” when alpha button
is clicked and “Beta pressed” when beta button is clicked.
A program to display greeting message on the browser “Hello T2 CO4
8 UserName”, “How Are You?”, accept username from the client using
servlet.
A servlet program to display the name, USN, and total marks by accepting T2 CO4
9
student detail
A Java program to create and read the cookie for the given cookie name T2 CO4
10
as “EMPID” and its value as “AN2356”.
Write a JAVA Program to insert data into Student DATA BASE and T2 CO5
11 retrieve info based on particular queries(For example update, delete,
search etc…).
A program to design the Login page and validating the USER_ID and T2 CO5
12
PASSWORD using JSP and DataBase.

Total No. of Hours required as per VTU: 20


Total No. of classes planned: 10*2=20 hours

TEXT BOOKS (TB):


1. Y. Daniel Liang: Introduction to JAVA Programming, 7th Edition, Pearson Education, 2007.
2. Stephanie Bodoff et al: The J2EE Tutorial, 2nd Edition, Pearson Education,2004.
3. Uttam K Roy, Advanced JAVA programming, Oxford University press, 2015.

CIE for the practical component of the IPCC


● 15 marks for the conduction of the experiment and preparation of laboratory record, and 10
marks for the test to be conducted after the completion of all the laboratory sessions.
● On completion of every experiment/program in the laboratory, the students shall be evaluated
including viva-voce and marks shall be awarded on the same day.
● The CIE marks awarded in the case of the Practical component shall be based on the
continuous evaluation of the laboratory report. Each experiment report can be evaluated for 10
marks. Marks of all experiments’ write-ups are added and scaled down to 15 marks.
● The laboratory test (duration 02/03 hours) after completion of all the experiments shall be
conducted for 50 marks and scaled down to 10 marks.
● Scaled-down marks of write-up evaluations and tests added will be CIE marks for the
laboratory component of IPCC for 25 marks.
● The student has to secure 40% of 25 marks to qualify in the CIE of the practical component
of the IPCC.
Table of Content

Sl. Content Page No


No.
Implement a java program to demonstrate creating an ArrayList, adding
1 elements, removing elements, sorting elements of ArrayList. Also 7
illustrate the use of toArray() method.
Develop a program to read random numbers between a given range that
2 are multiples of 2 and 5, sort the numbers according to tens place using 9
comparator.
Implement a java program to illustrate storing user defined classes in
3 11
collection.
Implement a java program to illustrate the use of different types of string
4 13
class constructors.
Implement a java program to illustrate the use of different types of
5 character extraction, string comparison, string search and string 14
modification methods.
6 Implement a java program to illustrate the use of different types of
16
StringBuffer methods
Demonstrate a swing event handling application that creates 2 buttons
7 Alpha and Beta and displays the text “Alpha pressed” when alpha button 18
is clicked and “Beta pressed” when beta button is clicked.
A program to display greeting message on the browser “Hello
8 UserName”, “How Are You?”, accept username from the client using 20
servlet.
A servlet program to display the name, USN, and total marks by
9 22
accepting student detail
A Java program to create and read the cookie for the given cookie name
10 25
as “EMPID” and its value as “AN2356”.
Write a JAVA Program to insert data into Student DATA BASE and
11 retrieve info based on particular queries(For example update, delete, 27
search etc…).
A program to design the Login page and validating the USER_ID and
12 30
PASSWORD using JSP and Database.
ADVANCED JAVA BIS402
Program 1

Implement a java program to demonstrate creating an ArrayList, adding elements,


removing elements, sorting elements of ArrayList. Also illustrate the use of toArray()
method.

import java.util.ArrayList;
import java.util.Collections;

public class ArrayListDemo {


public static void main(String[] args) {
// Creating an ArrayList
ArrayList<String> arrayList = new ArrayList<>();

// Adding elements to the ArrayList


arrayList.add("Apple");
arrayList.add("Banana");
arrayList.add("Orange");
arrayList.add("Mango");
arrayList.add("Grapes");

// Displaying the ArrayList


System.out.println("ArrayList before sorting:");
displayArrayList(arrayList);

// Removing an element from the ArrayList


arrayList.remove("Orange");

// Displaying the ArrayList after removing an element


System.out.println("\nArrayList after removing 'Orange':");
displayArrayList(arrayList);

// Sorting the ArrayList


Collections.sort(arrayList);

// Displaying the sorted ArrayList


System.out.println("\nArrayList after sorting:");
displayArrayList(arrayList);

// Converting ArrayList to Array using toArray() method


String[] array = arrayList.toArray(new String[0]);

// Displaying the Array


System.out.println("\nArray obtained from ArrayList using toArray() method:");
for (String item : array) {
System.out.println(item);

DEPT. OF ISE, JSSATEB 7


ADVANCED JAVA BIS402
}
}

// Method to display the contents of ArrayList


public static void displayArrayList(ArrayList<String> arrayList) {
for (String item : arrayList) {
System.out.println(item);
}
}
}

Output:
ArrayList before sorting:
Apple
Banana
Orange
Mango
Grapes

ArrayList after removing 'Orange':


Apple
Banana
Mango
Grapes

ArrayList after sorting:


Apple
Banana
Grapes
Mango

Array obtained from ArrayList using toArray() method:


Apple
Banana
Grapes
Mango

DEPT. OF ISE, JSSATEB 8


ADVANCED JAVA BIS402
Program 2

Develop a program to read random numbers between a given range that are multiples
of 2 and 5, sort the numbers according to tens place using comparator.

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Random;

public class NumberComparator {


public static void main(String[] args) {
int minRange = 10; // Minimum range value
int maxRange = 100; // Maximum range value
int numCount = 10; // Number of random numbers to generate

ArrayList<Integer> randomNumbers = generateRandomNumbers(minRange,


maxRange, numCount);
System.out.println("Random numbers generated:");
System.out.println(randomNumbers);

// Sorting the numbers according to their tens place using Comparator


Collections.sort(randomNumbers, new TensPlaceComparator());

System.out.println("\nRandom numbers sorted according to tens place:");


System.out.println(randomNumbers);
}

// Method to generate random numbers between a given range that are multiples of 2 and 5
public static ArrayList<Integer> generateRandomNumbers(int minRange, int maxRange,
int numCount) {
ArrayList<Integer> randomNumbers = new ArrayList<>();
Random random = new Random();

for (int i = 0; i < numCount; i++) {


int randomNumber;
do {
randomNumber = random.nextInt(maxRange - minRange + 1) + minRange;
} while (randomNumber % 2 != 0 || randomNumber % 5 != 0); // Checking if the
number is a multiple of 2 and 5
randomNumbers.add(randomNumber);
}

return randomNumbers;
}

DEPT. OF ISE, JSSATEB 9


ADVANCED JAVA BIS402
// Comparator to sort numbers based on their tens place
static class TensPlaceComparator implements Comparator<Integer> {
@Override
public int compare(Integer num1, Integer num2) {
return Integer.compare(num1 % 100 / 10, num2 % 100 / 10);
}
}
}

Output:

Random numbers generated:

[30, 80, 80, 30, 90, 100, 10, 10, 60, 70]

Random numbers sorted according to tens place:

[100, 10, 10, 30, 30, 60, 70, 80, 80, 90]

DEPT. OF ISE, JSSATEB 10


ADVANCED JAVA BIS402
Program 3

Implement a java program to illustrate storing user defined classes in collection.

import java.util.ArrayList;

class Student {
private String name;
private int age;

public Student(String name, int age) {


this.name = name;
this.age = age;
}

public String getName() {


return name;
}

public int getAge() {


return age;
}

@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
}
}

public class Main {


public static void main(String[] args) {
// Create ArrayList to store Student objects
ArrayList<Student> studentList = new ArrayList<>();

// Adding Student objects to the ArrayList


studentList.add(new Student("Alice", 20));
studentList.add(new Student("Bob", 22));
studentList.add(new Student("Charlie", 21));

// Displaying the contents of the ArrayList


System.out.println("Students in the list:");
for (Student student : studentList) {
System.out.println(student);
}
}
}

DEPT. OF ISE, JSSATEB 11


ADVANCED JAVA BIS402

Output:

Students in the list:


Student [name=Alice, age=20]
Student [name=Bob, age=22]
Student [name=Charlie, age=21]

DEPT. OF ISE, JSSATEB 12


ADVANCED JAVA BIS402
Program 4

Implement a java program to illustrate the use of different types of string class
constructors.

public class StringConstructorDemo {


public static void main(String[] args) {
// Using a string literal
String str1 = "Hello, World!";
System.out.println("String created using a string literal: " + str1);

// Using a character array


char[] charArray = {'H', 'e', 'l', 'l', 'o'};
String str2 = new String(charArray);
System.out.println("String created using a character array: " + str2);

// Using a portion of a character array


String str3 = new String(charArray, 2, 3); // Start index: 2, Length: 3
System.out.println("String created using a portion of a character array: " + str3);

// Using another string


String str4 = new String(str1);
System.out.println("String created using another string: " + str4);

// Using bytes and character encoding


byte[] byteArray = {72, 101, 108, 108, 111}; // ASCII values for "Hello"
String str5 = new String(byteArray);
System.out.println("String created using bytes and character encoding: " + str5);

// Using bytes, character encoding, and specifying a subrange


String str6 = new String(byteArray, 1, 4); // Start index: 1, Length: 4
System.out.println("String created using bytes, character encoding, and specifying a
subrange: " + str6);
}
}

Output:

String created using a string literal: Hello, World!


String created using a character array: Hello
String created using a portion of a character array: llo
String created using another string: Hello, World!
String created using bytes and character encoding: Hello
String created using bytes, character encoding, and specifying a subrange: ello

DEPT. OF ISE, JSSATEB 13


ADVANCED JAVA BIS402
Program 5

Implement a java program to illustrate the use of different types of character


extraction, string comparison, string search and string modification methods.

public class StringMethodsDemo {


public static void main(String[] args) {
// Character extraction methods
String str = "Hello, World!";
System.out.println("Original String: " + str);
System.out.println("Character at index 4: " + str.charAt(4)); // Extracting character at
index 4
System.out.println("Substring from index 7 to end: " + str.substring(7)); // Extracting
substring from index 7 to end
System.out.println("Substring from index 0 to 5: " + str.substring(0, 5)); // Extracting
substring from index 0 to 5

// String comparison methods


String str1 = "Hello";
String str2 = "hello";
System.out.println("Comparing 'Hello' with 'hello': " + str1.compareTo(str2)); //
Comparing case-sensitive
System.out.println("Comparing 'Hello' with 'hello' (ignore case): " +
str1.compareToIgnoreCase(str2)); // Comparing ignoring case

// String search methods


System.out.println("Index of 'World': " + str.indexOf("World")); // Finding the index of
substring "World"
System.out.println("Index of 'l' after index 5: " + str.indexOf('l', 5)); // Finding the index
of character 'l' after index 5
System.out.println("Last index of 'l': " + str.lastIndexOf('l')); // Finding the last index of
character 'l'

// String modification methods


System.out.println("Replacing 'World' with 'Java': " + str.replace("World", "Java")); //
Replacing substring "World" with "Java"
System.out.println("Uppercase: " + str.toUpperCase()); // Converting to uppercase
System.out.println("Lowercase: " + str.toLowerCase()); // Converting to lowercase
System.out.println("Trimming whitespace: " + " Hello, World! ".trim()); // Trimming
leading and trailing whitespace
}
}

DEPT. OF ISE, JSSATEB 14


ADVANCED JAVA BIS402
Output:
Original String: Hello, World!
Character at index 4: o
Substring from index 7 to end: World!
Substring from index 0 to 5: Hello
Comparing 'Hello' with 'hello': -32
Comparing 'Hello' with 'hello' (ignore case): 0
Index of 'World': 7
Index of 'l' after index 5: 10
Last index of 'l': 10
Replacing 'World' with 'Java': Hello, Java!
Uppercase: HELLO, WORLD!
Lowercase: hello, world!
Trimming whitespace: Hello, World!

DEPT. OF ISE, JSSATEB 15


ADVANCED JAVA BIS402
Program 6

Implement a java program to illustrate the use of different types of StringBuffer methods

public class StringBufferMethodsDemo {


public static void main(String[] args) {
// Creating a StringBuffer object
StringBuffer stringBuffer = new StringBuffer("Hello");

// Append method
stringBuffer.append(" World");
System.out.println("After appending: " + stringBuffer);

// Insert method
stringBuffer.insert(5, ", ");
System.out.println("After inserting: " + stringBuffer);

// Delete method
stringBuffer.delete(5, 8);
System.out.println("After deleting: " + stringBuffer);

// Reverse method
stringBuffer.reverse();
System.out.println("After reversing: " + stringBuffer);

// Replace method
stringBuffer.replace(0, 5, "Hola");
System.out.println("After replacing: " + stringBuffer);

// Capacity method
System.out.println("Capacity of StringBuffer: " + stringBuffer.capacity());

// Length method
System.out.println("Length of StringBuffer: " + stringBuffer.length());

// EnsureCapacity method
stringBuffer.ensureCapacity(50);
System.out.println("Capacity after ensuring: " + stringBuffer.capacity());

// SetLength method
stringBuffer.setLength(10);
System.out.println("StringBuffer after setting length: " + stringBuffer);
}
}

Output:

DEPT. OF ISE, JSSATEB 16


ADVANCED JAVA BIS402
After appending: Hello World
After inserting: Hello, World
After deleting: HelloWorld
After reversing: dlroWolleH
After replacing: HolaolleH
Capacity of StringBuffer: 21
Length of StringBuffer: 9
Capacity after ensuring: 50
StringBuffer after setting length: HolaolleH

DEPT. OF ISE, JSSATEB 17


ADVANCED JAVA BIS402
Program 7

Demonstrate a swing event handling application that creates 2 buttons Alpha and Beta
and displays the text “Alpha pressed” when alpha button is clicked and “Beta pressed”
when beta button is clicked.

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ButtonEventHandlingDemo extends JFrame implements ActionListener {


private JButton alphaButton;
private JButton betaButton;

public ButtonEventHandlingDemo() {
setTitle("Button Event Handling Demo");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);

// Creating buttons
alphaButton = new JButton("Alpha");
betaButton = new JButton("Beta");

// Adding action listeners to buttons


alphaButton.addActionListener(this);
betaButton.addActionListener(this);

// Setting layout
setLayout(new FlowLayout());

// Adding buttons to the frame


add(alphaButton);
add(betaButton);
}

// ActionPerformed method to handle button clicks


@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == alphaButton) {
JOptionPane.showMessageDialog(this, "Alpha pressed");
} else if (e.getSource() == betaButton) {
JOptionPane.showMessageDialog(this, "Beta pressed");
}
}

public static void main(String[] args) {


SwingUtilities.invokeLater(() -> {
ButtonEventHandlingDemo demo = new ButtonEventHandlingDemo();

DEPT. OF ISE, JSSATEB 18


ADVANCED JAVA BIS402
demo.setVisible(true);
});
}
}

Output:

DEPT. OF ISE, JSSATEB 19


ADVANCED JAVA BIS402
Program 8

A program to display greeting message on the browser “Hello UserName”, “How Are
You?”, accept username from the client using servlet.

HTML Code

<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="GreetingServlet" method ="post">
<p>Enter the Username: <input type="text" name="username"> </p>
<p> <input type="submit" value="submit"></p>
</form>
</body>
</html>

Servlet Code

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

/**
*
* @author Chetan
*/
public class GreetingServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {

DEPT. OF ISE, JSSATEB 20


ADVANCED JAVA BIS402
/* TODO output your page here. You may use following sample code. */

}
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
String username = request.getParameter("username");

out.println("<html>");
out.println("<head>");
out.println("<title>Greeting Message</title>");
out.println("</head>");
out.println("<body>");
out.println("<h2>Hello " + username + "</h2>");
out.println("<p>How Are You?</p>");
out.println("</body>");
out.println("</html>");
}
Output:

Enter the Username:

DEPT. OF ISE, JSSATEB 21


ADVANCED JAVA BIS402
Program 9

A servlet program to display the name, USN, and total marks by accepting student detail

HTML Code

<!DOCTYPE html>
<html>
<head>
<title>Student Details Form</title>
</head>
<body>
<h2>Enter Student Details</h2>
<form action="StudentDetailsServlet" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br><br>

<label for="usn">USN:</label>
<input type="text" id="usn" name="usn" required><br><br>

<label for="marks1">Marks 1:</label>


<input type="number" id="marks1" name="marks1" required><br><br>

<label for="marks2">Marks 2:</label>


<input type="number" id="marks2" name="marks2" required><br><br>

<label for="marks3">Marks 3:</label>


<input type="number" id="marks3" name="marks3" required><br><br>

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


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

Servlet Code

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

/**
*
* @author Chetan
*/
public class StudentDetailsServlet extends HttpServlet {

/**

DEPT. OF ISE, JSSATEB 22


ADVANCED JAVA BIS402
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */

}
}

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

// Retrieving student details from request parameters


String name = request.getParameter("name");
String usn = request.getParameter("usn");
int marks1 = Integer.parseInt(request.getParameter("marks1"));
int marks2 = Integer.parseInt(request.getParameter("marks2"));
int marks3 = Integer.parseInt(request.getParameter("marks3"));

// Calculating total marks


int totalMarks = marks1 + marks2 + marks3;

out.println("<html>");
out.println("<head>");
out.println("<title>Student Details</title>");
out.println("</head>");
out.println("<body>");
out.println("<h2>Student Details</h2>");
out.println("<p>Name: " + name + "</p>");
out.println("<p>USN: " + usn + "</p>");
out.println("<p>Total Marks: " + totalMarks + "</p>");
out.println("</body>");
out.println("</html>");
}

DEPT. OF ISE, JSSATEB 23


ADVANCED JAVA BIS402
Output

DEPT. OF ISE, JSSATEB 24


ADVANCED JAVA BIS402
Program 10

A Java program to create and read the cookie for the given cookie name as “EMPID” and its
value as “AN2356”.

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

@WebServlet("/CookieExample")
public class CookieExample extends HttpServlet {

/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */

}
}

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on


the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Cookie empIdCookie = new Cookie("EMPID", "AN2356");
empIdCookie.setMaxAge(3600); // Cookie will expire in 1 hour

DEPT. OF ISE, JSSATEB 25


ADVANCED JAVA BIS402

// Adding the cookie to the response


response.addCookie(empIdCookie);

response.getWriter().println("Cookie has been set successfully!");


}

/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>

Output

DEPT. OF ISE, JSSATEB 26


ADVANCED JAVA BIS402
Program 11

Write a JAVA Program to insert data into Student DATA BASE and retrieve info
based on particular queries(For example update, delete, search etc…).

package studentdatabase;

import java.sql.*;

public class StudentDatabase {


// JDBC URL, username, and password of MySQL server
private static final String URL = "jdbc:mysql://localhost:3306/student_db";
private static final String USER = "root";
private static final String PASSWORD = "root";

public static void main(String[] args) {


try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD)) {
// Insert data into the student table
insertStudent(conn, "John", 22, "ISE");

// Retrieve data based on particular queries


searchStudent(conn, "John");
updateStudent(conn, "John", 23);
deleteStudent(conn, "John");

} catch (SQLException e) {
e.printStackTrace();
}
}

// Method to insert data into the student table


private static void insertStudent(Connection conn, String name, int age, String department)
throws SQLException {
String sql = "INSERT INTO student (name, age, department) VALUES (?, ?, ?)";
try (PreparedStatement statement = conn.prepareStatement(sql)) {
statement.setString(1, name);
statement.setInt(2, age);
statement.setString(3, department);
int rowsInserted = statement.executeUpdate();
if (rowsInserted > 0) {
System.out.println("A new student has been inserted successfully!");
}
}
}

// Method to search for a student based on name


private static void searchStudent(Connection conn, String name) throws SQLException {
String sql = "SELECT * FROM student WHERE name = ?";
try (PreparedStatement statement = conn.prepareStatement(sql)) {
statement.setString(1, name);

DEPT. OF ISE, JSSATEB 27


ADVANCED JAVA BIS402
ResultSet result = statement.executeQuery();
if (result.next()) {
System.out.println("Student found:");
System.out.println("Name: " + result.getString("name"));
System.out.println("Age: " + result.getInt("age"));
System.out.println("Department: " + result.getString("department"));
} else {
System.out.println("No student found with the name: " + name);
}
}
}

// Method to update a student's age based on name


private static void updateStudent(Connection conn, String name, int newAge) throws
SQLException {
String sql = "UPDATE student SET age = ? WHERE name = ?";
try (PreparedStatement statement = conn.prepareStatement(sql)) {
statement.setInt(1, newAge);
statement.setString(2, name);
int rowsUpdated = statement.executeUpdate();
if (rowsUpdated > 0) {
System.out.println("Student's age has been updated successfully!");
} else {
System.out.println("No student found with the name: " + name);
}
}
}

// Method to delete a student based on name


private static void deleteStudent(Connection conn, String name) throws SQLException {
String sql = "DELETE FROM student WHERE name = ?";
try (PreparedStatement statement = conn.prepareStatement(sql)) {
statement.setString(1, name);
int rowsDeleted = statement.executeUpdate();
if (rowsDeleted > 0) {
System.out.println("Student has been deleted successfully!");
} else {
System.out.println("No student found with the name: " + name);
}
}
}
}

Create Database in MYSQL using below Queries:


mysql> create database student_db;
Query OK, 1 row affected (0.09 sec)

mysql> use student_db;


Database changed

DEPT. OF ISE, JSSATEB 28


ADVANCED JAVA BIS402
mysql> create table student(name varchar(30),age int,department varchar(10));
Query OK, 0 rows affected (0.21 sec)

Add mysql jar file

Output:
A new student has been inserted successfully!
Student found:
Name: John
Age: 22
Department: ISE
Student's age has been updated successfully!
Student has been deleted successfully!

DEPT. OF ISE, JSSATEB 29


ADVANCED JAVA BIS402
Program 12

A program to design the Login page and validating the USER_ID and PASSWORD
using JSP and DataBase.

Login.jsp

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


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login Page</title>
</head>

<body>
<h2>Login</h2>
<form action="loginvalidation.jsp" method="post">
<label for="userId">User ID:</label>
<input type="text" id="userId" name="userId" required><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br><br>
<input type="submit" value="Login">
</form>
</body>
</html>

LoginValidation.jsp

<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.sql.Connection"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login Validation</title>
</head>
<body>
<%
String userId = request.getParameter("userId");
String password = request.getParameter("password");
boolean valid = false;

// JDBC connection parameters


String url = "jdbc:mysql://localhost:3306/mydatabase";
String dbUser = "root";
String dbPassword = "root";

DEPT. OF ISE, JSSATEB 30


ADVANCED JAVA BIS402

// JDBC variables
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;

try {
// Establishing database connection
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url, dbUser, dbPassword);

// Query to validate user ID and password


String sql = "SELECT * FROM users WHERE userId=? AND password=?";
ps = conn.prepareStatement(sql);
ps.setString(1, userId);
ps.setString(2, password);
rs = ps.executeQuery();

// If a row is returned, user ID and password are valid


if (rs.next()) {
valid = true;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// Closing database resources
if (rs != null) rs.close();
if (ps != null) ps.close();
if (conn != null) conn.close();
}

// Redirecting based on validation result


if (valid) {
// User ID and password are valid, redirect to welcome page
response.sendRedirect("welcome.jsp");
} else {
// User ID and password are invalid, display error message
out.println("<h2>Login failed. Invalid User ID or Password.</h2>");
out.println("<a href=\"login.jsp\">Back to Login Page</a>");
}
%>
</body>
</html>

Welcome.jsp

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


<!DOCTYPE html>
<html>
<head>

DEPT. OF ISE, JSSATEB 31


ADVANCED JAVA BIS402
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>User ID and password are valid</h1>
</body>
</html>

Create Database in Mysql:

mysql> create database mydatabase;


Query OK, 1 row affected (0.00 sec)

mysql> use mydatabase


Database changed
mysql> create table users(userId varchar(10),password varchar(10));
Query OK, 0 rows affected (0.03 sec)

mysql> insert into users values('1js21is','vtu123');


Query OK, 1 row affected (0.00 sec)

Output:

DEPT. OF ISE, JSSATEB 32


ADVANCED JAVA BIS402

DEPT. OF ISE, JSSATEB 33

You might also like