0% found this document useful (0 votes)
25 views31 pages

Java ArrayList and String Methods Demo

The document contains a series of Java programming exercises covering various topics such as ArrayLists, user-defined classes, string manipulation, and servlet creation. Each section includes code examples demonstrating specific functionalities like sorting, string methods, event handling, and web application interactions. Additionally, it provides instructions for deploying and testing a servlet application that accepts and displays student details.

Uploaded by

sssecsis25
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views31 pages

Java ArrayList and String Methods Demo

The document contains a series of Java programming exercises covering various topics such as ArrayLists, user-defined classes, string manipulation, and servlet creation. Each section includes code examples demonstrating specific functionalities like sorting, string methods, event handling, and web application interactions. Additionally, it provides instructions for deploying and testing a servlet application that accepts and displays student details.

Uploaded by

sssecsis25
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

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 [Link];
import [Link];

public class ArrayListDemo {


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

// Adding elements to the ArrayList


[Link]("Apple");
[Link]("Orange");
[Link]("Banana");
[Link]("Grape");
[Link]("Mango");
// Display the ArrayList
[Link]("Original ArrayList: " + arrayList);
// Removing an element from the ArrayList [Link]("Banana");
[Link]("ArrayList after removing 'Banana': " + arrayList);

// Sorting the ArrayList [Link](arrayList);


[Link]("Sorted ArrayList: " + arrayList);

// Converting ArrayList to Array


String[] array = new String[[Link]()];
array = [Link](array);
// Display the elements of the array
[Link]("Array elements: ");
for (String element : array) {
[Link](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 [Link];
import [Link];
import [Link];

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) {
[Link](i);
}
}

// Sorting by tens place


[Link](numbers, new Comparator<Integer>() {
@Override
public int compare(Integer num1, Integer num2) {
return [Link](num1 % 10, num2 % 10);
}
});

[Link]("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 [Link];
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>();

[Link](new Address("A", "11 Ave", "City", "IL", "00000"));


[Link](new Address("B", "11 Lane", "Town", "IL","99999"));
[Link](new Address("T", "11 St", "Province", "IL", "11111"));
for (Address element : ml){ [Link](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();
[Link]("EmptyString"+a);
char ch[]={'a','b','c','d'};
String b=new String(ch);
[Link]("String with one argument as Char="+b);
String c=new String(ch,1,3);
[Link]("String with Three argument as Char="+c);
String d=new String(b);
[Link]("String with String object="+d);
byte e[]={65,66,67,68,69};
String f=new String(e); [Link]("byte to String="+e); String g=new String(e,1,3);
[Link]("byte to string for subbyte="+g);
StringBuffer h=new StringBuffer("hello"); String i=new String(h);
[Link]("StringBuffer to String="+i);
StringBuilder j=new StringBuilder("welcome"); String k=new String(j);
[Link]("StringBuilder to Stirng="+k); int l[]={66,67,68,69,70};
String m=new String(l,1,3);
[Link]("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 = [Link](7); // Extracts character at index 7
char[] charArrayExample = [Link](); // Converts the string to a char array

// String comparison methods


String comparisonStr1 = "hello, openai!";
String comparisonStr2 = "Hello, OpenAI!";
boolean equalsExample = [Link](comparisonStr1); // Case−sensitive comparison
boolean equalsIgnoreCaseExample = [Link](comparisonStr1);
// Case−insensitive comparison

int compareToExample = [Link](comparisonStr2); // Lexicographical


comparison
// String search methods
boolean containsExample = [Link]("OpenAI"); // Checks if the string sequence
int indexOfExample = [Link]("OpenAI"); // Returns the index of the first
occurrence
int lastIndexOfExample = [Link]('o'); // Returns the index of the last
occurrence

// String modification methods


String substringExample = [Link](7); // Extracts a substring starting from
index 7
String replaceExample = [Link]("OpenAI", "World"); // Replaces OpenAI
"World"
String toLowerCaseExample = [Link](); // Converts the string to lower
case
String toUpperCaseExample = [Link](); // Converts the string to upper
case

// Output the results


[Link]("Original String: " + example);

[Link]("charAt(7): " + charAtExample);


[Link]("toCharArray(): " + new String(charArrayExample));
[Link]("equals(comparisonStr1): " + equalsExample);
[Link]("equalsIgnoreCase(comparisonStr1): " + equalsIgnoreCaseExample);
[Link]("compareTo(comparisonStr2): " + compareToExample);
[Link]("contains(\"OpenAI\"): " + containsExample);
[Link]("indexOf(\"OpenAI\"): " + indexOfExample);
[Link]("lastIndexOf('o'): " + lastIndexOfExample);

Dept Of ISE, SSSE, Tumakuru Page 5


[Link]("substring(7): " + substringExample);
Advanced Java (IPCC) BIS402 2024-20

[Link]("replace(\"OpenAI\", \"World\"): " + replaceExample);


[Link]("toLowerCase(): " + toLowerCaseExample);
[Link]("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
[Link](" World");
[Link]("After append: " + sb);

// 2. Insert method
[Link](5, " Java");
[Link]("After insert: " + sb);

// 3. Replace method
[Link](6, 10, "C++");
[Link]("After replace: " + sb);

// 4. Delete method
[Link](5, 9);
[Link]("After delete: " + sb);
// 5. Reverse method
[Link]();
[Link]("After reverse: " + sb);
// Resetting the StringBuffer for further methods
[Link](); // To restore the original state

// 6. Capacity method
[Link]("Capacity: " + [Link]());

// 7. Ensure capacity method


[Link](50);
[Link]("Capacity after ensuring: " + [Link]());
// 8. Set length method
[Link](5);
[Link]("After set length: " + sb);

// 9. Char at method
char ch = [Link](1);
[Link]("Char at index 1: " + ch);

// 10. Substring method


String substring = [Link](1, 3);
[Link]("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 [Link].*;
import [Link];
import [Link];

public class ButtonClickExample {


public static void main(String[] args) {
// Create the frame
JFrame frame = new JFrame("Button Click Example");
[Link](JFrame.EXIT_ON_CLOSE);
[Link](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


[Link](new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
[Link]("Alpha Pressed");
}
});

[Link](new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
[Link]("Beta Pressed");
}
});
// Add the buttons and label to the panel
[Link](alphaButton);
[Link](betaButton);
[Link](messageLabel);
// Add the panel to the frame
[Link](panel);
// Make the frame visible
[Link](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 [Link].*;
import [Link].*; import [Link].*;
public class TestServlet extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res)throws
ServletException,IOException
{
PrintWriter out=[Link](); [Link]("Hello userNamr"); [Link]("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/
│ └── [Link]/
│ └── [Link]
├── WebContent/
│ ├── [Link]
│ └── WEB-INF/
│ └── [Link]

[Link]

<!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>

[Link]:

package [Link];

import [Link]; import [Link];


import [Link]; import [Link]; import
[Link];
import [Link];

Dept Of ISE, SSSE, Tumakuru Page 14


Advanced Java (IPCC) BIS402 2024-202

import [Link];

@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 = [Link]("name"); String usn =
[Link]("usn"); String marks = [Link]("marks");

// Set response content type [Link]("text/html");

// Write the response


PrintWriter out = [Link](); [Link]("<html><body>"); [Link]("<h2>Student
Details</h2>"); [Link]("<p>Name: " + name + "</p>"); [Link]("<p>USN: " + usn + "</p>");
[Link]("<p>Total Marks: " + marks + "</p>"); [Link]("</body></html>");
}
}

[Link] (Servlet Configuration):

<web−app xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link] version="3.0">
<servlet>
<servlet−name>StudentServlet</servlet−name>
<servlet−class>[Link]</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 [Link]
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/
│ └── [Link]/
│ ├── [Link]
│ └── [Link]
├── WebContent/
│ ├── [Link]
│ └── WEB−INF/
│ └── [Link]

[Link]

<!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>

[Link]:

package [Link];

import [Link]; import [Link];


import [Link]; import [Link]; import
[Link];
import [Link];
import [Link]; import [Link];

@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 [Link](7 * 24 * 60 * 60);
// Add the cookie to the response [Link](cookie);

// Set response content type [Link]("text/html");

// Write the response


PrintWriter out = [Link](); [Link]("<html><body>");
[Link]("<h2>Cookie 'EMPID' with value 'AN2356' has been set.</h2>"); [Link]("<p><a
href='[Link]'>Go back</a></p>"); [Link]("</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/
│ └── [Link]/
│ ├── [Link]
│ └── [Link]
├── WebContent/
│ ├── [Link]
│ └── WEB−INF/
│ └── [Link]

Dept Of ISE, SSSE, Tumakuru Page 18


Advanced Java (IPCC) BIS402 2024-202

[Link]:
This servlet sets a cookie with the name "EMPID" and value "AN2356". java
Copy code
package [Link];

import [Link];
import [Link]; import [Link]; import
[Link];
import [Link];
import [Link]; import [Link];

@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) [Link](86400);

// Add the cookie to the response [Link](empIdCookie);

// Notify the user that the cookie has been set [Link]("text/html");
[Link]().println("<html><body><h2>Cookie 'EMPID' with value 'AN2356' has been
set.</h2></body></html>");
}
}

[Link]:
This servlet reads the cookies sent by the client and displays the value of the "EMPID" cookie. java
Copy code
package [Link];

import [Link];
import [Link];

Dept Of ISE, SSSE, Tumakuru Page 19


Advanced Java (IPCC) BIS402 2024-202

import [Link]; import [Link];


import [Link];
import [Link]; import [Link];

@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 = [Link]();

// 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 ([Link]().equals("EMPID")) { empIdValue = [Link](); break;
}
}
}

// Display the value of the "EMPID" cookie [Link]("text/html");


[Link]().println("<html><body><h2>Value of 'EMPID' cookie: " + empIdValue +
"</h2></body></html>");
}
}

