0% found this document useful (0 votes)
12 views34 pages

BIS402(JAVA) Programs_AMC

The document outlines several Java programming tasks, including creating and manipulating ArrayLists, generating and sorting random numbers, storing user-defined classes in collections, and demonstrating various string and StringBuffer methods. Each task includes a program example, output, and a brief result description summarizing the program's functionality. Additionally, it mentions a swing event handling application with buttons Alpha and Beta, but details for this task are not provided.

Uploaded by

nswm4dsyjn
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)
12 views34 pages

BIS402(JAVA) Programs_AMC

The document outlines several Java programming tasks, including creating and manipulating ArrayLists, generating and sorting random numbers, storing user-defined classes in collections, and demonstrating various string and StringBuffer methods. Each task includes a program example, output, and a brief result description summarizing the program's functionality. Additionally, it mentions a swing event handling application with buttons Alpha and Beta, but details for this task are not provided.

Uploaded by

nswm4dsyjn
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/ 34

ADVANCED JAVA (BIS402) 2023-2024

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.

AIM: To implement creating of ArrayList, adding elements, removing elements, sorting elements of
ArrayList using Java Programming.

PROGRAM:

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 elements of the ArrayList
System.out.println("ArrayList elements: " + arrayList);
// Removing an element from the ArrayList
arrayList.remove("Orange");
System.out.println("After removing Orange: " + arrayList);
// Sorting elements of the ArrayList
Collections.sort(arrayList);
System.out.println("After sorting: " + arrayList);
// Using toArray() method to convert ArrayList to array
String[] array = arrayList.toArray(new String[0]);
// Displaying elements of the array
System.out.print("Array elements: ");

AMCEC, Dept of ISE 1


ADVANCED JAVA (BIS402) 2023-2024

for (String fruit: array) {


System.out.print(fruit + " ");
}
System.out.println();
}
}

OUTPUT
ArrayList elements: [Apple, Banana, Orange, Mango, Grapes]
After removing Orange: [Apple, Banana, Mango, Grapes]
After sorting: [Apple, Banana, Grapes, Mango]
Array elements: Apple Banana Grapes Mango

RESULT
This program creates an ArrayList of Strings, adds elements to it, removes an element, sorts the elements,
and finally converts the ArrayList to an array using the `toArray()` method.

AMCEC, Dept of ISE 2


ADVANCED JAVA (BIS402) 2023-2024

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.

AIM: To implement a java 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 interface.

PROGRAM
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Random;

