0% found this document useful (0 votes)
78 views52 pages

AJAVA Journal

The document contains code snippets from multiple Java programs demonstrating various concepts of generics, lambda expressions, collections like List, Set, Map using classes like ArrayList, LinkedList, HashSet, HashMap. It includes examples of generic classes, generic methods, wildcards, iterating through a List using ListIterator, Set operations, HashMap implementation, lambda expressions to print strings, with single and multiple parameters, and to convert between units like Fahrenheit to Celsius and Kilometer to Miles. The output of each program is also shown.

Uploaded by

Aryan Kamble
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)
78 views52 pages

AJAVA Journal

The document contains code snippets from multiple Java programs demonstrating various concepts of generics, lambda expressions, collections like List, Set, Map using classes like ArrayList, LinkedList, HashSet, HashMap. It includes examples of generic classes, generic methods, wildcards, iterating through a List using ListIterator, Set operations, HashMap implementation, lambda expressions to print strings, with single and multiple parameters, and to convert between units like Fahrenheit to Celsius and Kilometer to Miles. The output of each program is also shown.

Uploaded by

Aryan Kamble
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
You are on page 1/ 52

Roll No:23MCA11 ADVANCED JAVA

PRACTICAL 1.1
Generic Class
Aim: Program that demonstrates Generic Classes.
Code: package prac1;
class Test<T>{
T obj;
Test (T obj) { this.obj=obj;}
public T getobject(){return this.obj ;}
}
class generiClass{
public static void main(String[] args){
Test<Integer>iobj=new Test<Integer>(20);
System.out.println("the value of integer
is:"+iobj.getobject()); Test<String>sobj=new
Test<String>("anish"); System.out.println("the value of
string is: "+sobj.getobject());
}
}

Output:

GURU NANAK INSTITUTE OF MANAGEMENT


Roll No:23MCA11 ADVANCED JAVA

PRACTICAL 1.2
Generic Methods
Aim: Program that demonstrates Generic Methods.
Code: package prac1;

public class GenericMethod


{ 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)
{
GenericMethod g1= new
GenericMethod(); g1.display();
g1.gdisplay(1);
g1.gdisplay("Atharva");
g1.gdisplay(11.0);
}
}

Output:

GURU NANAK INSTITUTE OF MANAGEMENT


Roll No:23MCA11 ADVANCED JAVA

PRACTICAL 1.3
WildCards
Aim: Program that demonstrates Upper and Lower Bounded Wildcards.
Code: package prac1;

import java.util.*;
public class Wildcard {
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+"");
});
}
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("List1
sum:"+sum(list1));
List<Double>list2= Arrays.asList(4.7,2.4,7.3,5.4,1.5,9.2);
System.out.println("List2 sum:"+sum(list2));
System.out.println("\n lower bounded=");
List<Integer>list3=Arrays.asList(4,2,7,5,1,9);
System.out.println("only class with Integer Superclass will be Accepted:");
show(list3);
}
}

Output:

GURU NANAK INSTITUTE OF MANAGEMENT


Roll No:23MCA11 ADVANCED JAVA

PRACTICAL 2.1
List
Aim: Program that demonstrates List using ArrayList class.
Code: package practical_2_1;

import java.util.ArrayList;
public class Array1 {
public static void main(String[] args) {
ArrayList<String>list= new
ArrayList<String>(); list.add("MATHS");
list.add("ADBMS");
list.add("JAVA");
list.add("PYTHON");
System.out.println(list);
System.out.println("Travesing list trough for each loop");
for(String subject:list)
System.out.println(subject);
}
}

Output:

GURU NANAK INSTITUTE OF MANAGEMENT


Roll No:23MCA11 ADVANCED JAVA