[Link]:

<web−app xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link] version="3.0">
<servlet>
<servlet−name>SetCookieServlet</servlet−name>

Dept Of ISE, SSSE, Tumakuru Page 20


Advanced Java (IPCC) BIS402 2024-202
<servlet−class>[Link]</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>[Link]</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 [Link]
You should see a message indicating that the cookie has been set.
Read the Cookie:
Open a web browser and navigate to [Link]
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 [Link]; import [Link]; import [Link];

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


[Link](URL, USER, PASSWORD);
}
}

Step 2: Create the StudentDAO Class

import [Link];
import [Link]; import [Link];
import [Link]; import [Link]; import [Link];

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 = [Link]();

Dept Of ISE, SSSE, Tumakuru Page 22


Advanced Java (IPCC) BIS402 2024-202

PreparedStatement pstmt = [Link](sql)) { [Link](1, name);


[Link](2, usn); [Link](3, marks); [Link]();
}
}

public void updateStudent(String usn, int marks) throws SQLException { String sql = "UPDATE students
SET marks = ? WHERE usn = ?";
try (Connection conn = [Link](); PreparedStatement pstmt =
[Link](sql)) { [Link](1, marks);
[Link](2, usn); [Link]();
}
}

public void deleteStudent(String usn) throws SQLException { String sql = "DELETE FROM students
WHERE usn = ?";
try (Connection conn = [Link](); PreparedStatement pstmt =
[Link](sql)) { [Link](1, usn);
[Link]();
}
}