class NumberComparator implements Comparator<Integer> {


@Override
public int compare(Integer num1, Integer num2) {
int tensPlace1 = num1 % 100 / 10;
int tensPlace2 = num2 % 100 / 10;
return Integer.compare(tensPlace1, tensPlace2);
}
}
public class Main {
public static void main(String[] args) {
int minRange = 1;
int maxRange = 100;
int numberOfNumbers = 10;
List<Integer> randomNumbers = generateRandomNumbers(minRange, maxRange, numberOfNumbers);
System.out.println("Random Numbers:");
for (int num : randomNumbers) {
System.out.print(num + " ");
}
System.out.println();
randomNumbers.sort(new NumberComparator());
System.out.println("\nSorted Numbers by Tens Place:");

AMCEC, Dept of ISE 3


ADVANCED JAVA (BIS402) 2023-2024

for (int num : randomNumbers) {


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

private static List<Integer> generateRandomNumbers(int min, int max, int count) {


List<Integer> numbers = new ArrayList<>();
Random random = new Random();
while (numbers.size() < count) {
int randomNumber = random.nextInt(max - min + 1) + min;
if (randomNumber % 2 == 0 && randomNumber % 5 == 0) {
numbers.add(randomNumber);
}
}
return numbers;
}
}

OUTPUT
Random Numbers:
100 70 100 50 50 90 50 80 10 100

Sorted Numbers by Tens Place:


100 100 100 10 50 50 50 70 80 90

RESULT
This program generates random numbers between a given range (`minRange` to `maxRange`) that are
multiples of both 2 and 5. Then it sorts these numbers according to the tens place using a custom
comparator (`NumberComparator`). Finally, it prints both the randomly generated numbers and the sorted
numbers.

AMCEC, Dept of ISE 4


ADVANCED JAVA (BIS402) 2023-2024

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


AIM: To implement a java program to illustrate Storing User defined Classes using Collection Interface.
PROGRAM
import java.util.ArrayList;
import java.util.List;
class Person {
private String name;
private int age;
public Person(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 "Name: " + name + ", Age: " + age;
}
}
public class Main {
public static void main(String[] args) {
// Create a list to store Person objects
List<Person> personList = new ArrayList<>();
// Add some Person objects to the list
personList.add(new Person("Alice", 30));
personList.add(new Person("Bob", 25));
personList.add(new Person("Charlie", 40));

AMCEC, Dept of ISE 5


ADVANCED JAVA (BIS402) 2023-2024

// Print the list of Person objects


System.out.println("List of Persons:");
for (Person p : personList) {
System.out.println(p);
}
}
}
OUTPUT
List of Persons:
Name: Alice, Age: 30
Name: Bob, Age: 25
Name: Charlie, Age: 40

RESULT
This Program creates the user defined class for storing and manipulation of data using List.

AMCEC, Dept of ISE 6


ADVANCED JAVA (BIS402) 2023-2024

4. Implement a java program to illustrate the use of different types of string class constructors.
AIM: To implement a java program to illustrate the use of different types of string class constructors.
PROGRAM
public class StringConstructorsDemo {
public static void main(String[] args) {
// Using String literal
String str1 = "Hello, World!";
System.out.println("String literal: " + str1);
// Using char array
char[] charArray = {'J', 'a', 'v', 'a'};
String str2 = new String(charArray);
System.out.println("String from char array: " + str2);
// Using part of char array
String str3 = new String(charArray, 1, 2);
System.out.println("String from part of char array: " + str3);
// Using byte array
byte[] byteArray = {65, 66, 67, 68}; // ASCII values for A, B, C, D
String str4 = new String(byteArray);
System.out.println("String from byte array: " + str4);
// Using part of byte array
String str5 = new String(byteArray, 1, 2);
System.out.println("String from part of byte array: " + str5);
// Using another String object
String str6 = new String(str1);
System.out.println("String from another String object: " + str6);
// Using StringBuilder
StringBuilder sb = new StringBuilder("Hello, StringBuilder!");
String str7 = new String(sb);
System.out.println("String from StringBuilder: " + str7);
}
}

AMCEC, Dept of ISE 7


ADVANCED JAVA (BIS402) 2023-2024

OUTPUT
String literal: Hello, World!
String from char array: Java
String from part of char array: av
String from byte array: ABCD
String from part of byte array: BC
String from another String object: Hello, World!
String from StringBuilder: Hello, StringBuilder!

RESULT
This program demonstrates how different `String` constructors can be used to create strings from various
sources such as character arrays, byte arrays, other strings, and `StringBuilder` objects.

AMCEC, Dept of ISE 8


ADVANCED JAVA (BIS402) 2023-2024

5. Implement a java program to illustrate the use of different types of character extraction, string
comparison, string search and string modification methods.

AIM: To implement a different types of character extraction, string comparison, string search and string
modification methods using Java programs.

PROGRAM
public class StringMethodsDemo {
public static void main(String[] args) {
String str = "Hello, World!";
// Character Extraction (charAt)
char ch1 = str.charAt(0);
System.out.println("Character at index 0: " + ch1);
// getChars
char[] charArray = new char[5];
str.getChars(7, 12, charArray, 0);
System.out.println("Characters from index 7 to 11: " + new String(charArray));
// String Comparison
String str2 = "Hello, World!";
String str3 = "hello, world!";
// equals
boolean isEqual = str.equals(str2);
System.out.println("str equals str2: " + isEqual);
// equalsIgnoreCase
boolean isEqualIgnoreCase = str.equalsIgnoreCase(str3);
System.out.println("str equalsIgnoreCase str3: " + isEqualIgnoreCase);
// compareTo
int compareToResult = str.compareTo(str3);
System.out.println("str compareTo str3: " + compareToResult);
// String Search
// indexOf
int index1 = str.indexOf('o');
System.out.println("Index of first 'o': " + index1);

AMCEC, Dept of ISE 9


ADVANCED JAVA (BIS402) 2023-2024

// lastIndexOf
int index2 = str.lastIndexOf('o');
System.out.println("Index of last 'o': " + index2);

// contains
boolean contains = str.contains("World");
System.out.println("str contains 'World': " + contains);
// startsWith
boolean startsWith = str.startsWith("Hello");
System.out.println("str starts with 'Hello': " + startsWith);
// endsWith
boolean endsWith = str.endsWith("!");
System.out.println("str ends with '!': " + endsWith);
// String Modification
// substring
String substr = str.substring(7, 12);
System.out.println("Substring from index 7 to 11: " + substr);
// concat
String str4 = str.concat(" How are you?");
System.out.println("Concatenated string: " + str4);
// replace
String replacedStr = str.replace("World", "Java");
System.out.println("Replaced 'World' with 'Java': " + replacedStr);
// toLowerCase
String lowerStr = str.toLowerCase();
System.out.println("Lowercase string: " + lowerStr);
// toUpperCase
String upperStr = str.toUpperCase();
System.out.println("Uppercase string: " + upperStr);
// trim
String str5 = " Hello, World! ";
String trimmedStr = str5.trim();

AMCEC, Dept of ISE 10


ADVANCED JAVA (BIS402) 2023-2024

System.out.println("Trimmed string: '" + trimmedStr + "'");


}
}

OUTPUT
Character at index 0: H
Characters from index 7 to 11: World
str equals str2: true
str equalsIgnoreCase str3: true
str compareTo str3: -32
Index of first 'o': 4
Index of last 'o': 8
str contains 'World': true
str starts with 'Hello': true
str ends with '!': true
Substring from index 7 to 11: World
Concatenated string: Hello, World! How are you?
Replaced 'World' with 'Java': Hello, Java!
Lowercase string: hello, world!
Uppercase string: HELLO, WORLD!
Trimmed string: 'Hello, World!'
RESULT
This program illustrates the use of various methods for extracting characters from strings, comparing
strings, searching within strings, and modifying strings. Each method's result is printed to the console to
demonstrate its functionality.

AMCEC, Dept of ISE 11


ADVANCED JAVA (BIS402) 2023-2024

6. Implement a java program to illustrate the use of different types of StringBuffer methods
AIM: To implement the use of different types of StringBuffer methods using Java Programming.
PROGRAM
public class StringBufferExample
{
public static void main(String[] args)
{
// Creating a StringBuffer object
StringBuffer sb = new StringBuffer("Hello");

// 1. append() method
System.out.println("1. append() method:");
sb.append(" World");
System.out.println("After append: " + sb); // Hello World

// 2. insert() method
System.out.println("\n2. insert() method:");
sb.insert(5, " Java");
System.out.println("After insert: " + sb); // Hello Java World

// 3. replace() method
System.out.println("\n3. replace() method:");
sb.replace(6, 10, "C++");
System.out.println("After replace: " + sb); // Hello C++ World

// 4. delete() method
System.out.println("\n4. delete() method:");
sb.delete(5, 9);
System.out.println("After delete: " + sb); // Hello World

// 5. reverse() method
System.out.println("\n5. reverse() method:");

AMCEC, Dept of ISE 12


ADVANCED JAVA (BIS402) 2023-2024

sb.reverse();
System.out.println("After reverse: " + sb); // dlroW olleH

// 6. capacity() method
System.out.println("\n6. capacity() method:");
System.out.println("Capacity: " + sb.capacity());

// 7. ensureCapacity() method
System.out.println("\n7. ensureCapacity() method:");
sb.ensureCapacity(50);
System.out.println("Capacity after ensureCapacity(50): " + sb.capacity()); // 50

// 8. setLength() method
System.out.println("\n8. setLength() method:");
sb.setLength(5);
System.out.println("After setLength(5): " + sb); // dlroW

// 9. charAt() method
System.out.println("\n9. charAt() method:");
char ch = sb.charAt(2);
System.out.println("Character at index 2: " + ch); // r

// 10. substring() method


System.out.println("\n10. substring() method:");
String sub = sb.substring(1, 4);
System.out.println("Substring from index 1 to 4: " + sub); // lro
}
}

OUTPUT
1. append() method:
After append: Hello World

AMCEC, Dept of ISE 13


ADVANCED JAVA (BIS402) 2023-2024

2. insert() method:
After insert: Hello Java World

3. replace() method:
After replace: Hello C++ World

4. delete() method:
After delete: Hello World

5. reverse() method:
After reverse: dlroW olleH

6. capacity() method:
Capacity: 27

7. ensureCapacity() method:
Capacity after ensureCapacity(50): 50

8. setLength() method:
After setLength(5): dlroW

9. charAt() method:
Character at index 2: r

10. substring() method:


Substring from index 1 to 4: lro

RESULT

This program demonstrates various useful methods of the `StringBuffer` class in Java, showcasing how
each method manipulates the string buffer in different ways.

AMCEC, Dept of ISE 14


ADVANCED JAVA (BIS402) 2023-2024

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.
AIM: To implement an 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 using Java Programming.
PROGRAM
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ButtonEventDemo extends JFrame {
private JButton alphaButton;
private JButton betaButton;
private JLabel displayLabel;

public ButtonEventDemo() {
// Create the buttons
alphaButton = new JButton("Alpha");
betaButton = new JButton("Beta");

// Create the label to display the messages


displayLabel = new JLabel("Press a button");

// Add action listeners to the buttons


alphaButton.addActionListener(new ButtonClickListener());
betaButton.addActionListener(new ButtonClickListener());

// Set the layout and add components


setLayout(new java.awt.FlowLayout());
add(alphaButton);
add(betaButton);
add(displayLabel);

AMCEC, Dept of ISE 15


ADVANCED JAVA (BIS402) 2023-2024

// Set the frame properties


setTitle("Swing Event Handling Demo");
setSize(300, 100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
private class ButtonClickListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == alphaButton) {
displayLabel.setText("Alpha pressed");
} else if (e.getSource() == betaButton) {
displayLabel.setText("Beta pressed");
}
}
}
public static void main(String[] args) {
// Create and display the application frame
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new ButtonEventDemo().setVisible(true);
}
});
}
}