PRACTICAL 2.2
ListIterator
Aim: Program that iterates through an ArrayList.
Code: package practical_2_1;

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
public class Practical2_2 {
public static void main(String[] args) {
List<String>Products=new ArrayList<>();
Products.add("product1");
Products.add("product2");
Products.add("product3");
Products.add("product4");
Products.add("product5");
System.out.println("Printing product in forward direction using listiterator: ");
ListIterator<String> forwarditerator=Products.listIterator();
while(forwarditerator.hasNext()) {
System.out.println(forwarditerator.next());
}
System.out.println("printing Products in Reverse Direction using Listiterator: ");
ListIterator<String>
backwarditerator=Products.listIterator(Products.size());
while(backwarditerator.hasPrevious()) {
System.out.println(backwarditerator.previous());
}
}
}

Output:

GURU NANAK INSTITUTE OF MANAGEMENT


Roll No:23MCA11 ADVANCED JAVA

PRACTICAL 3.1
SETS
Aim: Program that demonstrates List using LinkedList class.
Code: package set1;

import java.util.HashSet;
import java.util.Set;
public class set1 {
public static void main(String[] args)
{ Set<String>set1=new HashSet<>();
set1.add("atharva");
set1.add("kunal");
set1.add("sujit");
set1.add("siddhart");
set1.add("sumit");
System.out.println("set1:"+set1);
Set<String>set2=new HashSet<>();
set2.add("bushan");
set2.add("rohit");
set2.add("sanket");
set1.addAll(set2);
System.out.println("set1 after adding item from set2:"+set1);
set1.remove("rohit");
System.out.println("set1 after removing rohit:"+set1);
boolean isPresent=set1.contains("parth");
System.out.println("is parth present in
set1?"+isPresent);
}
}

Output:

GURU NANAK INSTITUTE OF MANAGEMENT


Roll No:23MCA11 ADVANCED JAVA

PRACTICAL 3.2
Sets Operations
Aim: Program that demonstrates HashSet implementation.
Code: package set1;

import java.util.*;
public class set1
{
public static void main(String[] args) {
List<String> names=new
LinkedList<>(); names.add("Atharva");
names.add("kunal");
names.add("siddharth");
ListIterator<String> listiterator= names.listIterator();
System.out.println("Forward Direction Iteration");
while(listiterator.hasNext())
{
System.out.println(listiterator.next());
}
System.out.println("Backward Direction Iteration");
while(listiterator.hasPrevious())
{
System.out.println(listiterator.previous());
}
}
}

Output:

GURU NANAK INSTITUTE OF MANAGEMENT


Roll No:23MCA11 ADVANCED JAVA

PRACTICAL 4.1
HashMap
Aim: Program that demonstrates HashMap implementation.
Code: package prac1;

import java.util.Map;
import java.util.HashMap;
public class mapg {
public static void main(String[] args){
Map<Integer,String> map1=new
HashMap<>(); map1.put(1,"anish");
map1.put(1,"kunal");
map1.put(1,"sid");
map1.put(1,"bhushan");
map1.put(1,"atharva");
System.out.println("Map1:" +map1);
Map<Integer,String> map2=new
HashMap<>(); map2.put(6,"chaitanya");
map2.put(6,"chirag");
map2.put(6,"anurag");
map1.putAll(map2);
System.out.println("Map1 after adding items from map2:" +map1);
map1.remove(3);
System.out.println("map1 after removing keys3:"
+map1); boolean ispresent=map1.containsKey(4);
System.out.println("is key4 present in map1?"
+ispresent); String value=map1.get(2);
System.out.println("the value of key 2 is:" +value);
System.out.println("printing all keys and values of map1:");
for(Map.Entry<Integer,String> entry:map1.entrySet()){
System.out.println("key:"+entry.getKey()+",value:"+entry.getValue());
}
}
}

Output:

GURU NANAK INSTITUTE OF MANAGEMENT


Roll No:23MCA11 ADVANCED JAVA

PRACTICAL 5.1
Lambda Expression(String)

Aim: Program that demonstrates Lambda Expression strings.


Code: package prac5;

public class LambdaEx {


public static void main(String[] args) {
Runnable helloWorld = ()-> System.out.println("HelloWorld");
helloWorld.run();
}
}

Output:

GURU NANAK INSTITUTE OF MANAGEMENT


Roll No:23MCA11 ADVANCED JAVA

PRACTICAL 5.2
LAMBDA EXPRESSION (SINGLE PARAMETER)
Aim: Program that demonstrates Lambda Expression using a single parameter.
Code: package prac5;

import java.util.Arrays;
import java.util.List;
public class LambdaEx1
{
public static void main(String[] args) {
List<String>names=Arrays.asList("atharva","kunal","siddharth","bhushan");
names.forEach(name->System.out.println("Hello,"+name+"!"));
}
}

Output:

GURU NANAK INSTITUTE OF MANAGEMENT


Roll No:23MCA11 ADVANCED JAVA

PRACTICAL 5.3
LAMBDA EXPRESSION (MULTIPLE PARAMETER)
Aim: Program that demonstrates Lambda Expression using Multiple Parameter.
Code: package prac5;

interface A
{
int add(int i, int j);
}
public class Demo {
public static void main(String[] args)
{
A obj=(i,j)-> i+j;
int result=obj.add(5, 4);
System.out.println(result);
}
}

Output:

GURU NANAK INSTITUTE OF MANAGEMENT


Roll No:23MCA11 ADVANCED JAVA

PRACTICAL 5.4
LAMBDA EXPRESSION (CONVERTER)
Aim: Program that demonstrates Lambda Expression to Calculate:
a) Convert Fahrenheit to Celsius.
b) Convert Kilometer to
Miles. Code: package prac5;

