[go: up one dir, main page]

0% found this document useful (0 votes)
13 views59 pages

24MCA-56 Advanced Java Journal 6 Practs

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)
13 views59 pages

24MCA-56 Advanced Java Journal 6 Practs

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/ 59

ROLL NO – 24MCA56 ADVANCED JAVA

STEPS TO CONNECT TO ECLIPSE:


Step 1: Click on File > New > Java Project.

Step 2: Write a name of your Java project and click on finish.

GURU NANAK INSTITUTE OF MANAGEMENT STUDIES


1
ROLL NO – 24MCA56 ADVANCED JAVA

Step 3: Right click on the project file created and click on New >Class

Step 4: Finish

GURU NANAK INSTITUTE OF MANAGEMENT STUDIES


2
ROLL NO – 24MCA56 ADVANCED JAVA

Practical No. 1
(1.1) Generic Class

Aim: Write a Java Program to demonstrate a Generic Class


Code:
package generic;
class Test<T>
{
T obj;

Test(T obj)
{
this.obj=obj;
}
public T getObject()
{
return this.obj;
}
}
public class test{
public static void main(String[] args) {
Test<Integer> iobj=new Test<Integer>(04);
System.out.println("the value of integer:"+iobj.getObject());
Test<String>sobj=new Test<String>("Manoranjan");
System.out.println("the value of string:"+sobj.getObject());

GURU NANAK INSTITUTE OF MANAGEMENT STUDIES


3
ROLL NO – 24MCA56 ADVANCED JAVA

Output:

GURU NANAK INSTITUTE OF MANAGEMENT STUDIES


4
ROLL NO – 24MCA56 ADVANCED JAVA

(1.2) Generic Method


Aim: Write a Java Program to demonstrate generic method.
Code:
package generic;

public class prac1b {

void display()

{
System.out.println("Generic method example:");

}
<T>void gdisplay(T e)
{
System.out.println(e.getClass().getName()+"="+e);
}
public static void main(String[]args)
{
prac1b g1=new prac1b();
g1.display();
g1.gdisplay(1);
g1.gdisplay("Manoranjan");
g1.gdisplay(20.09);

GURU NANAK INSTITUTE OF MANAGEMENT STUDIES


5
ROLL NO – 24MCA56 ADVANCED JAVA

Output:

GURU NANAK INSTITUTE OF MANAGEMENT STUDIES


6
ROLL NO – 24MCA56 ADVANCED JAVA

(1.3) Wildcards
Aim: Write a Java program to demonstrate Wildcards in Java Generics.
Code:
package generic;

import java.util.Arrays;
import java.util.List;

public class prac1c {


private static double sum(List<? extends Number> List)
{
double sum=0.0;
for(Number i : List)
{
sum = sum+i.doubleValue();
}
return sum;

}
private static void show(List<? super Integer> list)
{
list.forEach
((x)->{
System.out.print(x+" ");
});

GURU NANAK INSTITUTE OF MANAGEMENT STUDIES


7
ROLL NO – 24MCA56 ADVANCED JAVA

public static void main(String[] args) {


System.out.println("Upper bounded:");
List<Integer>list1 = Arrays.asList(4,2,7,5,1,9);
System.out.println("List 1 Sum:"+ sum(list1));

List<Double> list2= Arrays.asList(4.7,2.4,7.3,5.4,1.5,9.2);


System.out.println("List 2 Sum:" + sum(list2));

System.out.println("\n Lower bounded:");


List<Integer> list3= Arrays.asList(4,2,7,5,1,9);

System.out.println("Only classes with integer SuperClass will be accepted");


show(list3);
}
}
Output:

GURU NANAK INSTITUTE OF MANAGEMENT STUDIES


8
ROLL NO – 24MCA56 ADVANCED JAVA

Practical No. 2
(2.1) List
Aim: Write a Java program to create a List containing a list of items of type String and use
for each loop to print the items of the list.
Code:
package Prac2;
import java.util.ArrayList;
public class prac2a {
public static void main(String[] args) {
ArrayList<String>list=new ArrayList<String>();
list.add("adbms");
list.add("python");
list.add("java");
list.add("maths");
System.out.println(list);
System.out.println("Traversing list through for each loop:");
for(String subject:list)
System.out.println(subject);

}
}

GURU NANAK INSTITUTE OF MANAGEMENT STUDIES


9
ROLL NO – 24MCA56 ADVANCED JAVA

Output:

GURU NANAK INSTITUTE OF MANAGEMENT STUDIES


10
ROLL NO – 24MCA56 ADVANCED JAVA

(2.2) List Iterator


Aim: Write a Java Program to create List containing list of items and use ListIterator
interface to print items present in the list. Also print the list in reverse/backward direction.
Code:
package Prac2;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
public class prac2b {
public static void main(String[] args) {
List<String>Products=new ArrayList<>();
Products.add("p1");
Products.add("p2");
Products.add("p3");
Products.add("p4");
System.out.println("printing products in forward direction using listiterator");
ListIterator<String>fi= Products.listIterator();
while(fi.hasNext()){
System.out.println(fi.next());
}
System.out.println("printing products in reverse direction using listiterator");
ListIterator<String>bi= Products.listIterator(Products.size());
while(bi.hasPrevious()) {
System.out.println(bi.previous());
}
}

GURU NANAK INSTITUTE OF MANAGEMENT STUDIES


11
ROLL NO – 24MCA56 ADVANCED JAVA

Output:

GURU NANAK INSTITUTE OF MANAGEMENT STUDIES


12
ROLL NO – 24MCA56 ADVANCED JAVA

Practical No. 3
(3.1) Sets
Aim: Write a java program to create a Set containing list of items of type String and print the
items in the list using Iterator interface. Also print the list in reverse/backward direction.
Code:
package Prac3;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
public class prac3a {
public static void main(String[] args) {
List<String>names = new LinkedList<>();
names.add("Amey");
names.add("Vishwas");
names.add("Shinde");
ListIterator<String> LT=names.listIterator();
System.out.println("forward direction ListIterator:");
while(LT.hasNext()) {
System.out.println(LT.next());
}
System.out.println("backward direction ListIterator:");
while(LT.hasPrevious()) {
System.out.println(LT.previous());
}
}
}

GURU NANAK INSTITUTE OF MANAGEMENT STUDIES


13
ROLL NO – 24MCA56 ADVANCED JAVA

Output:

GURU NANAK INSTITUTE OF MANAGEMENT STUDIES


14
ROLL NO – 24MCA56 ADVANCED JAVA

(3.2) Sets Operations


Aim: Write a Java program using Set interface containing list of items and perform the
following operations:
a. Add items in the set
b. Insert items of one set into another set
c. Remove items from the set
d. Search the specified item in the set
Code:
package Prac3;
import java.util.HashSet;
import java.util.Set;
public class prac3b {
public static void main(String[] args) {
Set<String>set1=new HashSet<>();
set1.add("Kaustubh");
set1.add("Subhash");
set1.add("Naik");
System.out.println("set1"+set1);
Set<String>set2=new HashSet<>();
set2.add("Ashmi");
set2.add("Arun");
set2.add("Anavkar");
set1.addAll(set2);
System.out.println("set1 adding item from set2"+set1);
set1.remove("Naik");
System.out.println("set1 after removing"+set1);
boolean isPresent=set1.contains("Kaustubh");
System.out.println("is Kaustubh present in set1:"+isPresent);
}
}

GURU NANAK INSTITUTE OF MANAGEMENT STUDIES


15
ROLL NO – 24MCA56 ADVANCED JAVA

Output:

GURU NANAK INSTITUTE OF MANAGEMENT STUDIES


16
ROLL NO – 24MCA56 ADVANCED JAVA

Practical No. 4
Aim: Write a java program using Map interface containing list of items having keys and
associated values and perform the following operations;
a. Add items in the map
b. Remove items from the map
c. Search specific key from the map
d. Get value of the specified key
e. Insert map elements of one map in to other map
f. Print all keys and values of the map
Code:
package prac4;
import java.util.HashMap;
import java.util.Map;

public class test {

public static void main(String[] args) {


Map<Integer,String> map1=new HashMap<>();
map1.put(1,"manoranjan");
map1.put(2,"mangaraj");
map1.put(3,"baral");

System.out.println("map1"+map1);
Map<Integer,String>map2=new HashMap<>();
map2.put(5,"komal");
map2.put(6,"vijay");
map2.put(7,"bhamble");
map1.putAll(map2);
System.out.println("map1 adding item from map2:"+map1);

map1.remove(5);
System.out.println("map1 after removing:"+map1);

GURU NANAK INSTITUTE OF MANAGEMENT STUDIES


17
ROLL NO – 24MCA56 ADVANCED JAVA

boolean isPresent=map1.containsKey(1);
System.out.println("is manoranjan present in set1:"+ isPresent);
String value= map1.get(2);
System.out.println("Value for key 1 is:"+ value);
System.out.println("Printing all key and values:");
for(Map.Entry<Integer,String>entry:map1.entrySet())
{

System.out.println("key:"+entry.getKey()+"values:"+entry.getValue());
}
}

Output:

GURU NANAK INSTITUTE OF MANAGEMENT STUDIES


18
ROLL NO – 24MCA56 ADVANCED JAVA

Practical No. 5
(5.1)
Aim: Write a java program using Lambda expressions to print “Hello World”.
Code:
package prac5;
public class prac5a {
public static void main(String[] args) {
Runnable helloworld=()-> System.out.println("Hello GNIMS World");
helloworld.run();
}
}

Output:

GURU NANAK INSTITUTE OF MANAGEMENT STUDIES


19
ROLL NO – 24MCA56 ADVANCED JAVA

(5.2)
Aim: Write a java program using Lambda expressions using single parameters.
Code:
package prac5;
import java.util.Arrays;
import java.util.List;
public class prac5b {
public static void main(String[] args) {
List<String>names=Arrays.asList("amey","vishwas","shinde");
names.forEach(name->System.out.println("Hello"+names+"!"));
}
}
Output:

GURU NANAK INSTITUTE OF MANAGEMENT STUDIES


20
ROLL NO – 24MCA56 ADVANCED JAVA

(5.3)
Aim: Write a java program using Lambda expressions with multiple parameters to add two
numbers.
Code:
package prac5;
interface A
{
int add(int i,int j);
}
public class prac5c
{
public static void main(String[] args) {
A num=(i,j)->i+j;
int result= num.add(7, 8);
System.out.println("Addition of 7 and 8 is : " +result);
}
}

Output:

GURU NANAK INSTITUTE OF MANAGEMENT STUDIES


21
ROLL NO – 24MCA56 ADVANCED JAVA

(5.4)
Aim: Write a Java Program using Lambda Expression to calculate the following
a) Convert Fahrenheit to Celsius
b) Convert Kilometers to Miles
Code:
package prac5;
interface Converter{
double convert(double input);
}
public class prac5d {
public static void main(String[] args) {
Converter a=f->(f-32)*5/9;
double celcius= a.convert(122);
System.out.println("100 Degree fahrenite is " +celcius+ " degree celcius");
Converter b =km->km/1.609344;
double miles=b.convert(90);
System.out.println("90 kilometer is : "+miles+ " miles");
}
}
Output:

GURU NANAK INSTITUTE OF MANAGEMENT STUDIES


22
ROLL NO – 24MCA56 ADVANCED JAVA

(5.5)
Aim: Write a Java Program using Lambda expression with or without return keyword.
Code:
package prac5;
interface Calculator{
int calculate(int i, int j);
}
public class prac5e {
public static void main(String[] args) {
Calculator add=(i,j)->i+j;
Calculator subtract=(i,j)->{
return i-j;
};
int sum= add.calculate(10,8);
int difference = subtract.calculate(78, 45);
System.out.println("Addition of 10 and 8 is : "+sum);
System.out.println("Subtraction of 78 and 45 is : "+difference);
}
}

Output:

GURU NANAK INSTITUTE OF MANAGEMENT STUDIES


23
ROLL NO – 24MCA56 ADVANCED JAVA

(5.6)
Aim: Write a Java Program using Lambda expression to concatenate two strings.
Code:
package prac5;
interface Concatenator{
String concatenate(String s1, String s2);
}
public class prac5f {
public static void main(String[] args) {
String str ="Amey_";
String str1="Shinde";
Concatenator cn= (s1,s2)-> s1+s2;
String result= cn.concatenate(str, str1);
System.out.println("The Concatenated String is : "+result);
}
}

Output:

GURU NANAK INSTITUTE OF MANAGEMENT STUDIES


24
ROLL NO – 24MCA56 ADVANCED JAVA

Practical No. 6
(6.1)
Aim: Create a Telephone directory using JSP and store all the information within a database,
so that later could be retrieved as per the requirement.
Code:
Create a database and create table
CREATE DATABASE PhoneDirectory;
USE PhoneDirectory;
CREATE TABLE Contacts (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
phone VARCHAR(20),
email VARCHAR(255)
);
DBConnection.java:

package phonedirectory;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBConnection {


public static Connection getConnection() throws SQLException {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
}
catch(ClassNotFoundException e) {
throw new SQLException("MySQL JDBC Driver not found",e);
}

GURU NANAK INSTITUTE OF MANAGEMENT STUDIES


25
ROLL NO – 24MCA56 ADVANCED JAVA

String url = "jdbc:mysql://localhost:3306/telephone_directory";


String username = "root";
String password = "password";

Connection connection = null;

try {
connection = DriverManager.getConnection(url, username, password);
} catch (SQLException e) {
e.printStackTrace();
throw e; // You may want to handle this exception more gracefully in a real
application
}

return connection;
}
}

Add_contact.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<%@ page import="java.sql.*" %>
<%@ page import="phonedirectory.DBConnection" %><%
Connection connection = DBConnection.getConnection();
if (request.getMethod().equals("POST")) {
String name = request.getParameter("name");
String phone = request.getParameter("phone");
String email = request.getParameter("email");
if (name != null && phone != null && email != null) {
GURU NANAK INSTITUTE OF MANAGEMENT STUDIES
26
ROLL NO – 24MCA56 ADVANCED JAVA

try {
// Insert the new contact into the database
String insertQuery = "INSERT INTO contacts (name, phone, email) VALUES (?, ?, ?)";
PreparedStatement preparedStatement = connection.prepareStatement(insertQuery);
preparedStatement.setString(1, name);
preparedStatement.setString(2, phone);
preparedStatement.setString(3, email);
preparedStatement.executeUpdate();
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
// Close the database connection
if (connection != null) {
connection.close();
}
%>
<html>
<body>
<h1>Add a New Contact</h1>
<form action="add_contact.jsp" method="post">
<label>Name: <input type="text" name="name"></label><br>
<label>Phone: <input type="text" name="phone"></label><br>
<label>Email: <input type="text" name="email"></label><br>
<input type="submit" value="Add Contact">
<a href="display_contacts.jsp">show data</a>
</form>
</body>

GURU NANAK INSTITUTE OF MANAGEMENT STUDIES


27
ROLL NO – 24MCA56 ADVANCED JAVA

</html>

Display_contact.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"


pageEncoding="UTF-8" %>
<%@ page import="java.sql.*" %>
<%@ page import="phonedirectory.DBConnection" %>
<!DOCTYPE html>
<html>
<head>
<title>Display Users</title>
</head>
<body>
<h1>Registered Users</h1>
<table border="1">
<tr>
<th>User ID</th>
<th>name</th>
<th>phone</th>
<th>Email</th>
<th>Update</th>
</tr>
<%
try {
// Establish a database connection
Connection connection = DBConnection.getConnection();
// Create and execute an SQL SELECT statement
String selectQuery = "SELECT * FROM contacts";
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(selectQuery);
GURU NANAK INSTITUTE OF MANAGEMENT STUDIES
28
ROLL NO – 24MCA56 ADVANCED JAVA

while (resultSet.next()) {
int userId = resultSet.getInt("id");
String username = resultSet.getString("name");
String phone = resultSet.getString("phone");
String email = resultSet.getString("email");
%>
<tr>
<td><%= userId %></td>
<td><%= username %></td>
<td><%= phone %></td>
<td><%= email %></td>
<td>
<a href="edit_contact.jsp?id=<%= userId %>">Edit</a>
<a href="delete_contact.jsp?id=<%= userId %>">Delete</a>
</td>
</tr>
<%
}
resultSet.close();
statement.close();
connection.close();
} catch (SQLException e) {
// Handle database errors here
out.println("Database error: " + e.getMessage());
}
%>
</table>
</body>
</html>

GURU NANAK INSTITUTE OF MANAGEMENT STUDIES


29
ROLL NO – 24MCA56 ADVANCED JAVA

Edit_contacts.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"


pageEncoding="UTF-8" %>
<%@ page import="java.sql.*" %>
<%@ page import="phonedirectory.DBConnection" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Edit Contact</title>
</head>
<body>
<h1>Edit Contact</h1>
<%
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
// Establish a database connection
connection = DBConnection.getConnection();
// Check if an ID parameter is provided in the URL
String idParam = request.getParameter("id");
int contactId = -1;
if (idParam != null) {
contactId = Integer.parseInt(idParam);
// Retrieve the contact's current details
String selectQuery = "SELECT * FROM contacts WHERE id=?";
preparedStatement = connection.prepareStatement(selectQuery);
preparedStatement.setInt(1, contactId);
resultSet = preparedStatement.executeQuery();
GURU NANAK INSTITUTE OF MANAGEMENT STUDIES
30
ROLL NO – 24MCA56 ADVANCED JAVA

if (resultSet.next()) {
String currentName = resultSet.getString("name");
String currentPhone = resultSet.getString("phone");
String currentEmail = resultSet.getString("email");
%>
<form action="update_contact.jsp" method="post">
<input type="hidden" name="id" value="<%= contactId %>">
Name: <input type="text" name="name" value="<%= currentName %>"><br>
Phone: <input type="text" name="phone" value="<%= currentPhone %>"><br>
Email: <input type="text" name="email" value="<%= currentEmail %>"><br>
<input type="submit" value="Update Contact">
</form>
<%
}
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// Close database resources individually
if (resultSet != null) resultSet.close();
if (preparedStatement != null) preparedStatement.close();
if (connection != null) connection.close();
}
%>
</body>
</html>

GURU NANAK INSTITUTE OF MANAGEMENT STUDIES


31
ROLL NO – 24MCA56 ADVANCED JAVA

update _contact.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"


pageEncoding="UTF-8" %>
<%@ page import="java.sql.*" %>
<%@ page import="phonedirectory.DBConnection" %>
<!DOCTYPE html>
<html>
<head>
<title>Update Contact</title>
</head>
<body>
<h1>Update Contact</h1>
<%
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
// Establish a database connection
connection = DBConnection.getConnection();
// Get the data submitted from the form
int contactId = Integer.parseInt(request.getParameter("id"));
String newName = request.getParameter("name");
String newPhone = request.getParameter("phone");
String newEmail = request.getParameter("email");
// Update the contact's information in the database

String updateQuery = "UPDATE contacts SET name=?, phone=?, email=? WHERE id=?";
preparedStatement = connection.prepareStatement(updateQuery);
preparedStatement.setString(1, newName);
preparedStatement.setString(2, newPhone);
preparedStatement.setString(3, newEmail);
GURU NANAK INSTITUTE OF MANAGEMENT STUDIES
32
ROLL NO – 24MCA56 ADVANCED JAVA

preparedStatement.setInt(4, contactId);
preparedStatement.executeUpdate();
%>
<p>Contact updated successfully.</p>
<a href="display_contacts.jsp">Back to Contacts</a>
<%
} catch (SQLException e) {
e.printStackTrace();
%>
<p>An error occurred while updating the contact: <%= e.getMessage() %></p>
<%
} finally {
// Close database resources individually
if (preparedStatement != null) preparedStatement.close();
if (connection != null) connection.close();
}
%>
</body>
</html>

Delete_contact.jsp:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<%@ page import="java.sql.*" %>
<%@ page import="phonedirectory.DBConnection" %>
<%
Connection connection = DBConnection.getConnection();
// Check if an ID parameter is provided in the URL
String idParam = request.getParameter("id");

GURU NANAK INSTITUTE OF MANAGEMENT STUDIES


33
ROLL NO – 24MCA56 ADVANCED JAVA

if (idParam != null) {
int contactId = Integer.parseInt(idParam);
try {
// Delete the contact from the database
String deleteQuery = "DELETE FROM contacts WHERE id=?";
PreparedStatement preparedStatement = connection.prepareStatement(deleteQuery);
preparedStatement.setInt(1, contactId);
preparedStatement.executeUpdate();
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
// Close the database connection
if (connection != null) {
connection.close();
}
%>
<html>
<body>
<h1>Contact Deleted</h1>
<p>The contact has been deleted successfully.</p>
<a href="display_contacts.jsp">Back to Contacts</a>
</body>
</html>

GURU NANAK INSTITUTE OF MANAGEMENT STUDIES


34
ROLL NO – 24MCA56 ADVANCED JAVA

Output:

GURU NANAK INSTITUTE OF MANAGEMENT STUDIES


35
ROLL NO – 24MCA56 ADVANCED JAVA

GURU NANAK INSTITUTE OF MANAGEMENT STUDIES


36
ROLL NO – 24MCA56 ADVANCED JAVA

(6.2)
Aim : Write a JSP Page to display the Registration Form.
Code:
<!DOCTYPE html>
<html>
<head>
<title>Registration Form</title>
</head>
<body>
<h2>Registration Form</h2>
<form action="storeRegistration.jsp" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br><br>

<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br><br>

<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br><br>
<input type="submit" value="Register">
</form>
</body>
</html>

GURU NANAK INSTITUTE OF MANAGEMENT STUDIES


37
ROLL NO – 24MCA56 ADVANCED JAVA

Output:

GURU NANAK INSTITUTE OF MANAGEMENT STUDIES


38
ROLL NO – 24MCA56 ADVANCED JAVA

(6.3)
Aim: Write a JSP Program to add, delete and display record from StudentMaster(Roll
No, Name, Semester, Course) table.
Code:
DBConnection.java
package studentdirectory;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBConnection {
public static Connection getConnection() throws SQLException {

try {
Class.forName("com.mysql.cj.jdbc.Driver");
}
catch(ClassNotFoundException e) {
throw new SQLException("MySQL JDBC Driver not found",e);
}
String url = "jdbc:mysql://localhost:3306/PhoneDirectory";
String username = "root";
String password = "";

Connection connection = null;

try {
connection = DriverManager.getConnection(url, username, password);
} catch (SQLException e) {
e.printStackTrace();
throw e; // You may want to handle this exception more gracefully in a real
application
}
GURU NANAK INSTITUTE OF MANAGEMENT STUDIES
39
ROLL NO – 24MCA56 ADVANCED JAVA

return connection;
}
}
Add_student.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page import="java.sql.*" %>
<%@ page import="studentdirectory.DBConnection" %><%
Connection connection = DBConnection.getConnection();
if (request.getMethod().equals("POST")) {
String Roll_no = request.getParameter("Roll_no");
String name = request.getParameter("name");
String semester = request.getParameter("semester");
String course = request.getParameter("course");
if (name != null && semester != null && course != null) {
try {
// Insert the new contact into the database
String insertQuery = "INSERT INTO students (Roll_no,name, semester, course) VALUES
(?, ?, ?, ?)";
PreparedStatement preparedStatement = connection.prepareStatement(insertQuery);
preparedStatement.setString(1, Roll_no);
preparedStatement.setString(2, name);
preparedStatement.setString(3, semester);
preparedStatement.setString(4, course);
preparedStatement.executeUpdate();
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
GURU NANAK INSTITUTE OF MANAGEMENT STUDIES
40
ROLL NO – 24MCA56 ADVANCED JAVA

}
// Close the database connection
if (connection != null) {
connection.close();
}
%>
<html>
<body>
<h1>Add a New Student Data</h1>
<form action="add_student.jsp" method="post">
<label>Roll_No: <input type="text" name="Roll_no"></label><br>
<label>Name: <input type="text" name="name"></label><br>
<label>Semester: <input type="text" name="semester"></label><br>
<label>Course: <input type="text" name="course"></label><br>
<input type="submit" value="Add Data">
<a href="display_data.jsp">show data</a>
</form>
</body>
</html>

Delete_data.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page import="java.sql.*" %>
<%@ page import="studentdirectory.DBConnection" %>
<%
Connection connection = DBConnection.getConnection();
// Check if an ID parameter is provided in the URL
String idParam = request.getParameter("id");
if (idParam != null) {

GURU NANAK INSTITUTE OF MANAGEMENT STUDIES


41
ROLL NO – 24MCA56 ADVANCED JAVA

int contactId = Integer.parseInt(idParam);


try {
// Delete the contact from the database
String deleteQuery = "DELETE FROM students WHERE id=?";
PreparedStatement preparedStatement = connection.prepareStatement(deleteQuery);
preparedStatement.setInt(1, contactId);
preparedStatement.executeUpdate();
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
// Close the database connection
if (connection != null) {
connection.close();
}
%>
<html>
<body>
<h1>Data Deleted</h1>
<p>The contact has been deleted successfully.</p>
<a href="display_data.jsp">Back to Contacts</a>
</body>
</html>

Display_data.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<%@ page import="java.sql.*" %>
<%@ page import="studentdirectory.DBConnection" %>
<!DOCTYPE html>
GURU NANAK INSTITUTE OF MANAGEMENT STUDIES
42
ROLL NO – 24MCA56 ADVANCED JAVA

<html>
<head>
<title>Display Students</title>
</head>
<body>
<h1>Registered Students</h1>
<table border="1">
<tr>
<th>User ID</th>
<th>Roll_no</th>
<th>name</th>
<th>semester</th>
<th>course</th>
<th>Update</th>
</tr>
<%
try {
// Establish a database connection
Connection connection = DBConnection.getConnection();
// Create and execute an SQL SELECT statement
String selectQuery = "SELECT * FROM students";
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(selectQuery);
while (resultSet.next()) {
int userId = resultSet.getInt("id");

String Roll_no= resultSet.getString("Roll_no");


String name = resultSet.getString("name");
String semester = resultSet.getString("semester");
String course = resultSet.getString("course");

GURU NANAK INSTITUTE OF MANAGEMENT STUDIES


43
ROLL NO – 24MCA56 ADVANCED JAVA

%>
<tr>
<td><%= userId %></td>
<td><%= Roll_no %></td>
<td><%= name %></td>
<td><%= semester %></td>
<td><%= course %></td>
<td>
<a href="edit_data.jsp?id=<%= userId %>">Edit</a>
<a href="delete_data.jsp?id=<%= userId %>">Delete</a>
</td>
</tr>
<%
}
resultSet.close();
statement.close();
connection.close();
} catch (SQLException e) {
// Handle database errors here
out.println("Database error: " + e.getMessage());
}
%>
</table>
</body>
</html>

edit_data.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<%@ page import="java.sql.*" %>
<%@ page import="studentdirectory.DBConnection" %>
GURU NANAK INSTITUTE OF MANAGEMENT STUDIES
44
ROLL NO – 24MCA56 ADVANCED JAVA

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Edit Data</title>
</head>
<body>
<h1>Edit Data</h1>
<%
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
// Establish a database connection
connection = DBConnection.getConnection();
// Check if an ID parameter is provided in the URL
String idParam = request.getParameter("id");
int contactId = -1;
if (idParam != null) {
contactId = Integer.parseInt(idParam);
// Retrieve the contact's current details
String selectQuery = "SELECT * FROM students WHERE id=?";
preparedStatement = connection.prepareStatement(selectQuery);
preparedStatement.setInt(1, contactId);
resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
String currentId = resultSet.getString("Id");

String currentRoll_no = resultSet.getString("Roll_no");


String currentName = resultSet.getString("name");

GURU NANAK INSTITUTE OF MANAGEMENT STUDIES


45
ROLL NO – 24MCA56 ADVANCED JAVA

String currentSemester = resultSet.getString("semester");


String currentCourse = resultSet.getString("course");
%>
<form action="update_data.jsp" method="post">
<input type="hidden" name="id" value="<%= currentId %>">
Roll_No:<input type="text" name="roll_no" value="<%= currentRoll_no %>"><br>
Name: <input type="text" name="name" value="<%= currentName %>"><br>
Semester: <input type="text" name="semester" value="<%= currentSemester %>"><br>
Course: <input type="text" name="course" value="<%= currentCourse %>"><br>
<input type="submit" value="Update Data">
</form>
<%
}
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// Close database resources individually
if (resultSet != null) resultSet.close();
if (preparedStatement != null) preparedStatement.close();
if (connection != null) connection.close();
}
%>
</body>
</html>

Update_data.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<%@ page import="java.sql.*" %>
<%@ page import="studentdirectory.DBConnection" %>
GURU NANAK INSTITUTE OF MANAGEMENT STUDIES
46
ROLL NO – 24MCA56 ADVANCED JAVA

<!DOCTYPE html>
<html>
<head>
<title>Update Data</title>
</head>
<body>
<h1>Update Data</h1>
<%
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
// Establish a database connection
connection = DBConnection.getConnection();
// Get the data submitted from the form
int contactId = Integer.parseInt(request.getParameter("id"));
String newRoll_no = request.getParameter("Roll_no");
String newName = request.getParameter("name");
String newSemester = request.getParameter("Semester");
String newCourse = request.getParameter("Course");
// Update the contact's information in the database
String updateQuery = "UPDATE students SET Roll_no=?, name=?, semester=?, course=?
WHERE id=?";
preparedStatement = connection.prepareStatement(updateQuery);
preparedStatement.setString(1,newRoll_no);
preparedStatement.setString(2, newName);
preparedStatement.setString(3, newSemester);
preparedStatement.setString(4, newCourse);

preparedStatement.executeUpdate();
%>
<p>Data updated successfully.</p>
GURU NANAK INSTITUTE OF MANAGEMENT STUDIES
47
ROLL NO – 24MCA56 ADVANCED JAVA

<a href="display_data.jsp">Back to Contacts</a>


<%
} catch (SQLException e) {
e.printStackTrace();
%>
<p>An error occurred while updating the contact: <%= e.getMessage() %></p>
<%
} finally {
// Close database resources individually
if (preparedStatement != null) preparedStatement.close();
if (connection != null) connection.close();
}
%>
</body>
</html>

Output:

GURU NANAK INSTITUTE OF MANAGEMENT STUDIES


48
ROLL NO – 24MCA56 ADVANCED JAVA

GURU NANAK INSTITUTE OF MANAGEMENT STUDIES


49
ROLL NO – 24MCA56 ADVANCED JAVA

GURU NANAK INSTITUTE OF MANAGEMENT STUDIES


50
ROLL NO – 24MCA56 ADVANCED JAVA

(6.4)
Aim: Design loan calculator using JSP which accepts Period of Time (in years) and
Principal Loan Amount. Display the payment amount for each loan and then list the
loan balance and interest paid for each payment over the term of the loan for the
following time period and interest rate:
a. 1 to 7 year at 5.35%
b. 8 to 15 year at 5.5%
c. 16 to 30 year at 5.75%
Code:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>SIMPLE INTEREST CALCULATOR</title>
</head>
<body>
<h1> Simple Interest Calculator</h1>
<form>
Principal Amount: <input type="text" id="principal" required><br>
Rate of Interest (per annum):<input type="text" id="rate" required><br>
Time(in years):<input type="text" id="time" required><br>

<input type="button" value="Calculate" onclick="calculateSimpleInterest()">


</form>
<p id="result"></p>
<script>
function calculateSimpleInterest(){
var principal = parseFloat(document.getElementById("principal").value);
var rate= parseFloat(document.getElementById("rate").value);
var time= parseFloat(document.getElementById("time").value);

GURU NANAK INSTITUTE OF MANAGEMENT STUDIES


51
ROLL NO – 24MCA56 ADVANCED JAVA

var simpleInterest= (principal*rate*time)/100;

var resultMessage="Simple Interest:" + simpleInterest;


var resultElement= document.getElementById("result");
resultElement.innerHTML = resultMessage;

}
</script>

</body>
</html>

Output:

GURU NANAK INSTITUTE OF MANAGEMENT STUDIES


52
ROLL NO – 24MCA56 ADVANCED JAVA

(6.5)
Aim: Write a program using JSP that displays a webpage consisting Application form
for change of Study Center which can be filled by any student who wants to change his/
her study center. Make necessary assumptions
Code:
prac6e.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Change Study Centre Application</title>
</head>
<body>
<h1> Change Study Center</h1>
<form action="exchange.jsp" method="post">
<label for="studentName">Student Name:</label>
<input type="text" id="studentName" name="studentName" required><br><br>
<label for="currentCenter">Current Study Center:</label>
<input type="text" id="currentCenter" name="currentCenter" required><br><br>
<label for="newCenter">New Study Center:</label>
<input type="text" id="newCenter" name="newCenter" required><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

GURU NANAK INSTITUTE OF MANAGEMENT STUDIES


53
ROLL NO – 24MCA56 ADVANCED JAVA

exchange.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Application Submitted</title>
</head>
<body>
<h1>Application Submitted</h1>
<p>Thank you for submitting your study center change application.</p>
<p> Student Name:<%=request.getParameter("studentName") %></p>
<p> Current Center:<%=request.getParameter("currentCenter") %></p>
<p> New Center:<%=request.getParameter("newCenter") %></p>
</body>
</html>

Output:

GURU NANAK INSTITUTE OF MANAGEMENT STUDIES


54
ROLL NO – 24MCA56 ADVANCED JAVA

(6.6)
Aim: Write a JSP program that demonstrates the use of JSP declaration, scriptlet,
directives, expression, header and footer.
Code:
Prac6f.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<style>
/* General page styles */
body {
font-family: Arial, sans-serif;
background-color: #f4f4f9;
color: #333;
margin: 0;
padding: 0;
}

/* Centering content */
center {
text-align: center;
margin-top: 50px;
}

/* Header styles */
h1 {

GURU NANAK INSTITUTE OF MANAGEMENT STUDIES


55
ROLL NO – 24MCA56 ADVANCED JAVA

color: #2c3e50;
}

/* Paragraph styles */
p{
font-size: 16px;
color: #7f8c8d;
}

/* Styling for the results */


.result {
font-size: 18px;
font-weight: bold;
color: #3498db;
margin: 10px 0;
}

/* Adding space between different results */


.result br {
margin-bottom: 15px;
}

/* Box to make the area and perimeter stand out */


.box {
background-color: #ecf0f1;
padding: 15px;
border-radius: 8px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
margin: 10px auto;
width: 60%;

GURU NANAK INSTITUTE OF MANAGEMENT STUDIES


56
ROLL NO – 24MCA56 ADVANCED JAVA

/* Footer styles */
footer {
font-size: 14px;
color: #95a5a6;
margin-top: 30px;
}
</style>
</head>
<body>
<%@ include file="header.jsp" %>
<center>
<%! int data=50; %>
<%= "Value of the variable is: " + data %>
<%! double circle(int n) {return 3.14 * n * n;} %>
<br>
<%= "Area of Circle is: " + circle(5) %>
<br>
<%! int rectangle(int l, int b) {return 1 * b;} %>
<%= "Area of rectangle is: " + rectangle(4,6) %>
<br>
<%! int perimeter(int x, int y) {
int peri = 2 * (x+y);
return peri;
}%>
<br>
<%= "Perimeter of rectangle: " + perimeter(5,6) %>
<br>
<p> thanks for visiting my page </p>

GURU NANAK INSTITUTE OF MANAGEMENT STUDIES


57
ROLL NO – 24MCA56 ADVANCED JAVA

<%@ include file="footer.jsp" %>


</center>
</body>
</html>

footer.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<center>
<b>Amey Shinde</b>
<b>24MCA-56</b>

</center>
</body>
</html>
Header.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>

GURU NANAK INSTITUTE OF MANAGEMENT STUDIES


58
ROLL NO – 24MCA56 ADVANCED JAVA

</head>
<body>
<center>
<h2>
This include directive example.
</h2>
</center>
</body>
</html>

Output:

GURU NANAK INSTITUTE OF MANAGEMENT STUDIES


59

You might also like