public Student getStudentByUsn(String usn) throws SQLException { String sql = "SELECT * FROM
students WHERE usn = ?";
try (Connection conn = [Link](); PreparedStatement pstmt =
[Link](sql)) { [Link](1, usn);
ResultSet rs = [Link](); if ([Link]()) {
return new Student([Link]("id"), [Link]("name"), [Link]("usn"), [Link]("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 = [Link](); PreparedStatement pstmt =


[Link](sql); ResultSet rs = [Link]()) {
while ([Link]()) {
[Link](new Student([Link]("id"), [Link]("name"), [Link]("usn"), [Link]("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) { [Link] = id;
[Link] = name; [Link] = usn; [Link] = 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 [Link]; import [Link];

public class Main {


public static void main(String[] args) { StudentDAO studentDAO = new StudentDAO();

try {
// Insert a new student [Link]("John Doe", "AN2356", 90);
[Link]("Student inserted.");

// Update the student's marks [Link]("AN2356", 95); [Link]("Student


updated.");

// Retrieve the student by USN


Student student = [Link]("AN2356"); [Link]("Student retrieved: " +
student);

// Retrieve all students


List<Student> students = [Link](); [Link]("All students:");
for (Student s : students) { [Link](s);
}

// Delete the student [Link]("AN2356"); [Link]("Student deleted.");


} catch (SQLException e) { [Link]();
}
}
}

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/
│ └── [Link]/
│ └── [Link]
├── WebContent/
│ ├── [Link]
│ ├── [Link]
│ ├── [Link]
│ └── WEB-INF/
│ └── [Link]

Step 1: Create the JDBC Utility Class

package [Link]; import [Link];


import [Link]; import [Link];

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


[Link](URL, USER, PASSWORD);
}}

Dept Of ISE, SSSE, Tumakuru Page 27


Advanced Java (IPCC) BIS402 2024-202

Step 2: Create the [Link]

<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<h2>Login</h2>
<form action="login−[Link]" 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 [Link]

<%@ page import="[Link].*, [Link]" %>


<%
String userId = [Link]("user_id"); String password = [Link]("password");
boolean isValid = false;

if (userId != null && password != null) {


try (Connection conn = [Link]()) {
String sql = "SELECT * FROM users WHERE user_id = ? AND password = ?"; try (PreparedStatement
pstmt = [Link](sql)) {
[Link](1, userId); [Link](2, password); ResultSet rs = [Link](); if
([Link]()) {
isValid = true;
}
}
} catch (SQLException e) { [Link]();
}
}

if (isValid) {

Dept Of ISE, SSSE, Tumakuru Page 28


Advanced Java (IPCC) BIS402 2024-202

[Link]("login−[Link]");
} else {
[Link]("login−[Link]");
}
%>

Step 4: Create the [Link]

<!DOCTYPE html>
<html>
<head>
<title>Login Successful</title>
</head>
<body>
<h2>Login Successful</h2>
<p>Welcome, <%= [Link]("user_id") %>!</p>
</body>
</html>

Step 5: Create the [Link]

<!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 [Link]

<web−app xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link] version="3.0">
<servlet>
<servlet−name>jsp</servlet−name>
<servlet−class>[Link]</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

Common questions

Powered by AI

In Java, both `StringBuffer` and `StringBuilder` can be converted to a `String` using their constructors. This involves creating a `StringBuffer` or `StringBuilder`, making modifications, and then constructing a new `String` object directly from these using `new String(StringBuffer)` or `new String(StringBuilder)`. These operations are similar and show no difference in functionality for conversion despite `StringBuffer` being synchronized and `StringBuilder` being unsynchronized.

To demonstrate adding, removing, sorting elements, and converting them into an array using an ArrayList in Java, first create an ArrayList and add elements using the `add` method. Remove elements using `remove`, sort them using `Collections.sort`, and convert them to an array using the `toArray` method. For example, create an ArrayList of strings, add several fruits, remove 'Banana', sort the list, then convert it to an array and print the contents.

To sort numbers based on their tens digit in Java, a Comparator can be used with the `Collections.sort` method, providing custom logic to compare the tens digit by taking `num1 % 10` and `num2 % 10` in the `compare` method of a Comparator. The list of numbers is then sorted according to this criteria.

The `ensureCapacity` method in `StringBuffer` ensures that the capacity is at least equal to the specified minimum, whereas `setLength` changes the length of the sequence. If the new length is greater, new char values are added; if less, the sequence is truncated. These methods allow dynamic adjustment of the buffer's capacity and contents.

In Java Servlets, a cookie named 'EMPID' can be set by creating a `Cookie` object with the desired name and value, then adding it to the HTTP response using `response.addCookie(cookie)`. To retrieve this cookie, the server reads the cookies sent by the client and locates the one with the name 'EMPID'.

To deploy a Java web application, compile the project ensuring no errors, set up the servlet configurations in `web.xml` defining servlets with `<servlet>` and `<servlet-mapping>` tags, deploy the project on a server like Tomcat, start the server, and navigate to the application URL. The servlet mapping associates the servlet with a specific URL path.

CRUD operations in the `StudentDAO` class include `insertStudent`, `updateStudent`, `deleteStudent`, `getStudentByUsn`, and `getAllStudents`. These methods use SQL statements with `PreparedStatement` to insert, update, delete, and retrieve student data from a MySQL database. Connection management is handled by the `getConnection` method of the `JDBCUtil` class.

In a Java servlet application, student details are read from the request object using `request.getParameter()`, and the response is displayed using `response.setContentType()` to set response types, and then `PrintWriter` prints HTML content within the servlet's `doGet` or `doPost` methods. This process encapsulates form handling and dynamic content generation for servlets.

Java provides several methods for string comparison: `equals()`, `equalsIgnoreCase()`, and `compareTo()`. `equals()` performs a case-sensitive comparison of two strings, while `equalsIgnoreCase()` ignores case differences. `compareTo()` provides lexicographical comparison, returning a negative, zero, or positive value depending on whether the calling string is lexicographically less than, equal to, or greater than the comparison string, and it is case-sensitive.

User-defined class objects such as `Address` can be stored in Java collections like `LinkedList`. Instances of the class are added to a LinkedList using `add()`. To iterate over and print each stored object, a for-each loop can be used. Each object in the collection can be accessed and its `toString` method can be called to display the structured data.

You might also like