interface converter{
double convert(double input);
}
public class Demo1 {
public static void main(String[] args)
{
converter a = f-> (f-32) *
5/9; double
Celsius=a.convert(88);
System.out.println("88 degrees fahrehit is"+Celsius+"degrees
Celsius"); converter KilometersToMiles=km-> km/1.609344;
double miles = KilometersToMiles.convert(90);
System.out.println("10 kilometer is"+ miles+"miles");
}
}

Output:

GURU NANAK INSTITUTE OF MANAGEMENT


Roll No:23MCA11 ADVANCED JAVA

PRACTICAL 5.5
LAMBDA EXPRESSION (CALCULATOR)
Aim: Program that demonstrates Lambda Expression using Calculator.
Code: package prac5d_mca11;

interface A
{
int calculate(int i, int j);
}
public class Demo {
public static void main(String[] args)
{
A obj1 =(i,j)-> i+j;
int resultadd=obj1.calculate(20,7);
System.out.println(resultadd);
A obj2 = (i,j)->
{
return i-j;
};
int resultsub=obj2.calculate(30, 3);
System.out.println(resultsub);
}
}

Output:

GURU NANAK INSTITUTE OF MANAGEMENT


Roll No:23MCA11 ADVANCED JAVA

PRACTICAL 5.6
LAMBDA EXPRESSION (CONCATENATOR)
Aim: Program that demonstrates Lambda Expression using Concatenation.
Code: package prac5;
public class LambdaExp6 {
public static void main (String[] args)
{ String str1="Hello";
String str2="atharva";
concatenator concatenator =(s1,s2)->s1+s2;
String result=concatenator .concatenate (str1,str2);
System.out.println(result);
}
interface concatenator {
String concatenate (String s1,String s2);
}
}

Output:

GURU NANAK INSTITUTE OF MANAGEMENT


Roll No:23MCA11 ADVANCED JAVA

PRACTICAL 6.1

JSP(Phone Directoy)
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:
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
{ String url = "jdbc:mysql://localhost:3306/practical6a";
String username = "root";
String password = "12345";
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)
{ 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();
}
}
}

GURU NANAK INSTITUTE OF MANAGEMENT


Roll No:23MCA11 ADVANCED JAVA

// 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_contact.jsp">show data</a>
</form>
</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");
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_contact.jsp">Back to Contacts</a>
</body>
</html>

Display_contact.jsp:

GURU NANAK INSTITUTE OF MANAGEMENT


Roll No:23MCA11 ADVANCED JAVA

<%@ 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);
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>

GURU NANAK INSTITUTE OF MANAGEMENT


Roll No:23MCA11 ADVANCED JAVA

</html>

Edit_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>
<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();
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();

