Advanced Java (IPCC) BIS402 2024-20
1. Implement a java program to demonstrate creating and 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) {
// Create an ArrayList
ArrayList<String> arrayList = new ArrayList<>();
// Adding elements to the ArrayList
arrayList.add("Apple");
arrayList.add("Orange");
arrayList.add("Banana");
arrayList.add("Grape");
arrayList.add("Mango");
// Display the ArrayList
System.out.println("Original ArrayList: " + arrayList);
// Removing an element from the ArrayList arrayList.remove("Banana");
System.out.println("ArrayList after removing 'Banana': " + arrayList);
// Sorting the ArrayList Collections.sort(arrayList);
System.out.println("Sorted ArrayList: " + arrayList);
// Converting ArrayList to Array
String[] array = new String[arrayList.size()];
array = arrayList.toArray(array);
// Display the elements of the array
System.out.println("Array elements: ");
for (String element : array) {
System.out.println(element);
}
}
}
Output:
Dept Of ISE, SSSE, Tumakuru Page 1
Advanced Java (IPCC) BIS402 2024-20
2. Develop a java program to read random numbers between a given range that are multiple of 2
and 5 the numbers according to tens place using comparator
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class ArrayListDemo {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
// Adding random multiples of 2 and 5 to ArrayList
// Assuming range from 1 to 100
for(int i = 1; i <= 100; i++) {
if(i % 2 == 0 && i % 5 == 0) {
numbers.add(i);
}
}
// Sorting by tens place
Collections.sort(numbers, new Comparator<Integer>() {
@Override
public int compare(Integer num1, Integer num2) {
return Integer.compare(num1 % 10, num2 % 10);
}
});
System.out.println("Sorted numbers: " + numbers);
}
}
Output:
Dept Of ISE, SSSE, Tumakuru Page 2
Advanced Java (IPCC) BIS402 2024-20
3. Implement a java program illustrate storing a user defined classes in collection
import java.util.LinkedList;
class Address
{
private String name; private String street; private String city; private String state; private String
code;
Address(String n, String s, String c, String st, String cd)
{
name = n; street = s; city = c; state = st; code = cd;
}
public String toString()
{
return name + "\n" + street + "\n" + city + " " + state + " " +code;
}
}
public class Main
{
public static void main(String args[])
{
LinkedList<Address> ml = new LinkedList<Address>();
ml.add(new Address("A", "11 Ave", "City", "IL", "00000"));
ml.add(new Address("B", "11 Lane", "Town", "IL","99999"));
ml.add(new Address("T", "11 St", "Province", "IL", "11111"));
for (Address element : ml){ System.out.println(element + "\n");
}
}
}
Output:
Dept Of ISE, SSSE, Tumakuru Page 3
Advanced Java (IPCC) BIS402 2024-202
4. A java program to illustrate the use of different types of String Buffer methods.
public class StrBuf
{
public static void main(String[] args) {
String a=new String();
System.out.println("EmptyString"+a);
char ch[]={'a','b','c','d'};
String b=new String(ch);
System.out.println("String with one argument as Char="+b);
String c=new String(ch,1,3);
System.out.println("String with Three argument as Char="+c);
String d=new String(b);
System.out.println("String with String object="+d);
byte e[]={65,66,67,68,69};
String f=new String(e); System.out.println("byte to String="+e); String g=new String(e,1,3);
System.out.println("byte to string for subbyte="+g);
StringBuffer h=new StringBuffer("hello"); String i=new String(h);
System.out.println("StringBuffer to String="+i);
StringBuilder j=new StringBuilder("welcome"); String k=new String(j);
System.out.println("StringBuilder to Stirng="+k); int l[]={66,67,68,69,70};
String m=new String(l,1,3);
System.out.println("codepoint to String="+m);
}
Output:
Dept Of ISE, SSSE, Tumakuru Page 4
Advanced Java (IPCC) BIS402 2024-20
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 StringMethodsExample {
public static void main(String[] args) {
// Example string
String example = "Hello, OpenAI!";
// Character extraction methods
char charAtExample = example.charAt(7); // Extracts character at index 7
char[] charArrayExample = example.toCharArray(); // Converts the string to a char array
// String comparison methods
String comparisonStr1 = "hello, openai!";
String comparisonStr2 = "Hello, OpenAI!";
boolean equalsExample = example.equals(comparisonStr1); // Case−sensitive comparison
boolean equalsIgnoreCaseExample = example.equalsIgnoreCase(comparisonStr1);
// Case−insensitive comparison
int compareToExample = example.compareTo(comparisonStr2); // Lexicographical
comparison
// String search methods
boolean containsExample = example.contains("OpenAI"); // Checks if the string sequence
int indexOfExample = example.indexOf("OpenAI"); // Returns the index of the first
occurrence
int lastIndexOfExample = example.lastIndexOf('o'); // Returns the index of the last
occurrence
// String modification methods
String substringExample = example.substring(7); // Extracts a substring starting from
index 7
String replaceExample = example.replace("OpenAI", "World"); // Replaces OpenAI
"World"
String toLowerCaseExample = example.toLowerCase(); // Converts the string to lower
case
String toUpperCaseExample = example.toUpperCase(); // Converts the string to upper
case
// Output the results
System.out.println("Original String: " + example);
System.out.println("charAt(7): " + charAtExample);
System.out.println("toCharArray(): " + new String(charArrayExample));
System.out.println("equals(comparisonStr1): " + equalsExample);
System.out.println("equalsIgnoreCase(comparisonStr1): " + equalsIgnoreCaseExample);
System.out.println("compareTo(comparisonStr2): " + compareToExample);
System.out.println("contains(\"OpenAI\"): " + containsExample);
System.out.println("indexOf(\"OpenAI\"): " + indexOfExample);
System.out.println("lastIndexOf('o'): " + lastIndexOfExample);
Dept Of ISE, SSSE, Tumakuru Page 5
System.out.println("substring(7): " + substringExample);
Advanced Java (IPCC) BIS402 2024-20
System.out.println("replace(\"OpenAI\", \"World\"): " + replaceExample);
System.out.println("toLowerCase(): " + toLowerCaseExample);
System.out.println("toUpperCase(): " + toUpperCaseExample);
}
}
Output:
Dept Of ISE, SSSE, Tumakuru Page 6
Advanced Java (IPCC) BIS402 2024-202
6. Implement a java program to illustrate the use of different types of string methods
public class StringBufferExample {
public static void main(String[] args) {
// Creating a StringBuffer instance
StringBuffer sb = new StringBuffer("Hello");
// 1. Append method
sb.append(" World");
System.out.println("After append: " + sb);
// 2. Insert method
sb.insert(5, " Java");
System.out.println("After insert: " + sb);
// 3. Replace method
sb.replace(6, 10, "C++");
System.out.println("After replace: " + sb);
// 4. Delete method
sb.delete(5, 9);
System.out.println("After delete: " + sb);
// 5. Reverse method
sb.reverse();
System.out.println("After reverse: " + sb);
// Resetting the StringBuffer for further methods
sb.reverse(); // To restore the original state
// 6. Capacity method
System.out.println("Capacity: " + sb.capacity());
// 7. Ensure capacity method
sb.ensureCapacity(50);
System.out.println("Capacity after ensuring: " + sb.capacity());
// 8. Set length method
sb.setLength(5);
System.out.println("After set length: " + sb);
// 9. Char at method
char ch = sb.charAt(1);
System.out.println("Char at index 1: " + ch);
// 10. Substring method
String substring = sb.substring(1, 3);
System.out.println("Substring from index 1 to 3: " + substring);
}
}
Dept Of ISE, SSSE, Tumakuru Page 7
Advanced Java (IPCC) BIS402 2024-202
Output:
Dept Of ISE, SSSE, Tumakuru Page 8
Advanced Java (IPCC) BIS402 2024-20
7. Demonstrate a swing event handling application that create 2 buttons Alpha and Beta display
the text “Alpha Pressed” when alpha button is clicked and “Beta pressed” when beta button is
clicked.
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ButtonClickExample {
public static void main(String[] args) {
// Create the frame
JFrame frame = new JFrame("Button Click Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
// Create a panel to hold the buttons
JPanel panel = new JPanel();
// Create the buttons
JButton alphaButton = new JButton("Alpha");
JButton betaButton = new JButton("Beta");
// Create a label to display the messages
JLabel messageLabel = new JLabel("");
// Add action listeners to the buttons
alphaButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
messageLabel.setText("Alpha Pressed");
}
});
betaButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
messageLabel.setText("Beta Pressed");
}
});
// Add the buttons and label to the panel
panel.add(alphaButton);
panel.add(betaButton);
panel.add(messageLabel);
// Add the panel to the frame
frame.add(panel);
// Make the frame visible
frame.setVisible(true);
Dept Of ISE, SSSE, Tumakuru Page 9
}
Advanced
} Java (IPCC) BIS402 2024-20
Output:
Dept Of ISE, SSSE, Tumakuru Page 10
Advanced Java (IPCC) BIS402 2024-20
8. A Program to display greeting message on the browser “Hello UserName”, “How are you?”,
accept username from the client using servlet.
import java.io.*;
import jakarta.servlet.*; import jakarta.servlet.http.*;
public class TestServlet extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res)throws
ServletException,IOException
{
PrintWriter out=res.getWriter(); out.println("Hello userNamr"); out.println("How are you");
}
}
<web−app>
<servlet>
<servlet−name>Test</servlet−name>
<servlet−class>TestServlet</servlet−class>
</servlet>
<servlet−mapping>
<servlet−name>Test</servlet−name>
<url−pattern>/test</url−pattern>
</servlet−mapping>
</web−app>
Output:
Setup path Steps:
Dept Of ISE, SSSE, Tumakuru Page 11
Advanced Java (IPCC) BIS402 2024-202
Dept Of ISE, SSSE, Tumakuru Page 12
Advanced Java (IPCC) BIS402 2024-202
Dept Of ISE, SSSE, Tumakuru Page 13
Advanced Java (IPCC) BIS402 2024-202
9. A servlet to display the name, USN, and total marks by accepting student details.
YourProject/
│
├── src/
│ └── com.example/
│ └── StudentServlet.java
├── WebContent/
│ ├── index.html
│ └── WEB-INF/
│ └── web.xml
index.html
<!DOCTYPE html>
<html>
<head>
<title>Student Details Form</title>
</head>
<body>
<h2>Enter Student Details</h2>
<form action="StudentServlet" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br><br>
<label for="usn">USN:</label>
<input type="text" id="usn" name="usn"><br><br>
<label for="marks">Total Marks:</label>
<input type="number" id="marks" name="marks"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
StudentServlet.java:
package com.example;
import java.io.IOException; import java.io.PrintWriter;
import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import
javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
Dept Of ISE, SSSE, Tumakuru Page 14
Advanced Java (IPCC) BIS402 2024-202
import javax.servlet.http.HttpServletResponse;
@WebServlet("/StudentServlet")
public class StudentServlet extends HttpServlet { private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// Get the student details from the request String name = request.getParameter("name"); String usn =
request.getParameter("usn"); String marks = request.getParameter("marks");
// Set response content type response.setContentType("text/html");
// Write the response
PrintWriter out = response.getWriter(); 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: " + marks + "</p>"); out.println("</body></html>");
}
}
web.xml (Servlet Configuration):
<web−app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema−instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web−app_3_0.xsd" version="3.0">
<servlet>
<servlet−name>StudentServlet</servlet−name>
<servlet−class>com.example.StudentServlet</servlet−class>
</servlet>
<servlet−mapping>
<servlet−name>StudentServlet</servlet−name>
<url−pattern>/StudentServlet</url−pattern>
</servlet−mapping>
</web−app>
Dept Of ISE, SSSE, Tumakuru Page 15
Advanced Java (IPCC) BIS402 2024-202
Steps to Deploy and Test:
Build the Project: Ensure your project builds successfully with no errors.
Deploy the Project: Deploy the project to your Tomcat server.
Run the Server: Start the Tomcat server.
Access the Form: Open a web browser and navigate to http://localhost:8080/YourProject/index.html.
Submit the Form: Enter the student details and submit the form to see the details displayed by the
servlet.
Output:
Dept Of ISE, SSSE, Tumakuru Page 16
Advanced Java (IPCC) BIS402 2024-202
10. A Java Program to create and read the cookie for the given cookie name as “EMPID” and its value
as “AN2356”.
YourProject/
│
├── src/
│ └── com.example/
│ ├── SetCookieServlet.java
│ └── ReadCookieServlet.java
├── WebContent/
│ ├── index.html
│ └── WEB−INF/
│ └── web.xml
index.html
<!DOCTYPE html>
<html>
<head>
<title>Cookie Example</title>
</head>
<body>
<h2>Cookie Example</h2>
<p><a href="SetCookieServlet">Set Cookie</a></p>
<p><a href="ReadCookieServlet">Read Cookie</a></p>
</body>
</html>
SetCookieServlet.java:
package com.example;
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("/SetCookieServlet")
public class SetCookieServlet extends HttpServlet { private static final long serialVersionUID = 1L;
Dept Of ISE, SSSE, Tumakuru Page 17
Advanced Java (IPCC) BIS402 2024-202
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// Create a cookie named "EMPID" with value "AN2356" Cookie cookie = new Cookie("EMPID",
"AN2356");
// Set the cookie to expire in 7 days cookie.setMaxAge(7 * 24 * 60 * 60);
// Add the cookie to the response response.addCookie(cookie);
// Set response content type response.setContentType("text/html");
// Write the response
PrintWriter out = response.getWriter(); out.println("<html><body>");
out.println("<h2>Cookie 'EMPID' with value 'AN2356' has been set.</h2>"); out.println("<p><a
href='index.html'>Go back</a></p>"); out.println("</body></html>");
}
}
To create and read a cookie with the name "EMPID" and value "AN2356" in a Java web application
using servlets, you need to perform the following steps:
Create a Servlet to Set the Cookie:
This servlet will create a cookie with the name "EMPID" and value "AN2356" and send it to the client.
Create a Servlet to Read the Cookie:
This servlet will read the cookies sent by the client and display the value of the "EMPID" cookie.
Directory Structure:
css
Copy code YourProject/
│
├── src/
│ └── com.example/
│ ├── SetCookieServlet.java
│ └── ReadCookieServlet.java
├── WebContent/
│ ├── index.html
│ └── WEB−INF/
│ └── web.xml
Dept Of ISE, SSSE, Tumakuru Page 18
Advanced Java (IPCC) BIS402 2024-202
SetCookieServlet.java:
This servlet sets a cookie with the name "EMPID" and value "AN2356". java
Copy code
package com.example;
import java.io.IOException;
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("/SetCookieServlet")
public class SetCookieServlet extends HttpServlet { private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// Create a cookie with the name "EMPID" and value "AN2356" Cookie empIdCookie = new
Cookie("EMPID", "AN2356");
// Set the maximum age of the cookie to 24 hours (86400 seconds) empIdCookie.setMaxAge(86400);
// Add the cookie to the response response.addCookie(empIdCookie);
// Notify the user that the cookie has been set response.setContentType("text/html");
response.getWriter().println("<html><body><h2>Cookie 'EMPID' with value 'AN2356' has been
set.</h2></body></html>");
}
}
ReadCookieServlet.java:
This servlet reads the cookies sent by the client and displays the value of the "EMPID" cookie. java
Copy code
package com.example;
import java.io.IOException;
import javax.servlet.ServletException;
Dept Of ISE, SSSE, Tumakuru Page 19
Advanced Java (IPCC) BIS402 2024-202
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("/ReadCookieServlet")
public class ReadCookieServlet extends HttpServlet { private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// Get the cookies from the request Cookie[] cookies = request.getCookies();
// Initialize a variable to hold the value of the "EMPID" cookie String empIdValue = "Cookie not found";
// Check if cookies are present and search for the "EMPID" cookie if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("EMPID")) { empIdValue = cookie.getValue(); break;
}
}
}
// Display the value of the "EMPID" cookie response.setContentType("text/html");
response.getWriter().println("<html><body><h2>Value of 'EMPID' cookie: " + empIdValue +
"</h2></body></html>");
}
}
web.xml:
<web−app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema−instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web−app_3_0.xsd" version="3.0">
<servlet>
<servlet−name>SetCookieServlet</servlet−name>
Dept Of ISE, SSSE, Tumakuru Page 20
Advanced Java (IPCC) BIS402 2024-202
<servlet−class>com.example.SetCookieServlet</servlet−class>
</servlet>
<servlet−mapping>
<servlet−name>SetCookieServlet</servlet−name>
<url−pattern>/SetCookieServlet</url−pattern>
</servlet−mapping>
<servlet>
<servlet−name>ReadCookieServlet</servlet−name>
<servlet−class>com.example.ReadCookieServlet</servlet−class>
</servlet>
<servlet−mapping>
<servlet−name>ReadCookieServlet</servlet−name>
<url−pattern>/ReadCookieServlet</url−pattern>
</servlet−mapping>
</web−app>
Steps to Deploy and Test:
Build the Project: Ensure your project builds successfully with no errors.
Deploy the Project: Deploy the project to your Tomcat server.
Run the Server: Start the Tomcat server.
Set the Cookie:
Open a web browser and navigate to http://localhost:8080/YourProject/SetCookieServlet.
You should see a message indicating that the cookie has been set.
Read the Cookie:
Open a web browser and navigate to http://localhost:8080/YourProject/ReadCookieServlet.
You should see the value of the "EMPID" cookie displayed
Dept Of ISE, SSSE, Tumakuru Page 21
Advanced Java (IPCC) BIS402 2024-202
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...)
Database Setup:
Install a database system like MySQL or PostgreSQL.
Create a database named studentdb.
Create a table named students with the following structure:
CREATE TABLE students (
id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100) NOT NULL,
usn VARCHAR(50) NOT NULL UNIQUE,
marks INT NOT NULL
);
Step 1: Create a JDBC Utility Class
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException;
public class JDBCUtil {
private static final String URL = "jdbc:mysql://localhost:3306/studentdb"; private static final String
USER = "root"; // replace with your database username
private static final String PASSWORD = "password"; // replace with your database password
public static Connection getConnection() throws SQLException { return
DriverManager.getConnection(URL, USER, PASSWORD);
}
}
Step 2: Create the StudentDAO Class
import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.ResultSet;
import java.sql.SQLException; import java.util.ArrayList; import java.util.List;
public class StudentDAO {
public void insertStudent(String name, String usn, int marks) throws SQLException { String sql =
"INSERT INTO students (name, usn, marks) VALUES (?, ?, ?)";
try (Connection conn = JDBCUtil.getConnection();
Dept Of ISE, SSSE, Tumakuru Page 22
Advanced Java (IPCC) BIS402 2024-202
PreparedStatement pstmt = conn.prepareStatement(sql)) { pstmt.setString(1, name);
pstmt.setString(2, usn); pstmt.setInt(3, marks); pstmt.executeUpdate();
}
}
public void updateStudent(String usn, int marks) throws SQLException { String sql = "UPDATE students
SET marks = ? WHERE usn = ?";
try (Connection conn = JDBCUtil.getConnection(); PreparedStatement pstmt =
conn.prepareStatement(sql)) { pstmt.setInt(1, marks);
pstmt.setString(2, usn); pstmt.executeUpdate();
}
}
public void deleteStudent(String usn) throws SQLException { String sql = "DELETE FROM students
WHERE usn = ?";
try (Connection conn = JDBCUtil.getConnection(); PreparedStatement pstmt =
conn.prepareStatement(sql)) { pstmt.setString(1, usn);
pstmt.executeUpdate();
}
}
public Student getStudentByUsn(String usn) throws SQLException { String sql = "SELECT * FROM
students WHERE usn = ?";
try (Connection conn = JDBCUtil.getConnection(); PreparedStatement pstmt =
conn.prepareStatement(sql)) { pstmt.setString(1, usn);
ResultSet rs = pstmt.executeQuery(); if (rs.next()) {
return new Student(rs.getInt("id"), rs.getString("name"), rs.getString("usn"), rs.getInt("marks"));
}
}
return null;
}
public List<Student> getAllStudents() throws SQLException { List<Student> students = new
ArrayList<>();
String sql = "SELECT * FROM students";
Dept Of ISE, SSSE, Tumakuru Page 23
Advanced Java (IPCC) BIS402 2024-202
try (Connection conn = JDBCUtil.getConnection(); PreparedStatement pstmt =
conn.prepareStatement(sql); ResultSet rs = pstmt.executeQuery()) {
while (rs.next()) {
students.add(new Student(rs.getInt("id"), rs.getString("name"), rs.getString("usn"), rs.getInt("marks")));
}
}
return students;
}
}
Step 3: Create the Student Class
public class Student { private int id; private String name; private String usn; private int marks;
public Student(int id, String name, String usn, int marks) { this.id = id;
this.name = name; this.usn = usn; this.marks = marks;
}
public int getId() { return id;
}
public String getName() { return name;
}
public String getUsn() { return usn;
}
public int getMarks() { return marks;
}
Dept Of ISE, SSSE, Tumakuru Page 24
Advanced Java (IPCC) BIS402 2024-202
@Override
public String toString() {
return "Student{id=" + id + ", name='" + name + "', usn='" + usn + "', marks=" + marks + "}";
}
}
Step 4: Create the Main Class
import java.sql.SQLException; import java.util.List;
public class Main {
public static void main(String[] args) { StudentDAO studentDAO = new StudentDAO();
try {
// Insert a new student studentDAO.insertStudent("John Doe", "AN2356", 90);
System.out.println("Student inserted.");
// Update the student's marks studentDAO.updateStudent("AN2356", 95); System.out.println("Student
updated.");
// Retrieve the student by USN
Student student = studentDAO.getStudentByUsn("AN2356"); System.out.println("Student retrieved: " +
student);
// Retrieve all students
List<Student> students = studentDAO.getAllStudents(); System.out.println("All students:");
for (Student s : students) { System.out.println(s);
}
// Delete the student studentDAO.deleteStudent("AN2356"); System.out.println("Student deleted.");
} catch (SQLException e) { e.printStackTrace();
}
}
}
Dept Of ISE, SSSE, Tumakuru Page 25
Advanced Java (IPCC) BIS402 2024-202
Steps to Run the Program:
Set Up the Database:
Make sure your database is running.
Create the studentdb database and the students table using the provided SQL commands.
Add JDBC Driver to Classpath:
Ensure the JDBC driver for your database is added to the classpath of your project.
Compile and Run:
Compile all the Java files.
Run the Main class to see the output.
Output:
Student inserted. Student updated.
Student retrieved: Student{id=1, name='John Doe', usn='AN2356', marks=95} All students:
Student{id=1, name='John Doe', usn='AN2356', marks=95} Student deleted.
Dept Of ISE, SSSE, Tumakuru Page 26
Advanced Java (IPCC) BIS402 2024-202
12. A Program to design the Login page and validating the USER_ID and PASSWORD using JSP and
Database.
Database Setup:
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY, user_id VARCHAR(50) NOT NULL UNIQUE,
password VARCHAR(50) NOT NULL
);
JDBC Driver:
Directory Structure:
YourProject/
│
├── src/
│ └── com.example/
│ └── JDBCUtil.java
├── WebContent/
│ ├── login.jsp
│ ├── login-success.jsp
│ ├── login-fail.jsp
│ └── WEB-INF/
│ └── web.xml
Step 1: Create the JDBC Utility Class
package com.example; import java.sql.Connection;
import java.sql.DriverManager; import java.sql.SQLException;
public class JDBCUtil {
private static final String URL = "jdbc:mysql://localhost:3306/userdb";
private static final String USER = "root"; // replace with your database username
private static final String PASSWORD = "password"; // replace with your database password
public static Connection getConnection() throws SQLException { return
DriverManager.getConnection(URL, USER, PASSWORD);
}}
Dept Of ISE, SSSE, Tumakuru Page 27
Advanced Java (IPCC) BIS402 2024-202
Step 2: Create the login.jsp
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<h2>Login</h2>
<form action="login−validate.jsp" method="post">
<label for="user_id">User ID:</label>
<input type="text" id="user_id" name="user_id"><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password"><br><br>
<input type="submit" value="Login">
</form>
</body>
</html>
Step 3: Create the login-validate.jsp
<%@ page import="java.sql.*, com.example.JDBCUtil" %>
<%
String userId = request.getParameter("user_id"); String password = request.getParameter("password");
boolean isValid = false;
if (userId != null && password != null) {
try (Connection conn = JDBCUtil.getConnection()) {
String sql = "SELECT * FROM users WHERE user_id = ? AND password = ?"; try (PreparedStatement
pstmt = conn.prepareStatement(sql)) {
pstmt.setString(1, userId); pstmt.setString(2, password); ResultSet rs = pstmt.executeQuery(); if
(rs.next()) {
isValid = true;
}
}
} catch (SQLException e) { e.printStackTrace();
}
}
if (isValid) {
Dept Of ISE, SSSE, Tumakuru Page 28
Advanced Java (IPCC) BIS402 2024-202
response.sendRedirect("login−success.jsp");
} else {
response.sendRedirect("login−fail.jsp");
}
%>
Step 4: Create the login-success.jsp
<!DOCTYPE html>
<html>
<head>
<title>Login Successful</title>
</head>
<body>
<h2>Login Successful</h2>
<p>Welcome, <%= request.getParameter("user_id") %>!</p>
</body>
</html>
Step 5: Create the login-fail.jsp
<!DOCTYPE html>
<html>
<head>
<title>Login Failed</title>
</head>
<body>
<h2>Login Failed</h2>
<p>Invalid User ID or Password. Please try again.</p>
</body>
</html>
Step 6: Configure the web.xml
<web−app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema−instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web−app_3_0.xsd" version="3.0">
<servlet>
<servlet−name>jsp</servlet−name>
<servlet−class>org.apache.jasper.servlet.JspServlet</servlet−class>
<init−param>
<param−name>fork</param−name>
Dept Of ISE, SSSE, Tumakuru Page 29
Advanced Java (IPCC) BIS402 2024-202
<param−value>false</param−value>
</init−param>
<load−on−startup>3</load−on−startup>
</servlet>
<servlet−mapping>
<servlet−name>jsp</servlet−name>
<url−pattern>*.jsp</url−pattern>
</servlet−mapping>
</web−app>
Output:
User ID: test user Password: password123
Then click the "Login" button.
Dept Of ISE, SSSE, Tumakuru Page 30
Advanced Java (IPCC) BIS402 2024-202
Dept Of ISE, SSSE, Tumakuru Page 31