OUTPUT

AMCEC, Dept of ISE 16


ADVANCED JAVA (BIS402) 2023-2024

RESULT
This program created a simple GUI with two buttons that display corresponding messages when clicked
using Swing Components.

AMCEC, Dept of ISE 17


ADVANCED JAVA (BIS402) 2023-2024

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

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

PROGRAM
Program8.html file
<!DOCTYPE html>
<html>
<head>
<title>Greetings Form</title>
</head>
<body>
<form action="Greetings" method="post">
Enter the UserName: <br>
<input type="text" name="username"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Greetings.java File
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.*;
public class StudentServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.getWriter().append("Served at: ").append(request.getContextPath());
}

AMCEC, Dept of ISE 18


ADVANCED JAVA (BIS402) 2023-2024

protected void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
// Set response content type
response.setContentType("text/html");
// Retrieve student details from request parameters
String username=request.getParameter("username");
response.setContentType("text/html");
java.io.PrintWriter out=response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title> Greetings Response</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Hello,"+username+"</h1> How are You?");
out.println("</body>");
out.println("</html>");
}
}

OUTPUT

AMCEC, Dept of ISE 19


ADVANCED JAVA (BIS402) 2023-2024

RESULT
Implemented a Servlet program to display the name, along with Hell username, How are you? ,by
accepting Username through an HTML form. Assuming that the servlet handles the details using a
doPost method for receiving form data securely.