GURU NANAK INSTITUTE OF MANAGEMENT


Roll No:23MCA11 ADVANCED JAVA

if (connection != null) connection.close();

GURU NANAK INSTITUTE OF MANAGEMENT


Roll No:23MCA11 ADVANCED JAVA

}
%>
</body>
</html>

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);
preparedStatement.setInt(4, contactId);
preparedStatement.executeUpdate();
%>
<p>Contact updated successfully.</p>
<a href="Display_contact.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>

GURU NANAK INSTITUTE OF MANAGEMENT


Roll No:23MCA11 ADVANCED JAVA

Output:

GURU NANAK INSTITUTE OF MANAGEMENT


Roll No:23MCA11 ADVANCED JAVA

PRACTICAL 6.2

JSP (Registration form)


Aim: Write a JSP page to display the Registration form.
Code:

registration.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<body>
<form action="register.jsp" method="post">
<div class="container">
<label for="fname"><b>FirstName</b></label>
<input type="text" placeholder="Enter FirstName" name="fname" required>
<label for="mname"><b>MiddleName</b></label>
<input type="text" placeholder="Enter MiddleName" name="mname" required>
<label for="lname"><b>LastName</b></label>
<input type="text" placeholder="Enter LastName" name="lname" required>
<label for="pass"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="pass" required></br>
<input type="submit" name="btn_add" value="submit">
</div>
</form>
</body>
</html>

register.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
String firstname = request.getParameter("fname");
String middlename = request.getParameter("mname");
String lastname = request.getParameter("lname");
String password = request.getParameter("pass");
// Check if the passwords match
if (request.getParameter("btn_add")!=null) {
try {
// Establish a database connection
String dbUrl = "jdbc:mysql://localhost:3306/prac7";
String dbUser = "root";
String dbPassword = "1234";
Connection connection = DriverManager.getConnection(dbUrl, dbUser, dbPassword);

GURU NANAK INSTITUTE OF MANAGEMENT


Roll No:23MCA11 ADVANCED JAVA

// Create and execute an SQL INSERT statement


String insertQuery = "INSERT INTO register (fname, mname, lname, pass) VALUES (?, ?, ?, ?)";
PreparedStatement preparedStatement = connection.prepareStatement(insertQuery);
preparedStatement.setString(1, firstname);
preparedStatement.setString(2, middlename);
preparedStatement.setString(3, lastname);
preparedStatement.setString(4, password);
preparedStatement.executeUpdate();
// Close the database connection
connection.close();
// Display the registration success message
%>
<p>Registration successful!</p>
<%
} catch (SQLException e) {
// Handle any database errors here
out.println("Database error: " + e.getMessage());
}
} else if(request.getParameter("btn_show")!=null){
%>
<p>Passwords do not match. Please try again.</p>
<%
}
%>
</body>
</html>

Output:

GURU NANAK INSTITUTE OF MANAGEMENT


Roll No:23MCA11 ADVANCED JAVA

GURU NANAK INSTITUTE OF MANAGEMENT


Roll No:23MCA11 ADVANCED JAVA

PRACTICAL 6.4

JSP (Simple Interest Calculator)

Aim: Design a loan calculator using JSP which accepts period of time (in years) and Principal Loan
amount.

Code:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>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);
var simpleInterest = (principal * rate * time) / 100;
// Display the result in a traditional way
var resultMessage = "Simple Interest: " + simpleInterest;
var resultElement = document.getElementById("result");
resultElement.innerHTML = resultMessage;
}
</script>
</body>
</html>

Output:

GURU NANAK INSTITUTE OF MANAGEMENT


Roll No:23MCA11 ADVANCED JAVA

GURU NANAK INSTITUTE OF MANAGEMENT


Roll No:23MCA11 ADVANCED JAVA

PRACTICAL 6.5

JSP (Study Center)

Aim: Write a program using JSP that displays a webpage consisting Application form for change
study center.

Code:
main.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>Study Center</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap- [email protected]/font/bootstrap-
icons.css">
<link href="https://cdn.jsdelivr.net/npm/[email protected]
beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-
BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqlj6ltLrc4wSX0sz
H/Ev+nYRRuWlolflfl" crossorigin="anonymous">
</head>
<body>
<center>
<h1>Change of Study Center</h1>
<form action="Main.jsp" method="post">
<table>
<tr>
<td>UID No.</td>
<td><input type="text" name="uid" required/></td> </tr>
<td>
Current Center
</td>
<td>
<select name="currentCenter" required> <option selected disabled hidden></option>
<option value="MUMBAI">MUMBAI</option>
<option value="PUNE">PUNE</option>
<option value="GUJRAT">GUJRAT</option>
</select>
</td>
</tr>
<tr>
<td>
New Center
</td>
<td>
<select name="newCenter" required>
<option selected disabled hidden></option>
<option value="MUMBAI">MUMBAI</option>
<option value="PUNE">PUNE</option>

GURU NANAK INSTITUTE OF MANAGEMENT


Roll No:23MCA11 ADVANCED JAVA

<option value="GUJRAT">GUJRAT</option>
</select>
</td>
</tr>
</table>
<input type="submit" value="Submit"/>
</form>
</center>
<%
if(request.getParameter("uid") != null &&
request.getParameter("currentCenter") != null &&
request.getParameter("newCenter") != null) {
out.println(" <center> <br>Your request to change Study Center from <br>" +
request.getParameter("currentCenter") + " to " + request.getParameter("newCenter") + "<br> has been
sent to the Administrator.</center>");
}
%>
</body>
</html>

Output:

GURU NANAK INSTITUTE OF MANAGEMENT


Roll No:23MCA11 ADVANCED JAVA

PRACTICAL 6.7

JSP (Header, Scriplet, declaration, Footer)

Aim: Write a JSP program that demonstrates the use of JSP declaration, scriptlet, directives,
expression, header and footer.

code:
main.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>
<%@include file="NewFile.jsp" %>
<center>
<%!int data=50;
%>
<%="values of varible is"+ data %>
<%! double circle(int n){
return 3.14*n*n;
}%></br>
<%="area of circle is: "+circle(3) %></br>
<%! int rectangle(int a ,int b)
{ return a*b;

}%>
<%="area of rectangle is: " + rectangle(4,3)%>
<%! int perimeter(int x,int y)
{ int peri=2*(x+y);
return peri;
} %>
<%="perimeter is:" +perimeter(5,6) %>
<p>thanks for visiting my page </p>
</center>
<%@include file="footer.jsp" %>
</body>

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">
<%! int pageCount=0;
void addCount(){pageCount++;}%>
<% addCount(); %>
<title>JSP declaration,scriptiet,directives,expression,header and footer example</title>
</head>
<body>
<center>

GURU NANAK INSTITUTE OF MANAGEMENT


Roll No:23MCA11 ADVANCED JAVA

<h2><u>The include Directive Example</u></h2>


<p><b>This site been visited<%=pageCount
%> times</b>
</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>
<p><b>Atharva chakote</b>
<b>23MCA11</b>
</center>
</body>
</html>

output:

GURU NANAK INSTITUTE OF MANAGEMENT


Roll No:23MCA11 ADVANCED JAVA

PRACTICAL 7.1

Spring (Hello World)

Aim: Write a program to print “Hello World” using spring framework.

code:

package com.example.demo;

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class Pract7ApplicationTests {

@Test
void contextLoads() {
System.out.println("Hello World!");
}

output:

GURU NANAK INSTITUTE OF MANAGEMENT


Roll No:23MCA11 ADVANCED JAVA

PRACTICAL 7.2
Spring (Setter Method)

Aim: Write a program to demonstrate dependency injection via setter method.

code:

Student.java
package com.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
@Component
public class student {
private int rollno;
private String name;
private int marks;
@Autowired
@Qualifier("course1")
private course course;
public student() {
super();
System.out.println("obj created");
}
public course getC() {
return course;
}
public void setC(course course)
{ this.course = course;
}
public int getRollno() {
return rollno;
}
public void setRollno(int rollno)
{ this.rollno = rollno;
}
public String getName() {
return name;
}
public void setName(String name)
{ this.name = name;
}
public int getMarks() {
return marks;
}
public void setMarks(int marks)
{ this.marks = marks;
}
public void show() {
System.out.print("in show");
}

GURU NANAK INSTITUTE OF MANAGEMENT


Roll No:23MCA11 ADVANCED JAVA

public void compile() {


System.out.println("compiling from
student"); course.compile();
}
}

Course.java
package com.example.demo;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

@Component
@Qualifier("course1")
public class course {
private int courseid;
private String
coursename; public int
getCourseid() { return
courseid;
}
public void setCourseid(int courseid)
{ this.courseid = courseid;
}
public String getCoursename() {
return coursename;
}
public void setCoursename(String coursename)
{ this.coursename = coursename;
}
public void compile() {
System.out.println("compiling");
}

@Override
public String toString() {
return "course [courseid=" + courseid + ", coursename=" +

coursename + "]";
}
}

Application.java
package com.example.demo;

GURU NANAK INSTITUTE OF MANAGEMENT


Roll No:23MCA11 ADVANCED JAVA

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
ConfigurableApplicationContext
context=SpringApplication.run(Application.class, args);
//System.out.print("hello world");
student s= context.getBean(student.class);
s.show();
s.compile();
}
}

Output:

GURU NANAK INSTITUTE OF MANAGEMENT


Roll No:23MCA11 ADVANCED JAVA

PRACTICAL 7.3
Spring (Constructor)

Aim: Write a program to demonstrate dependency injection via Constructor.

code:

Student.java
package com.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
@Component
public class student {
private int rollno;
private String name;
private int marks;
@Autowired
@Qualifier("course1")
private course course;
public student() {
super();
System.out.println("obj created");
}
public course getC() {
return course;
}
public void setC(course course)
{ this.course = course;
}
public int getRollno() {
return rollno;
}
public void setRollno(int rollno)
{ this.rollno = rollno;
}
public String getName() {
return name;
}
public void setName(String name)
{ this.name = name;
}
public int getMarks() {
return marks;
}
public void setMarks(int marks)
{ this.marks = marks;
}
public void show() {
System.out.print("in show");
}

GURU NANAK INSTITUTE OF MANAGEMENT


Roll No:23MCA11 ADVANCED JAVA

public void compile() {


System.out.println("compiling from
student"); course.compile();
}
}

Course.java
package com.example.demo;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

@Component
@Qualifier("course1")
public class course {
private int courseid;
private String
coursename; public int
getCourseid() { return
courseid;
}
public void setCourseid(int courseid)
{ this.courseid = courseid;
}
public String getCoursename() {
return coursename;
}
public void setCoursename(String coursename)
{ this.coursename = coursename;
}
public void compile() {
System.out.println("compiling");
}

@Override
public String toString() {
return "course [courseid=" + courseid + ", coursename=" +

coursename + "]";
}
}

Application.java
package com.example.demo;

GURU NANAK INSTITUTE OF MANAGEMENT


Roll No:23MCA11 ADVANCED JAVA

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
ConfigurableApplicationContext
context=SpringApplication.run(Application.class, args);
//System.out.print("hello world");
student s= context.getBean(student.class);
s.show();
s.compile();
}
}