AMCEC, Dept of ISE 20


ADVANCED JAVA (BIS402) 2023-2024

9. A servlet program to display the name, USN, and total marks by accepting student detail.
AIM: To implement a servlet program to display the name, USN, and total marks by accepting student
detail.

PROGRAM
Students.html file
<!DOCTYPE html>
<html>
<head>
<title>Student Details Form</title>
</head>
<body>
<h2>Enter Student Details</h2>
<form action="Students" method="post">
Name: <br>
<input type="text" name="name"><br><br>
USN:<br>
<input type="text" name="usn"><br><br>
Marks 1:<br>
<input type="number" name="marks1"><br><br>
Marks 2: <br>
<input type="number" name="marks2" ><br><br>
Marks 3:<br>
<input type="number" name="marks3" ><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Students.java File
import java.io.IOException;

AMCEC, Dept of ISE 21


ADVANCED JAVA (BIS402) 2023-2024

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.*;
public class StudentServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Set response content type
response.setContentType("text/html");
// Retrieve 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"));
// Calculate total marks
int totalMarks = marks1 + marks2 + marks3;
double per = (totalMarks/600.0)*100.0;
java.io.PrintWriter out=reponse.getWriter();
// Display the student details and total marks
out.println("<html><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 ("<p>Total Marks: " + totalMarks + "</p>");
out.println ("</body></html>");
}
}