Output:

GURU NANAK INSTITUTE OF MANAGEMENT


Roll No:23MCA11 ADVANCED JAVA

PRACTICAL 8.1
Spring AOP(Before)

Aim: Write a program to demonstrate Spring AOP – before

advice code:

Application.java
package com.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import com.example.service.YourService;
@SpringBootApplication
public class YourApplication
{
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(YourApplication.class,
args);
YourService yourService = context.getBean(YourService.class);
yourService.yourmethod();
}
}

Service.java
package com.example.service;
import org.springframework.stereotype.Service;
@Service
public class YourService {
public void yourmethod()
{
System.out.println("Your method executed.");
}
}

Aspect.java
package com.example.aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class MyAspect {
@Before("execution(* com.example.service.YourService.yourmethod())")
public void beforeAdvice() {
System.out.println("Before advice executed.");
}
}
pom.xml:
<parent>
<!-- Your own application should inherit from spring-boot-starter-parent -->
GURU NANAK INSTITUTE OF MANAGEMENT
Roll No:23MCA11 ADVANCED JAVA

<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.0</version>
</parent>

output:

GURU NANAK INSTITUTE OF MANAGEMENT


Roll No:23MCA11 ADVANCED JAVA

PRACTICAL 8.2
Spring AOP(After)

Aim: Write a program to demonstrate Spring AOP – After

advice code:

Application.java
package com.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import com.example.service.YourService;
@SpringBootApplication
public class YourApplication
{
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(YourApplication.class,
args);
YourService yourService = context.getBean(YourService.class);
yourService.yourmethod();
}
}

Service.java
package com.example.service;
import org.springframework.stereotype.Service;
@Service
public class YourService {
public void yourmethod()
{
System.out.println("Your method executed.");
}
}

Aspect.java
package com.example.aspect;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class MyAspect {
@Before("execution(* com.example.service.YourService.yourmethod())")
public void beforeAdvice() {
System.out.println("After advice executed.");
}
}

pom.xml:
<parent>
GURU NANAK INSTITUTE OF MANAGEMENT
Roll No:23MCA11 ADVANCED JAVA

<!-- Your own application should inherit from spring-boot-starter-parent -->


<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.0</version>
</parent>

output:

GURU NANAK INSTITUTE OF MANAGEMENT


Roll No:23MCA11 ADVANCED JAVA

PRACTICAL 8.3
Spring AOP(Around)

Aim: Write a program to demonstrate Spring AOP –Around

advice code:

Application.java
package com.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import com.example.service.YourService;
@SpringBootApplication
public class YourApplication
{
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(YourApplication.class,
args);
YourService yourService = context.getBean(YourService.class);
yourService.yourmethod();
}
}

yourservice.java
package com.example.service;
import org.springframework.stereotype.Service;
@Service
public class YourService {
public void yourmethod()
{
System.out.println("Your method executed.");
}
}

myaspect.java
package com.example.aspect;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class MyAspect {
@Around("execution(* com.example.service.YourService.yourmethod())")
public void aspect(ProceedingJoinPoint joinPoint) {
try {
System.out.println("Before Advice");
joinPoint.proceed();
System.out.println("After Advice");
} catch (Throwable e) {
System.err.println("Exception in advice: " + e.getMessage());
}

GURU NANAK INSTITUTE OF MANAGEMENT


Roll No:23MCA11 ADVANCED JAVA

}
}

pom.xml:
<parent>
<!-- Your own application should inherit from spring-boot-starter-parent -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.0</version>
</parent>

output:

GURU NANAK INSTITUTE OF MANAGEMENT


Roll No:23MCA11 ADVANCED JAVA

PRACTICAL 8.4
Spring AOP(AfterReturning)

Aim: Write a program to demonstrate Spring AOP – AfterReturning

advice code:
yourapplication.java:
package com.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import com.example.service.YourService;
@SpringBootApplication
public class YourApplication
{
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(YourApplication.class,
args);
YourService yourService = context.getBean(YourService.class);
yourService.yourmethod();
}
}

yourservice.java
package com.example.service;
import org.springframework.stereotype.Service;
@Service
public class YourService {
public void yourmethod()
{
System.out.println("Your method executed.");
}
}
myaspect.java
package com.example.aspect;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class MyAspect {
@AfterReturning(pointcut = "execution(* com.example.service.YourService.yourmethod())",
returning = "result")
public void afterReturningAdvice() {
System.out.println("After Returning Advice: Aspect executed after yourmethod()returns");
}
}

GURU NANAK INSTITUTE OF MANAGEMENT


Roll No:23MCA11 ADVANCED JAVA

output:

GURU NANAK INSTITUTE OF MANAGEMENT


Roll No:23MCA11 ADVANCED JAVA

PRACTICAL 8.5
Spring AOP(AfterThrowing)