AMCEC, Dept of ISE 22


ADVANCED JAVA (BIS402) 2023-2024

OUTPUT
Run the Students.html file and input the following below details.

 Name: John Doe


 USN: 123456789
 Marks 1: 85
 Marks 2: 78
 Marks 3: 92

Student Details:
Name: John Doe
USN: 123456789
Total Marks: 255
RESULT
Implemented a Servlet program to display the name, USN, and total marks by accepting student
details through an HTML form. Assuming that the servlet handles the details using a doPost method
for receiving form data securely

AMCEC, Dept of ISE 23


ADVANCED JAVA (BIS402) 2023-2024

10. A Java program to create and read the cookie for the given cookie name as “EMPID” and its
value as “AN2356”.
AIM: To implement a Java program to create and read the cookie for the given cookie name as “EMPID”
and its value as “AN2356”.
PROGRAM
import java.util.*;
import jakarta.servlet.http.Cookie;
public class Pgm10 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
System.out.println("Enter the value of Cookie Emp ID");
String cv=sc.nextLine();
sc.close();
Cookie c=new Cookie("EMPID",cv);
System.out.println("Cookie Name"+c.getName());
System.out.println("Cookie Value"+c.getValue());
}
}

OUTPUT

RESULT
To create and read a cookie named "EMPID" with the value "AN2356" in Java, we'll create a servlet that
demonstrates both creating the cookie and reading its value.

AMCEC, Dept of ISE 24


ADVANCED JAVA (BIS402) 2023-2024

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…).
AIM: To implement a JAVA Program to insert data into Student DATA BASE and retrieve info based on
particular queries.
PROGRAM
STEP 1: Set Up MySQL DataBase
Install MYSQL.
Create a database named student_database using a MYSQL client or command line interface.
CREATE DATABASE student_database;
Create a table named Student with the Specified columns (id,first_name, last_name. age,
department) as described.
CREATE TABLE Student(
id INT AUTO_INCREMENT PRIMARY_KEY,
first_name VARCHAR(50);
last_name VARCHAR(50);
age INT,
dept VARCHAR(50);
);
STEP 2: Set up Eclipse Project
Open Eclipse IDE.
Create a new Java Project : Go to “File”>”New”>Java Project. Enter a project name and click
“Finish”.
STEP 3: Add Jar File
Add MYSQL JDBC driver jar file to the project.
Once the JAR file is downloaded, Open Eclipse.
Right-click on your Java project in the Package Explorer.
Select “Build Path” > “Configure Build Path”.
In the “Libraries” tab, click on the “Add External JARs” button.
Navigate to the location where you downloaded the MYSQL JDBC driver JAR files, Select it and
click “Open”.
Click “Apply and Close” to save the changes.
STEP 4: JAVA Program.
Import java.sql.*;
Public class StudentDatabaseEx

AMCEC, Dept of ISE 25


ADVANCED JAVA (BIS402) 2023-2024