Aim: Write a program to demonstrate Spring AOP – AfterThrowing

advice code:

Myaspect.java
package com.example.aspect;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import
org.springframework.stereotype.Component;
@Aspect
@Component
public class myaspect {
@AfterThrowing(
pointcut = "execution(* com.example.service.serv1.service2())",throwing= "exception")
public void afterThrowingAdvice(Exception exception) {
System.out.println("After Throwing Advice: Exception caught - " +
exception.getMessage());
}
}

Serv1.java

package com.example.service;
import org.springframework.stereotype.Service;
@Service
public class serv1 {
public void service2() {
// System.out.println(“my method”);
throw new RuntimeException("Simulated exception in myMethod");
}
}

Application.java

package com.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import com.example.service.serv1;
@SpringBootApplication
public class application {
public static void main(String[] args)
{ ConfigurableApplicationContext

GURU NANAK INSTITUTE OF MANAGEMENT


Roll No:23MCA11 ADVANCED JAVA

context=SpringApplication.run(application.class, args);
serv1 mservice=context.getBean(serv1.class);
try {
mservice.service2();
}catch(Exception e) {
}
}
}

Pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.0</version>
</parent>

Output:

GURU NANAK INSTITUTE OF MANAGEMENT


Roll No:23MCA11 ADVANCED JAVA

PRACTICAL 8.6
Spring AOP( pointcut

) Aim: Write a program to demonstrate Spring AOP –

pointcuts code:

serv1.java
package com.example.service;
import org.springframework.stereotype.Service;
@Service
public class serv1 {
public void method1() {
System.out.println("Executing method1");
}
public void method2() {
System.out.println("Executing method2");
}
}

MYASPECT.java
package com.example.aspect;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import
org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class myaspect {
@Pointcut("execution(* com.example.service.serv1.method1())")
public void pointcutMethod1() {
}
@Pointcut("execution(* com.example.service.serv1.method2())")

public void pointcutMethod2() {


}
@Before("pointcutMethod1()")
public void beforeMethod1() {
System.out.println("Before advice for method1");
}
@Before("pointcutMethod2()")
public void beforeMethod2() {
System.out.println("Before advice for method2");
}
}

GURU NANAK INSTITUTE OF MANAGEMENT


Roll No:23MCA11 ADVANCED JAVA

Application.java
package com.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import com.example.service.serv1;
@SpringBootApplication
public class application {
public static void main(String[] args) {
ConfigurableApplicationContext
context=SpringApplication.run(application.class, args);
serv1 mservice=context.getBean(serv1.class);
mservice.method1();
mservice.method2();
}
}
Pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.0</version>
</parent>

Output:

GURU NANAK INSTITUTE OF MANAGEMENT


Roll No:23MCA11 ADVANCED JAVA

PRACTICAL 10.1
Spring Web Services( SpringBoot )

Aim: Write a program to create a simple Spring Boot application that prints a message.

code:

package com.example.demo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class prac10 {
@GetMapping("/prac10")
public String prac10()
{
return "Practical 10.1: Atharva Chakote";
}
}

output:

GURU NANAK INSTITUTE OF MANAGEMENT


Roll No:23MCA11 ADVANCED JAVA

PRACTICAL 10.2
Spring Web Services( restfull )

Aim: Write a program to create a simple Spring Boot application that prints a message.

code:

helloworldbean.java
package com.example.demo;
public class helloworldbean {
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public String toString() {
return "helloworldbean [message=" + message + ", getMessage()=" + getMessage() +
"]";
}
public helloworldbean(String message) {
super();
this.message = message;
}
}

controller.java
package com.example.demo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class controller {
@GetMapping(path="/hello-world")
public String helloWorld() {
return "hey Atharva";
}
@GetMapping
(path="/hello-world-bean")
public helloworldbean helloWorldBean() {
return new helloworldbean("hey Atharva");
}
}

output:

GURU NANAK INSTITUTE OF MANAGEMENT


Roll No:23MCA11 ADVANCED JAVA

GURU NANAK INSTITUTE OF MANAGEMENT

You might also like