{
Private static final String JDBC_URL=”jdbc:mysql://localhost:3306/student_database”;
Private static final String USERNAME=”root”;
Private static final String PASSWORD=”root”;
Public static void main(String args[])
{
try{
//Step 1: Establishing a Connection to the Database.
try((Connection con=DriverManager.getConnection(JDBC_URL,
USERNAME, PASSWORD)){
System.out.println(“Connected to the Database”);
//Step 2:Inserting data into Student Table
insertStudent(con,”Ram”,”Kumar”,24,”ISE”);
//Step 3: Updating data in Student Table
updateStudent(con,1,”Kumar”,”Ram”,26,”CSE”);
//Step 4: Deleting data from Student Table.
deleteStudent(con,”Ram”);
//Step 5: Searching data in Student Table.
searchStudent(con,”Ram”);
//Step 6: Displaying all records in Student Table
displayAllStudents(con);
}
}
Catch(SQLException e)
{
System.out.println(“SQLException:” +e.getmessage());
System.out.println(“SQLState:” +e.getSQLState());
System.out.println(“Vendor Error:” +e.getErrorCode ());
}
}
//method to insert data into Student Table
Private static void insertStudent(Connection con, String firstName, String lastName, int age,
String dept) throws SQLException {

AMCEC, Dept of ISE 26


ADVANCED JAVA (BIS402) 2023-2024

String insertQuery = “INSERT INTO Student (first_name,last_name,age,dept) VALUES


(?,?,?,?)”;
try (PreparedStatement prepareStmt = con.preparedStatement(insertQuery)){
prepareStmt.setString(1,firstName);
prepareStmt.setString(2,lasttName);
prepareStmt.setString(3,age);
prepareStmt.setString(4,dept);
int rowsInsterted = prepareStmt.executeUpdate();
if(rowsInserted>0){
System.out.println(“A new student record was inserted successfully”);
}
}
}
//method to update data in Student Table
Private static void updateStudent(Connection con, int StudentId, String firstName, String
lastName, int age, String dept) throws SQLException{
String updateQuery = UPDATE Student SET first_name=?,last_name=?,age=?,dept=?
WHERE id=”?”
try (PreparedStatement prepareStmt = con.preparedStatement(updateQuery)){
prepareStmt.setString(1,firstName);
prepareStmt.setString(2,lasttName);
prepareStmt.setString(3,age);
prepareStmt.setString(4,dept);
int rowsInsterted = prepareStmt.executeUpdate();
if(rowsUpated>0){
System.out.println(“Student record with ID” + studentID+”was update
successfully”);
}
}
}
//method to delete data from Student Table
Private static void updateStudent(Connection con, int StudentId) throws SQLException{
String deleteQuery = DELETE FROM Student WHERE id=”?”;

AMCEC, Dept of ISE 27


ADVANCED JAVA (BIS402) 2023-2024

try (PreparedStatement prepareStmt = con.preparedStatement(deleteQuery)){


prepareStmt.setInt(1,StudentId);
int rowsDeleted = prepareStmt.executeUpdate();
if(rowsDeleted>0){
System.out.println(“Student record with ID” + studentId+” was deleted
successfully”);
}
}
}
//method to search for data in Student Table
Private static void searchStudent(Connection con, String firstName) throws SQLException{
String searchQuery = SELECT * FROM Student WHERE first_name=”?”;
try (PreparedStatement prepareStmt = con.preparedStatement(searchQuery)){
prepareStmt.setString(1,firstName);

try (ResultSet resultset = preparedStatement.executeQuery()){


if (resultset.next()){
System.out.println(“Student Found”);
System.out.println(“ID:”+resultset.getInt(“id”));
System.out.println(“First Name:”+resultset.getString(“first_name”));
System.out.println(“Last Name:”+resultset.getString(“last_name”));
System.out.println(“Age:”+resultset.getInt(“age”));
System.out.println(“Department:”+resultset.getString(“dept”));
}
Else {
System.out.println(“No Student found with first name:”+first_Name);
}
}
}
//method display all records in Student Table
Private static void displayStudent(Connection con) throws SQLException{
String selectQuery = “SELECT * FROM Student”;

AMCEC, Dept of ISE 28


ADVANCED JAVA (BIS402) 2023-2024

try(Statement stmt=con.createStatement();
ResultSet resultset = Statement.executeQuery(selectQuery)){
while(resultset.next()){
System.out.println(“ID:”+resultset.getInt(“id”));
System.out.println(“First Name:”+resultset.getString(“first_name”));
System.out.println(“Last Name:”+resultset.getString(“last_name”));
System.out.println(“Age:”+resultset.getInt(“age”));
System.out.println(“Department:”+resultset.getString(“dept”));
System.out.println(“-------------------------------------------------");
}
}
}
OUTPUT
Connected to the Database.
A new student record was inserted successfully!
Student record with ID 1 was updated successfully!
Student record with ID 1 was deleted successfully!
No student found with first Name: Pankaj
Connected to the Database
A new Student record was inserted Successfully!
Student Found:
ID: 2;
First Name: Pankaj
Last Name: Kumar
Age: 25
Department: ISE
----------------------------------------------------------------------------
ID: 3;
First Name: Rahul
Last Name: Sharma
Age: 30
Department: ISE

AMCEC, Dept of ISE 29


ADVANCED JAVA (BIS402) 2023-2024

12. A program to design the Login page and validating the USER_ID and PASSWORD using JSP
and DataBase.
AIM: To design the Login page and validating the USER_ID and PASSWORD using JSP and DataBase.
PROGRAM
STEP 1: Set Up Dynamic Web Project.
1. Open Eclipse IDE.
2. Go to “File”>”New”>”Dynamic web project”.
3. Enter a project name and click “Next”.
4. Choose the target runtime (Apache tomcat server) and click “Next”.
5. Choose the default configuration for the web.xml deployment descriptor and click “Finish”.
6. Right-click on the java project in the package Explorer.
7. Select “build-path”>”Configure Build Path.
8. In the Libraries tab click on the “Add External JARS” button.
STEP 2: Create JSP Files
1. Right click on the web content directory in the project explorer.
2. Go to “New”>File.
3. Enter a file name with a.jsp extension and click Finish.
4. Write your JSP code in the created file.
STEP 3: Set up MYSQL Database:
1. Create a MYSQL database/
2. Create a table to store user credentials for user_id and password,
CREATE DATABASE user_database;
USE user_database;
CREATE TABLE users(
User_id VARCHAR(50) PRIMARY KEY,
Password VARCHAR(50)
);
STEP 4: Create a Login Page (login.jsp):
1. Create a JSP file named login.jsp
2. Design a login form with fields for user Id and password.
3. Submit the form to JSP page for validation.
<%@page language=”java” contentType=”text/html”%>
<html>
<head>
<title>Program 12</title>
</head>
<body>

AMCEC, Dept of ISE 30


ADVANCED JAVA (BIS402) 2023-2024

<form action=”validate.jsp”method=”post”>
User ID : <input type=”text” name=”uname”> <br>
Password:>input type=”password” name=”pwd”><br>
<input type=”submit” value=”Login”>
</form>
</body>
</html>
STEP 5: Validate User credentials (validate.jsp)
<%@page language=”java” contentType=”text.html”%>
<%@page import=”java.sql.*”%>
<html>
<head>
<title>Login Validation</title>
</head>
<body>
<%
//Retrieve user_id and password from the login form
String user_id=request.getParameter(“user_is”);
String pwd=request.getParameter(“pwd”);
//JDBC URL username and password of MYSQL server.
String jdbcURL=”jdbc:mysql://localhost:3306/users_database”;
String dbUser=”root”;
String dbPassword=”root”;
Connection con=null;
preparedStatement stmt=null;
ResultSet rs=null;
try{
//Establish connection to the database
Class.forName(“com.mysql.cj.jdbc.Driver”)
Con=DriverManager.getConnection(jdbcURL,dbUser,dbPassword);
//Prepare SQL query to select user by user id and password
String sql =”SELECT * FROM users WHERE user_id=” AND password=?”;

AMCEC, Dept of ISE 31


ADVANCED JAVA (BIS402) 2023-2024

stmt=con.prepareStatement(sql);
stmt.getString(1,user_id);
stmt.getString(2,password);
resultset=stmt.executeQuer();
if(resultset.next()){
response.sendRedirect(“success,jsp?user_id”+user_id);
} else {
response.sendRedirect(“error.jsp”);
}
}catch(SQLException | ClassNotFoundException e){
e.printStacktrace();
out.println(“Error Connecting to the database”);
} finally {
if(resultSet !=null) {
try {
resultSet.close();
} catch(SQLException e) {
e.printStacktrace();
}
}
if (stmt ! = null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStacktrace();
}
}
if (con ! = null) {
try {
con.close();
} catch (SQLException e) {
e.printStacktrace();

AMCEC, Dept of ISE 32


ADVANCED JAVA (BIS402) 2023-2024

}
}
}
%>
STEP 6 Create Success and Error Pages
1. Create JSP pages for success (success.jsp)

<%@page language=”java” contentType=”text.html”%>


<html>
<head>
<title>Login Successful</title>
</head>
<body>
<h2>Login Successful</h2>
<p>Welcome,<%=request.getparameter(“user_id”)%> ! </p>
</body>
</html>
STEP 7 Create Success and Error Pages
1. Create JSP pages for success (error.jsp)

<%@page language=”java” contentType=”text.html”%>


<html>
<head>
<title>Login Error</title>
</head>
<body>
<h2>Login UnSuccessful</h2>
<p>Invalid user ID or Password. Please try again. </p>
</body>
</html>

AMCEC, Dept of ISE 33


ADVANCED JAVA (BIS402) 2023-2024

OUTPUT

AMCEC, Dept of ISE 34

You might also like