Advanced Java Lab - Complete

Download as pdf or txt
Download as pdf or txt
You are on page 1of 101

‭Program 1‬

‭Aim:‬‭Write a Java program to demonstrate the concept‬‭of socket programming.‬

‭Theory:‬

‭Java Socket Programming‬

J‭ ava‬ ‭Socket‬ ‭programming‬ ‭is‬ ‭used‬ ‭for‬ ‭communication‬ ‭between‬ ‭the‬ ‭applications‬
‭running‬ ‭on‬ ‭different‬ ‭JRE.‬ ‭Java‬ ‭Socket‬ ‭programming‬ ‭can‬ ‭be‬‭connection-oriented‬‭or‬
‭connection-less.‬

‭ ocket‬ ‭and‬ ‭ServerSocket‬ ‭classes‬ ‭are‬ ‭used‬ ‭for‬ ‭connection-oriented‬ ‭socket‬


S
‭programming‬ ‭and‬ ‭DatagramSocket‬ ‭and‬ ‭DatagramPacket‬ ‭classes‬ ‭are‬ ‭used‬ ‭for‬
‭connection-less socket programming.‬

‭The client in socket programming must know two information:‬


‭1.‬ ‭IP Address of Server, and‬
‭2.‬ ‭Port number.‬

‭ ere,‬ ‭we‬ ‭are‬ ‭going‬ ‭to‬ ‭make‬ ‭one-way‬ ‭client‬ ‭and‬ ‭server‬ ‭communication.‬ ‭In‬ ‭this‬
H
‭application,‬ ‭client‬ ‭sends‬ ‭a‬ ‭message‬ ‭to‬ ‭the‬ ‭server,‬ ‭server‬ ‭reads‬ ‭the‬ ‭message‬ ‭and‬
‭prints‬ ‭it.‬ ‭Here,‬ ‭two‬ ‭classes‬ ‭are‬ ‭being‬ ‭used:‬ ‭Socket‬ ‭and‬ ‭ServerSocket.‬ ‭The‬ ‭Socket‬
‭class‬‭is‬‭used‬‭to‬‭communicate‬‭client‬‭and‬‭server.‬‭Through‬‭this‬‭class,‬‭we‬‭can‬‭read‬‭and‬
‭write‬‭message.‬‭The‬‭ServerSocket‬‭class‬‭is‬‭used‬‭at‬‭server-side.‬‭The‬‭accept()‬‭method‬
‭of‬ ‭ServerSocket‬ ‭class‬ ‭blocks‬ ‭the‬ ‭console‬ ‭until‬ ‭the‬ ‭client‬ ‭is‬ ‭connected.‬ ‭After‬ ‭the‬
‭successful connection of client, it returns the instance of Socket at server-side.‬
‭Code:‬

i‭mport java.io.*;‬
‭import java.net.*;‬

‭ ublic class SocketProgrammingDemo‬


p
‭{ public static void main(String[] args)‬
‭{ // Server‬
‭Thread serverThread = new Thread(() ->‬

‭{ try‬
‭{ // Create server socket‬
‭ServerSocket serverSocket = new ServerSocket(12345);‬

/‭/ Wait for client connection‬


‭System.out.println("Server waiting for client...");‬
‭Socket clientSocket = serverSocket.accept();‬
‭System.out.println("Client connected.");‬

‭// Create input and output streams‬


‭BufferedReader‬ ‭in‬ ‭=‬ ‭new‬ ‭BufferedReader(new‬
‭InputStreamReader(clientSocket.getInputStream()));‬
‭PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);‬

/‭/ Read message from client‬


‭String message = in.readLine();‬
‭System.out.println("Client: " + message);‬

/‭/ Send response to client‬


‭out.println("Hello from server!");‬

/‭/ Close streams and sockets‬


‭in.close();‬
‭out.close();‬
‭clientSocket.close();‬
‭serverSocket.close();‬
}‭ ‬
‭catch (IOException e)‬
‭{ e.printStackTrace();‬
‭}‬
‭});‬
‭// Client‬
‭Thread clientThread = new Thread(() ->‬
‭{ try‬
‭{ // Create client socket‬
‭Socket socket = new Socket("localhost", 12345);‬

‭// Create input and output streams‬


‭BufferedReader‬ ‭in‬ ‭=‬ ‭new‬ ‭BufferedReader(new‬
‭InputStreamReader(socket.getInputStream()));‬
‭PrintWriter out = new PrintWriter(socket.getOutputStream(), true);‬

/‭/ Send message to server‬


‭out.println("Hello from client!");‬

/‭/ Read response from server‬


‭String response = in.readLine();‬
‭System.out.println("Server: " + response);‬

/‭/ Close streams and socket‬


‭in.close();‬
‭out.close();‬
‭socket.close();‬

}‭ ‬
‭catch (IOException e)‬
{‭ e.printStackTrace();‬
‭}‬
‭});‬
‭// Start server and client threads‬
‭serverThread.start();‬
‭clientThread.start();‬
‭}‬
‭}‬

‭Output:‬
‭Program 2‬

‭Aim:‬‭Write a Java program to demonstrate the concept‬‭of applet programming.‬

‭Theory:‬

‭Java Applet‬

‭ pplet‬‭is‬‭a‬‭special‬‭program‬‭embedded‬‭in‬‭the‬‭webpage‬‭to‬‭generate‬‭dynamic‬‭content.‬
A
‭It runs inside the browser and works on the client side.‬

‭Advantages of Applet‬

‭There are many advantages of applet. They are as follows:‬

‭ ‬ I‭t works on the client side so less response time.‬



‭●‬ ‭Secured‬
‭●‬ ‭It‬ ‭can‬ ‭be‬ ‭executed‬ ‭by‬ ‭browsers‬ ‭running‬ ‭under‬ ‭many‬ ‭platforms,‬ ‭including‬
‭Linux, Windows, Mac OS etc.‬

‭The drawback of Applet‬

‭●‬ ‭Plugin is required at the client browser to execute the applet.‬

‭Lifecycle of Java Applet‬

‭‬
● ‭ pplet is initialised.‬
A
‭●‬ ‭Applet is started.‬
‭●‬ ‭Applet is painted.‬
‭●‬ ‭Applet is stopped.‬
‭●‬ ‭Applet is destroyed.‬
‭Code:‬

i‭mport java.awt.*;‬
‭import java.applet.*;‬
‭public class MyApplet extends Applet {‬
‭public void paint(Graphics g) {‬
‭g.drawString("A simple Applet", 20, 20);‬
‭}‬
‭}‬

‭Output:‬
‭Program 3‬

‭Aim:‬‭Write a Java program to demonstrate the concept‬‭of multithreading.‬

‭Theory:‬

‭Thread‬

‭ ‬‭thread‬‭is‬‭a‬‭lightweight‬‭subprocess,‬‭the‬‭smallest‬‭unit‬‭of‬‭processing.‬‭It‬‭is‬‭a‬‭separate‬
A
‭path of execution.‬

‭ hreads‬‭are‬‭independent.‬‭If‬‭there‬‭occurs‬‭an‬‭exception‬‭in‬‭one‬‭thread,‬‭it‬‭doesn't‬‭affect‬
T
‭other threads. It uses a shared memory area.‬

‭Multithreading in Java‬

‭ ultithreading‬ ‭in‬ ‭Java‬ ‭is‬ ‭a‬ ‭process‬ ‭of‬ ‭executing‬ ‭multiple‬‭threads‬‭simultaneously.‬‭A‬


M
‭thread‬ ‭is‬‭a‬‭lightweight‬‭sub-process,‬‭the‬‭smallest‬‭unit‬‭of‬‭processing.‬‭Multiprocessing‬
‭and multithreading, both are used to achieve multitasking.‬

‭ owever,‬ ‭we‬‭use‬‭multithreading‬‭rather‬‭than‬‭multiprocessing‬‭because‬‭threads‬‭use‬‭a‬
H
‭shared‬ ‭memory‬‭area.‬‭They‬‭don't‬‭allocate‬‭separate‬‭memory‬‭areas‬‭so‬‭save‬‭memory,‬
‭and context-switching between the threads takes less time than the process.‬

‭Java Multithreading is mostly used in games, animation, etc.‬

‭Advantages of Java Multithreading‬

‭ )‬ ‭It‬ ‭doesn't‬ ‭block‬ ‭the‬ ‭user‬ ‭because‬ ‭threads‬‭are‬‭independent‬‭and‬‭you‬‭can‬‭perform‬


1
‭multiple operations at the same time.‬

‭2) You can perform many operations together, so it saves time.‬

‭ )‬‭Threads‬‭are‬‭independent,‬‭so‬‭it‬‭doesn't‬‭affect‬‭other‬‭threads‬‭if‬‭an‬‭exception‬‭occurs‬
3
‭in a single thread.‬
‭Code:‬

‭public class PrintNumberThread extends Thread {‬

‭private int number;‬

‭public PrintNumberThread(int number) {‬


‭this.number = number;‬
‭}‬

‭ Override‬
@
‭public void run() {‬
‭System.out.println("Printing from Thread " + getName() + ": " + number);‬
‭}‬

‭public static void main(String[] args) {‬


‭PrintNumberThread thread1 = new PrintNumberThread(1);‬
‭PrintNumberThread thread2 = new PrintNumberThread(2);‬

t‭hread1.start();‬
‭thread2.start();‬
‭}‬
‭}‬

‭Output:‬
‭Program 4‬

‭Aim:‬‭Write a Java program to demonstrate the concept‬‭of applet.‬

‭Theory:‬

‭ n applet is a Java program that can be embedded into a web page. It runs inside‬
A
‭the web browser and works at client side. An applet is embedded in an HTML page‬
‭using the APPLET or OBJECT tag and hosted on a web server.‬
‭Applets are used to make the website more dynamic and entertaining.‬

‭Important points:‬

‭1.‬ A ‭ ll applets are sub-classes (either directly or indirectly) of java.applet.Applet‬


‭class.‬
‭2.‬ ‭Applets are not stand-alone programs. Instead, they run within either a web‬
‭browser or an applet viewer. JDK provides a standard applet viewer tool‬
‭called applet viewer.‬
‭3.‬ ‭In general, execution of an applet does not begin at main() method.‬
‭4.‬ ‭Output of an applet window is not performed by System.out.println(). Rather it‬
‭is handled with various AWT methods, such as drawString().‬

‭Life cycle of an applet :‬


‭Code:‬

i‭mport java.applet.*;‬
‭import java.awt.*;‬
‭public class MyApplet extends Applet {‬
‭int height, width;‬
‭public void init() {‬
‭height = getSize().height;‬
‭width = getSize().width;‬
‭setName("MyApplet");‬
‭}‬
‭public void paint(Graphics g) {‬
‭g.drawRoundRect(10, 30, 120, 120, 2, 3);‬
‭}‬
‭}‬

‭Output:‬
‭Program 5‬

‭Aim:‬‭Write a Java program to demonstrate the use of‬‭Java Beans‬

‭Theory:‬

‭JavaBean‬

‭A JavaBean is a Java class that should follow the following conventions:‬

‭ ‬ I‭t should have a no-arg constructor.‬



‭●‬ ‭It should be Serializable.‬
‭●‬ ‭It‬ s‭ hould‬ ‭provide‬ ‭methods‬‭to‬‭set‬‭and‬‭get‬‭the‬‭values‬‭of‬‭the‬‭properties,‬‭known‬
‭as getter and setter methods.‬

‭Why use JavaBean?‬

‭ ccording‬ ‭to‬ ‭Java‬ ‭white‬ ‭paper,‬ ‭it‬ ‭is‬ ‭a‬ ‭reusable‬ ‭software‬ ‭component.‬ ‭A‬ ‭bean‬
A
‭encapsulates‬ ‭many‬ ‭objects‬ ‭into‬ ‭one‬ ‭object‬ ‭so‬ ‭that‬ ‭we‬ ‭can‬ ‭access‬ ‭this‬ ‭object‬‭from‬
‭multiple places. Moreover, it provides easy maintenance.‬

‭Advantages of JavaBean‬

‭The following are the advantages of JavaBean:‬

‭●‬ T ‭ he‬ ‭JavaBean‬ ‭properties‬ ‭and‬ ‭methods‬ ‭can‬ ‭be‬ ‭exposed‬ ‭to‬ ‭another‬
‭application.‬
‭●‬ ‭It provides an easiness to reuse the software components.‬

‭Disadvantages of JavaBean‬

‭The following are the disadvantages of JavaBean:‬

‭ ‬ J‭ avaBeans are mutable. So, it can't take advantages of immutable objects.‬



‭●‬ ‭Creating‬ ‭the‬ ‭setter‬ ‭and‬‭getter‬‭method‬‭for‬‭each‬‭property‬‭separately‬‭may‬‭lead‬
‭to the boilerplate code.‬
‭Code:‬

‭public class JavaBeanDemo {‬

‭ rivate String name;‬


p
‭private int age;‬

/‭/ Default constructor (no arguments)‬


‭public JavaBeanDemo() {‬
‭}‬

/‭/ Constructor with arguments‬


‭public JavaBeanDemo(String name, int age) {‬
‭this.name = name;‬
‭this.age = age;‬
‭}‬

/‭/ Getter and setter methods for name‬


‭public String getName() {‬
‭return name;‬
‭}‬

‭public void setName(String name) {‬


‭this.name = name;‬
‭}‬

/‭/ Getter and setter methods for age‬


‭public int getAge() {‬
‭return age;‬
‭}‬

‭public void setAge(int age) {‬


‭this.age = age;‬
‭}‬

‭ Override‬
@
‭public String toString() {‬
‭return "Name: " + name + ", Age: " + age;‬
‭}‬

‭public static void main(String[] args) {‬


‭// Create a JavaBeanDemo object using the default constructor‬
‭JavaBeanDemo person1 = new JavaBeanDemo();‬
/‭/ Set the name and age using setter methods‬
‭person1.setName("Aman Gupta");‬
‭person1.setAge(20);‬

/‭/ Create a JavaBeanDemo object using the constructor with arguments‬


‭JavaBeanDemo person2 = new JavaBeanDemo("Anupam Mittal", 25);‬

/‭/ Print the information using toString() method‬


‭System.out.println(person1);‬
‭System.out.println(person2);‬
‭}‬
‭}‬

‭Output:‬
‭Program 6‬

‭Aim:‬‭Write a Java program to insert data into a table‬‭using JSP.‬

‭Theory:‬

‭ ata‬‭insertion‬‭into‬‭a‬‭table‬‭using‬‭JSP‬‭enables‬‭developers‬‭to‬‭dynamically‬‭add‬‭records‬
D
‭to a database table based on user input or predefined data.‬

‭Front-End Design:‬

‭1.‬ H ‭ TML‬ ‭Form:‬ ‭The‬ ‭JSP‬ ‭page‬ ‭contains‬ ‭an‬ ‭HTML‬ ‭form‬ ‭with‬ ‭input‬ ‭fields‬ ‭for‬
‭collecting data to be inserted into the table.‬
‭2.‬ ‭Submit‬‭Button:‬‭Users‬‭trigger‬‭the‬‭data‬‭insertion‬‭process‬‭by‬‭clicking‬‭a‬‭submit‬
‭button within the form.‬

‭Data Insertion Logic in JSP:‬

‭1.‬ R ‭ equest‬ ‭Handling:‬ ‭The‬ ‭JSP‬ ‭page‬ ‭retrieves‬ ‭form‬ ‭parameters‬ ‭using‬ ‭the‬
‭request.getParameter() method.‬
‭2.‬ ‭Database‬ ‭Connection:‬ ‭JSP‬ ‭establishes‬ ‭a‬‭connection‬‭to‬‭the‬‭database‬‭using‬
‭JDBC.‬
‭3.‬ ‭SQL‬ ‭Execution:‬ ‭JSP‬ ‭executes‬ ‭an‬ ‭SQL‬ ‭INSERT‬ ‭query‬ ‭to‬ ‭add‬ ‭data‬ ‭into‬ ‭the‬
‭table.‬
‭4.‬ ‭Parameter‬‭Binding:‬‭Parameters‬‭are‬‭bound‬‭to‬‭the‬‭SQL‬‭query‬‭to‬‭prevent‬‭SQL‬
‭injection attacks.‬
‭5.‬ ‭Error‬ ‭Handling:‬ ‭Exception‬ ‭handling‬ ‭mechanisms‬ ‭are‬ ‭implemented‬ ‭to‬
‭manage errors during the insertion process.‬
‭Code:‬

‭SQL QUERY:‬

‭ REATE‬
C
‭TABLE users(‬
‭id int NOT NULL AUTO_INCREMENT,‬
‭first_name‬
‭varchar(50),‬
‭last_name‬
‭varchar(50),‬
‭city_name‬
‭varchar(50),‬
‭email‬
‭varchar(50),‬
‭PRIMARY‬
‭KEY(id)‬
‭);‬
‭index.html:‬
‭< !DOCTYPE html >‬
‭<html>‬
‭<body>‬
‭<form method="post" action="process.jsp">‬
‭First name: <input type="text" name="first_name">‬
‭<br><br>‬
‭Last name: <input type="text" name="last_name">‬
‭<br><br>‬
‭City name: <input type="text" name="city_name">‬
‭<br><br>‬
‭Email Id: <input type="email" name="email">‬
‭<br><br>‬
‭<input type="submit" value="submit">‬
‭</form>‬
‭</body>‬
‭</html>‬
‭process.jsp:‬
‭<%@‬ ‭page‬ ‭language="java"‬ ‭contentType="text/html";‬
‭charset=ISO-8859-1" pageEncoding="ISO8859-1"%>‬
‭<%@page import="java.sql.*,java.util.*"%>‬
‭<%‬
‭String‬
‭first_name=request.getParameter("first_name‬
‭"); String‬
‭last_name=request.getParameter("last_name"‬
)‭ ; String‬
‭city_name=request.getParameter("city_name"‬
‭); String‬
‭email=request.getParameter("email");‬
‭try {‬
‭Class.forName("com.mysql.jdbc.Driver");‬
‭ onnection‬ ‭conn‬ ‭=‬
C
‭DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root",‬
‭""); Statement st=conn.createStatement();‬
‭int i=st.executeUpdate("insert into‬

‭ sers(first_name,last_name,city_name,email)values('"+first_name+"','"+last_name+"'‬
u
‭,'"+city_name+"','"‬
‭+ema il+"')");‬
‭out.println("Data is successfully inserted!");‬
‭}‬
‭catch(Exception e) {‬
‭System.out.print(e);‬
‭e.printStackTrace();‬
‭}‬
‭%‬
‭>‬

‭Output:‬
‭Program 7‬

‭Aim:‬‭Write JSP program to implement form data validation.‬

‭Theory:‬

‭ orm‬ ‭data‬ ‭validation‬ ‭in‬ ‭JSP‬ ‭ensures‬ ‭that‬ ‭user‬ ‭input‬‭meets‬‭specified‬‭criteria‬‭before‬


F
‭submission, enhancing data integrity and security in web applications.‬

‭Front-End Design:‬

‭ .‬ H
1 ‭ TML Form:‬‭The JSP page contains an HTML form that‬‭collects user input.‬
‭2.‬ ‭Validation‬‭Rules:‬‭Input‬‭fields‬‭are‬‭accompanied‬‭by‬‭validation‬‭rules‬‭specifying‬
‭required formats, lengths, or data types.‬

‭Validation Logic in JSP:‬

‭1.‬ C ‭ lient-Side‬ ‭Validation:‬ ‭JavaScript‬ ‭or‬ ‭HTML5‬ ‭validation‬ ‭may‬ ‭be‬ ‭used‬ ‭for‬
‭immediate feedback on invalid inputs.‬
‭2.‬ ‭Server-Side‬ ‭Validation:‬ ‭JSP‬ ‭code‬ ‭validates‬ ‭user‬ ‭input‬ ‭upon‬ ‭form‬
‭submission.‬
‭3.‬ ‭Retrieving‬ ‭Parameters:‬ ‭JSP‬ ‭retrieves‬ ‭form‬ ‭parameters‬ ‭using‬ ‭the‬
‭request.getParameter() method.‬
‭4.‬ ‭Validation‬ ‭Checks:‬ ‭JSP‬ ‭code‬ ‭checks‬ ‭each‬ ‭parameter‬ ‭against‬ ‭predefined‬
‭validation rules or patterns.‬
‭5.‬ ‭Error‬ ‭Handling:‬ ‭If‬ ‭validation‬ ‭fails,‬ ‭error‬ ‭messages‬ ‭are‬ ‭generated‬ ‭and‬
‭displayed to prompt users to correct their input.‬
‭Code:‬

‭Form to accept username and password: login.jsp‬

‭ % @page contentType = "text/html" pageEncoding = "UTF-8" %>‬


<
‭< !DOCTYPE html >‬
‭<html>‬
‭<head>‬
‭<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">‬
‭<title>Login Page</title>‬
‭</head>‬
‭<body>‬
‭<h1>User Details</h1>‬
‭<form method="get" action="acceptuser.jsp">‬
‭Enter Username : <input type="text" name="user"><br /><br />‬
‭Enter Password : <input type="password" name="pass"><br />‬
‭<input type="submit" value="SUBMIT">‬
‭</html>‬

‭JSP to accept form data and verify a user: acceptuser.jsp‬

‭ % @page contentType = "text/html" pageEncoding = "UTF-8" %>‬


<
‭< !DOCTYPE html >‬
‭<html>‬
‭<head>‬
‭<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">‬
‭<title>Accept User Page</title>‬
‭</head>‬
‭<body>‬
‭<h1>Verifying Details</h1>‬
‭<jsp:useBean id="snr" class="Kshitiz.ValidateUser" />‬
‭<jsp:setProperty name="snr" property="user" />‬
‭<jsp:setProperty name="snr" property="pass" />‬
‭The Details Entered Are as Under<br />‬
‭<p>Username : <jsp:getProperty name="snr" property="user" /></p>‬
‭<p>Password : <jsp:getProperty name="snr" property="pass" /></p>‬
‭<%if(snr.validate(“Kshitiz_Sharma", “Kxx6969")){%>‬
‭Welcome! You are a VALID USER<br />‬
‭<%}else{%>‬
‭Error! You are an INVALID USER<br />‬
‭<%}%>‬
‭</body>‬
‭</html>‬
‭ he validateUser.java class‬
T
‭package Kshitiz;‬
‭import java.io.Serializable;‬
‭public class ValidateUser implements Serializable {‬
‭private String user, pass;‬
‭public void setUser(String u1) { this.user = u1; }‬
‭public void setPass(String p1) { this.pass = p1; }‬
‭public String getUser() { return user; }‬
‭public String getPass() { return pass; }‬
‭public boolean validate(String u1, String p1) {‬
‭if (u1.equals(user) && p1.equals(pass))‬
‭return true;‬
‭else‬
‭return false;‬
‭}‬
‭}‬

‭Output:‬
‭Program 8‬

‭Aim:‬‭Write a Java program to show user validation‬‭using Servlet.‬

‭Theory:‬

‭ ser‬‭validation‬‭is‬‭crucial‬‭in‬‭web‬‭applications‬‭to‬‭ensure‬‭that‬‭only‬‭authorized‬‭users‬‭can‬
U
‭access‬ ‭protected‬ ‭resources.‬ ‭Servlets‬ ‭provide‬ ‭a‬ ‭server-side‬ ‭mechanism‬ ‭for‬
‭implementing user validation logic.‬

‭Servlet Initialization:‬

‭1.‬ S ‭ ervlet‬ ‭Class:‬ ‭The‬ ‭program‬ ‭defines‬ ‭a‬ ‭servlet‬ ‭class‬ ‭that‬ ‭extends‬ ‭the‬
‭javax.servlet.http.HttpServlet class.‬
‭2.‬ ‭Initialization:‬‭The‬‭init()‬‭method‬‭of‬‭the‬‭HttpServlet‬‭class‬‭initializes‬‭the‬‭servlet,‬
‭setting up any necessary resources or parameters.‬

‭User Validation Logic:‬

‭1.‬ R ‭ equest‬ ‭Handling:‬ ‭The‬ ‭servlet‬‭overrides‬‭the‬‭doGet()‬‭or‬‭doPost()‬‭method‬‭to‬


‭handle HTTP requests.‬
‭2.‬ ‭Parameter‬ ‭Retrieval:‬ ‭The‬ ‭servlet‬ ‭retrieves‬ ‭user‬ ‭input‬ ‭parameters‬ ‭from‬ ‭the‬
‭HTTP request, such as username and password.‬
‭3.‬ ‭Validation:‬ ‭The‬ ‭servlet‬ ‭validates‬ ‭the‬ ‭user‬ ‭input‬ ‭against‬ ‭stored‬ ‭credentials‬
‭(e.g., in a database) or predefined rules.‬
‭4.‬ ‭Response‬ ‭Generation:‬ ‭Depending‬ ‭on‬ ‭the‬ ‭validation‬ ‭result,‬ ‭the‬ ‭servlet‬
‭generates‬‭an‬‭appropriate‬‭response,‬‭such‬‭as‬‭granting‬‭access‬‭or‬‭displaying‬‭an‬
‭error message.‬
‭Code:‬

‭login.jsp:‬

‭ % @page language = "java" contentType = "text/html" pageEncoding = "UTF-8" %>‬


<
‭< !DOCTYPE html >‬
‭<html lang="en">‬
‭<head>‬
‭<meta charset="UTF-8" />‬
‭<meta name="viewport" content="width=device-width, initial-scale=1.0" />‬
‭<title>BackEnd</title>‬
‭</head>‬
‭<body>‬
‭<h1>User Details</h1>‬
‭<form action="/loginServlet" method="post"‬
‭onclick="ValidateEmail(document.getElementById('emailId'))">‬
‭<div class="container">‬
‭<label for="username"><b>Email</b></label>‬
‭<input‬ ‭type="text"‬ ‭placeholder="Please‬ ‭enter‬ ‭your‬ ‭email"‬ ‭name="emailId"‬
‭id="emailId" required />‬
‭<br /><br />‬
‭<label for="password"><b>Password</b></label>‬
‭<input‬ ‭type="password"‬ ‭placeholder="Please‬ ‭enter‬ ‭Password"‬
‭name="password" id="password"‬
‭required />‬
‭<br /><br />‬
‭<button type="submit">Login</button>‬
‭</div>‬
‭</form>‬
‭<script type="text/javascript">‬
‭function ValidateEmail(emailId) {‬
‭var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2, 3})+$/;‬
‭if (emailId.value.match(mailformat)) {‬
‭document.getElementById("password").focus();‬
‭return true;‬
‭} else {‬
‭alert("You have entered an invalid email address!");‬
‭document.getElementById("emailId").focus();‬
‭return false;‬
‭}‬
‭}‬
‭</script>‬
‭</body>‬
‭</html>‬
‭LoginServer.java:‬

i‭mport java.io.IOException;‬
‭import javax.servlet.ServletException;‬
‭import javax.servlet.annotation.WebServlet;‬
‭import javax.servlet.http.HttpServlet;‬
‭import javax.servlet.http.HttpServletRequest;‬
‭import javax.servlet.http.HttpServletResponse;‬
‭import javax.servlet.http.HttpSession;‬
‭@WebServlet("/loginServlet")‬
‭public class LoginServlet extends HttpServlet {‬
‭private static final long serialVersionUID = 1L;‬
‭public LoginServlet() {‬
‭super();‬
‭}‬
‭protected void doPost(HttpServletRequest request, HttpServletResponse response)‬
‭throws ServletException, IOException {‬
‭String emailId = request.getParameter("emailId");‬
‭String password = request.getParameter("password");‬
‭System.out.println("emailId.." + emailId);‬
‭System.out.println("password.." + password);‬
‭if‬‭(emailId‬‭!=‬‭null‬‭&&‬‭emailId.equalsIgnoreCase("[email protected]")‬‭&&‬‭password‬
‭!=‬
‭null && password.equalsIgnoreCase("Kxx6969")) {‬
‭HttpSession httpSession = request.getSession();‬
‭httpSession.setAttribute("emailId", emailId);‬
‭request.getRequestDispatcher("welcome.jsp").forward(request, response);‬
‭}‬
‭}‬
‭}‬

‭welcome.jsp:‬

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


<
‭pageEncoding = "ISO-8859-1" %>‬
‭<html>‬
‭<head>‬
‭</head>‬
‭<body>‬
‭Welcome <%=session.getAttribute("emailId") %>‬
‭</body>‬
‭</html>‬
‭Output:‬

‭Login view:‬

‭Client-side validation output:‬


‭Program 9‬

‭Aim:‬‭Write a program to set cookie information using‬‭Servlet.‬

‭Theory:‬

‭Introduction to Servlet Cookie Setting:‬

‭●‬ S‭ ervlets‬ ‭facilitate‬ ‭server-side‬ ‭processing‬ ‭of‬ ‭HTTP‬ ‭requests,‬ ‭including‬


‭managing‬ ‭cookies,‬ ‭small‬ ‭pieces‬ ‭of‬ ‭data‬ ‭sent‬ ‭by‬ ‭the‬ ‭server‬ ‭to‬ ‭the‬ ‭client's‬
‭browser for various purposes.‬

‭Purpose of Cookie Setting:‬

‭●‬ T‭ he‬‭program‬‭aims‬‭to‬‭demonstrate‬‭how‬‭servlets‬‭can‬‭set‬‭cookie‬‭information‬‭to‬
‭be stored on the client-side browser.‬

‭Steps in Cookie Setting:‬

‭1.‬ I‭nitialization:‬ ‭The‬ ‭servlet‬ ‭initializes‬ ‭by‬ ‭extending‬ ‭the‬ ‭HttpServlet‬ ‭class‬ ‭and‬
‭overriding the doGet() or doPost() method.‬
‭2.‬ ‭Creating‬ ‭Cookies:‬ ‭Within‬ ‭the‬ ‭servlet,‬ ‭cookies‬ ‭are‬ ‭created‬‭using‬‭the‬‭Cookie‬
‭class, specifying the name and value of the cookie.‬
‭3.‬ ‭Setting‬ ‭Cookie‬ ‭Attributes:‬ ‭Attributes‬ ‭such‬ ‭as‬ ‭expiration‬ ‭time,‬ ‭path,‬ ‭and‬
‭domain for the cookie are optionally set to control its behavior.‬
‭4.‬ ‭Adding‬ ‭Cookies‬ ‭to‬ ‭Response:‬ ‭The‬ ‭cookies‬ ‭are‬ ‭added‬ ‭to‬ ‭the‬
‭HttpServletResponse object using the addCookie() method.‬
‭5.‬ ‭Sending‬ ‭Cookies‬ ‭to‬ ‭Client:‬ ‭When‬ ‭the‬ ‭servlet‬ ‭response‬ ‭is‬ ‭sent‬‭back‬‭to‬‭the‬
‭client, the cookies are included in the HTTP response headers.‬
‭6.‬ ‭Client-Side‬ ‭Storage:‬ ‭The‬ ‭client's‬ ‭browser‬ ‭stores‬ ‭the‬ ‭cookies,‬ ‭making‬ ‭them‬
‭available for subsequent requests to the server.‬
‭Code:‬

i‭mport java.io.IOException;‬
‭import jakarta.servlet.ServletException;‬
‭import jakarta.servlet.annotation.WebServlet;‬
‭import jakarta.servlet.http.*;‬
‭@WebServlet("/setCookie")‬
‭public class SetCookieServlet extends HttpServlet {‬
‭@Override‬
‭protected‬‭void‬‭doGet(HttpServletRequest‬‭request,‬‭HttpServletResponse‬‭response)‬
‭throws ServletException,‬
‭IOException {‬
‭String cookieName = "userPref";‬
‭String cookieValue = "darkMode";‬
‭int maxAge = 60 * 60 * 24;‬
‭Cookie cookie = new Cookie(cookieName, cookieValue);‬
‭cookie.setMaxAge(maxAge);‬
‭response.addCookie(cookie);‬
‭response.setContentType("text/plain");‬
‭response.getWriter().println("Cookie set successfully!");‬
‭}‬
‭}‬

‭Output:‬
‭Program 10‬

‭Aim:‬‭Develop a small web program using Servlets, JSPs‬‭with Database connectivity.‬

‭Theory:‬

‭ he‬ ‭program‬ ‭aims‬ ‭to‬‭showcase‬‭the‬‭integration‬‭of‬‭Java‬‭Servlets,‬‭JavaServer‬‭Pages‬


T
‭(JSP), and database connectivity to develop a dynamic web application.‬

‭Servlets for Backend Processing:‬

‭●‬ S ‭ ervlets‬ ‭handle‬ ‭HTTP‬ ‭requests‬ ‭and‬ ‭responses,‬ ‭serving‬‭as‬‭the‬‭backbone‬‭for‬


‭server-side logic and processing.‬
‭●‬ ‭They‬ ‭interact‬ ‭with‬ ‭the‬ ‭database‬ ‭to‬ ‭fetch‬ ‭or‬ ‭manipulate‬ ‭data‬ ‭based‬ ‭on‬ ‭client‬
‭requests.‬

‭JavaServer Pages (JSP) for Presentation:‬

‭●‬ J‭ SPs‬‭are‬‭used‬‭to‬‭create‬‭dynamic‬‭web‬‭pages‬‭by‬‭embedding‬‭Java‬‭code‬‭within‬
‭HTML markup.‬
‭●‬ ‭They‬ ‭provide‬ ‭a‬ ‭user-friendly‬ ‭interface,‬ ‭presenting‬ ‭data‬ ‭fetched‬ ‭from‬ ‭the‬
‭database via servlets.‬

‭Database Connectivity:‬

‭●‬ D ‭ atabase‬ ‭connectivity‬ ‭is‬ ‭established‬ ‭using‬ ‭JDBC‬ ‭(Java‬ ‭Database‬


‭Connectivity) to interact with the backend database.‬
‭●‬ ‭Servlets‬ ‭utilize‬ ‭JDBC‬ ‭to‬ ‭execute‬ ‭SQL‬ ‭queries,‬ ‭retrieve‬ ‭data,‬ ‭and‬ ‭update‬
‭database records as required.‬

‭Workflow:‬

‭1.‬ C ‭ lient‬ ‭Request‬ ‭Handling:‬ ‭Servlets‬ ‭receive‬ ‭HTTP‬ ‭requests‬‭from‬‭clients‬‭and‬


‭perform necessary processing.‬
‭2.‬ ‭Data‬ ‭Presentation:‬ ‭Servlets‬‭pass‬‭data‬‭to‬‭JSPs,‬‭which‬‭dynamically‬‭generate‬
‭HTML content for presentation.‬
‭3.‬ ‭Database‬ ‭Interaction:‬ ‭Servlets‬ ‭interact‬ ‭with‬ ‭the‬ ‭database‬ ‭using‬ ‭JDBC‬ ‭to‬
‭retrieve or manipulate data.‬
‭4.‬ ‭Response‬‭Generation:‬‭Servlets‬‭send‬‭the‬‭processed‬‭data‬‭to‬‭clients‬‭as‬‭HTTP‬
‭responses.‬
‭Code:‬

‭UserServlet.java‬

i‭mport java.io.*;‬
‭import javax.servlet.*;‬
‭import javax.servlet.http.*;‬
‭import java.sql.*;‬

‭public class UserServlet extends HttpServlet {‬


‭public‬ ‭void‬ ‭doPost(HttpServletRequest‬ ‭request,‬‭HttpServletResponse‬‭response)‬
‭throws ServletException, IOException {‬
‭String action = request.getParameter("action");‬

‭if ("register".equals(action)) {‬
‭register(request, response);‬
‭} else if ("login".equals(action)) {‬
‭login(request, response);‬
‭}‬
‭}‬

‭ rivate‬‭void‬‭register(HttpServletRequest‬‭request,‬‭HttpServletResponse‬‭response)‬
p
‭throws ServletException, IOException {‬
‭String username = request.getParameter("username");‬
‭String password = request.getParameter("password");‬

‭try {‬
‭Class.forName("com.mysql.jdbc.Driver");‬
‭ onnection‬
C ‭con‬ ‭=‬
‭DriverManager.getConnection("jdbc:mysql://localhost:3306/userdb",‬ ‭"username",‬
‭"password");‬

‭ reparedStatement‬ ‭pst‬ ‭=‬ ‭con.prepareStatement("INSERT‬ ‭INTO‬ ‭users‬


P
‭(username, password) VALUES (?, ?)");‬
‭pst.setString(1, username);‬
‭pst.setString(2, password);‬
‭pst.executeUpdate();‬

c‭ on.close();‬
‭response.sendRedirect("registration_success.jsp");‬
‭} catch (Exception e) {‬
‭e.printStackTrace();‬
‭}‬
‭}‬
‭ rivate‬ ‭void‬ ‭login(HttpServletRequest‬ ‭request,‬ ‭HttpServletResponse‬ ‭response)‬
p
‭throws ServletException, IOException {‬
‭String username = request.getParameter("username");‬
‭String password = request.getParameter("password");‬

‭try {‬
‭Class.forName("com.mysql.jdbc.Driver");‬
‭ onnection‬
C ‭con‬ ‭=‬
‭DriverManager.getConnection("jdbc:mysql://localhost:3306/userdb",‬ ‭"username",‬
‭"password");‬

‭ reparedStatement‬‭pst‬‭=‬‭con.prepareStatement("SELECT‬‭*‬‭FROM‬‭users‬
P
‭WHERE username=? AND password=?");‬
‭pst.setString(1, username);‬
‭pst.setString(2, password);‬
‭ResultSet rs = pst.executeQuery();‬

‭if (rs.next()) {‬
‭// Successful login‬
‭HttpSession session = request.getSession();‬
‭session.setAttribute("username", username);‬
‭response.sendRedirect("welcome.jsp");‬
‭} else {‬
‭// Invalid credentials‬
‭response.sendRedirect("login.jsp?error=true");‬
‭}‬

c‭ on.close();‬
‭} catch (Exception e) {‬
‭e.printStackTrace();‬
‭}‬
‭}‬
‭}‬

‭registration.jsp‬

‭ html>‬
<
‭<head><title>User Registration</title></head>‬
‭<body>‬
‭<h2>User Registration</h2>‬
‭<form action="UserServlet" method="post">‬
‭Username: <input type="text" name="username" required><br>‬
‭Password: <input type="password" name="password" required><br>‬
‭ input type="hidden" name="action" value="register">‬
<
‭<input type="submit" value="Register">‬
‭</form>‬
‭</body>‬
‭</html>‬

‭login.jsp‬

‭ html>‬
<
‭<head><title>User Login</title></head>‬
‭<body>‬
‭<h2>User Login</h2>‬
‭<form action="UserServlet" method="post">‬
‭Username: <input type="text" name="username" required><br>‬
‭Password: <input type="password" name="password" required><br>‬
‭<input type="hidden" name="action" value="login">‬
‭<input type="submit" value="Login">‬
‭<% if ("true".equals(request.getParameter("error"))) { %>‬
‭<p style="color:red;">Invalid username or password</p>‬
‭<% } %>‬
‭</form>‬
‭</body>‬
‭</html>‬

‭registration_success.jsp‬

‭ html>‬
<
‭<head><title>Registration Success</title></head>‬
‭<body>‬
‭<h2>Registration Successful</h2>‬
‭<p>You have successfully registered.</p>‬
‭<a href="login.jsp">Login</a>‬
‭</body>‬
‭</html>‬

‭welcome.jsp‬

‭ html>‬
<
‭<head><title>Welcome</title></head>‬
‭<body>‬
‭<h2>Welcome, <%= session.getAttribute("username") %>!</h2>‬
‭<p>You are now logged in.</p>‬
‭</body>‬
‭</html>‬
‭Output:‬
‭Program 11‬

‭ im:‬ ‭Create‬ ‭a‬ ‭class‬ ‭Box‬ ‭that‬ ‭uses‬ ‭a‬ ‭parameterized‬ ‭constructor‬ ‭to‬ ‭initialize‬ ‭the‬
A
‭dimensions‬‭of‬‭a‬‭box.‬‭The‬‭dimensions‬‭of‬‭the‬‭Box‬‭are‬‭width,‬‭height,‬‭depth.‬‭The‬‭class‬
‭should‬‭have‬‭a‬‭method‬‭that‬‭can‬‭return‬‭the‬‭volume‬‭of‬‭the‬‭box.‬‭Create‬‭an‬‭object‬‭of‬‭the‬
‭Box class and test the functionalities.‬

‭Theory:‬

‭Parameterized Constructor:‬

‭●‬ T‭ he‬ ‭Box‬ ‭class‬ ‭features‬ ‭a‬ ‭parameterized‬ ‭constructor‬ ‭that‬ ‭accepts‬ ‭the‬
‭dimensions‬ ‭(width,‬ ‭height,‬ ‭depth)‬ ‭as‬ ‭arguments‬ ‭and‬ ‭initializes‬ ‭the‬ ‭instance‬
‭variables accordingly.‬

‭Method for Calculating Volume:‬

‭●‬ W ‭ ithin‬‭the‬‭Box‬‭class,‬‭a‬‭method‬‭is‬‭implemented‬‭to‬‭compute‬‭the‬‭volume‬‭of‬‭the‬
‭box based on its dimensions.‬
‭●‬ ‭This‬‭method‬‭calculates‬‭the‬‭volume‬‭by‬‭multiplying‬‭the‬‭width,‬‭height,‬‭and‬‭depth‬
‭of the box.‬

‭Object Creation and Functionality Testing:‬

‭●‬ A ‭ n‬ ‭object‬ ‭of‬ ‭the‬‭Box‬‭class‬‭is‬‭instantiated,‬‭and‬‭the‬‭parameterized‬‭constructor‬


‭is invoked to initialize its dimensions.‬
‭●‬ ‭The‬ ‭volume‬ ‭calculation‬ ‭method‬ ‭is‬ ‭called‬ ‭on‬ ‭the‬ ‭Box‬ ‭object‬‭to‬‭determine‬‭the‬
‭volume of the box.‬
‭Code:‬

‭ ackage Java;‬
p
‭import java.util.Scanner;‬
‭class Box {‬
‭int width,height, depth;‬
‭Box(int w, int h, int d) {‬
‭width = w;‬
‭height = h;‬
‭depth = d;‬
‭}‬
‭int calVolume() {‬
‭return width * height * depth;‬
‭}‬
‭}‬
‭public class Program1 {‬
‭public static void main(String[] args) {‬
‭System.out.println("Parameterized Constructor");‬
‭Scanner s = new Scanner(System.in);‬
‭System.out.print("Enter the dimensions: ");‬
‭int w = s.nextInt();‬
‭int h = s.nextInt();‬
‭int d = s.nextInt();‬
‭Box b = new Box(w, h, d);‬
‭System.out.println("The volume of the box is: " + b.calVolume());‬
‭}‬
‭}‬

‭Output:‬
‭Program 12‬

‭ im:‬ ‭Create‬ ‭a‬ ‭base‬ ‭class‬ ‭Fruit‬ ‭which‬ ‭has‬ ‭name‬ ‭,taste‬‭and‬‭size‬‭as‬‭its‬‭attributes.‬‭A‬
A
‭method‬ ‭called‬ ‭eat()‬ ‭is‬ ‭created‬ ‭which‬ ‭describes‬ ‭the‬ ‭name‬ ‭of‬ ‭the‬ ‭fruit‬ ‭and‬ ‭its‬ ‭taste.‬
‭Inherit‬‭the‬‭same‬‭in‬‭2‬‭other‬‭class‬‭Apple‬‭and‬‭Orange‬‭and‬‭override‬‭the‬‭eat()‬‭method‬‭to‬
‭represent each fruit taste. (Method overriding)‬

‭Theory:‬

‭ his‬ ‭program‬ ‭demonstrates‬ ‭the‬ ‭concepts‬ ‭of‬ ‭inheritance‬ ‭and‬ ‭method‬ ‭overriding‬ ‭in‬
T
‭Java‬‭by‬‭creating‬‭a‬‭base‬‭class,‬‭Fruit,‬‭with‬‭attributes‬‭like‬‭name,‬‭taste,‬‭and‬‭size,‬‭along‬
‭with a method called eat().‬

‭Base Class Fruit:‬

‭●‬ T ‭ he‬ ‭Fruit‬ ‭class‬ ‭serves‬ ‭as‬ ‭the‬ ‭base‬ ‭class,‬ ‭containing‬ ‭attributes‬ ‭like‬ ‭name,‬
‭taste, and size.‬
‭●‬ ‭It‬ ‭includes‬ ‭a‬ ‭method‬ ‭called‬ ‭eat()‬ ‭that‬ ‭describes‬ ‭the‬ ‭name‬ ‭of‬‭the‬‭fruit‬‭and‬‭its‬
‭taste.‬

‭Inheritance in Apple and Orange Classes:‬

‭●‬ T ‭ he‬ ‭Apple‬ ‭and‬‭Orange‬‭classes‬‭inherit‬‭from‬‭the‬‭Fruit‬‭class,‬‭thereby‬‭inheriting‬


‭its attributes and methods.‬
‭●‬ ‭By‬ ‭extending‬ ‭the‬ ‭Fruit‬ ‭class,‬ ‭the‬ ‭Apple‬‭and‬‭Orange‬‭classes‬‭can‬‭access‬‭and‬
‭utilize its properties and behaviors.‬

‭Method Overriding:‬

‭●‬ I‭n‬‭the‬‭Apple‬‭and‬‭Orange‬‭classes,‬‭the‬‭eat()‬‭method‬‭is‬‭overridden‬‭to‬‭represent‬
‭the specific taste of each fruit.‬
‭●‬ ‭Method‬‭overriding‬‭allows‬‭subclasses‬‭to‬‭provide‬‭their‬‭own‬‭implementation‬‭of‬‭a‬
‭method‬ ‭inherited‬ ‭from‬ ‭the‬ ‭superclass,‬ ‭enabling‬ ‭customization‬ ‭based‬ ‭on‬ ‭the‬
‭specific characteristics of each fruit.‬

‭Testing Functionality:‬

‭●‬ O‭ bjects‬‭of‬‭the‬‭Apple‬‭and‬‭Orange‬‭classes‬‭are‬‭created,‬‭and‬‭the‬‭eat()‬‭method‬‭is‬
‭called‬ ‭to‬ ‭showcase‬ ‭the‬ ‭overridden‬ ‭behavior,‬ ‭demonstrating‬ ‭the‬‭distinct‬‭taste‬
‭of each fruit.‬
‭Code:‬

‭ ackage Java;‬
p
‭class Fruit {‬
‭String name, taste;‬
‭int size;‬
‭void eat() {‬
‭System.out.println("Inside Fruit class");‬
‭}‬
‭}‬
‭class Apple extends Fruit {‬
‭Apple(String n, String t, int s) {‬
‭name = n;‬
‭taste = t;‬
‭size = s;‬
‭}‬
‭void eat() {‬
‭System.out.println("Name: " + name + "\nTaste: " + taste);‬
‭}‬
‭}‬
‭class Orange extends Fruit {‬
‭Orange(String n, String t, int s) {‬
‭name = n;‬
‭taste = t;‬
‭size = s;‬
‭}‬
‭void eat() {‬
‭System.out.println("Name: " + name + "\nTaste: " + taste);‬
‭}‬
‭}‬
‭public class Program2 {‬
‭public static void main(String[] args) {‬
‭Apple a = new Apple("Apple", "sour", 10);‬
‭System.out.println("Method Overriding");‬
‭a.eat();‬
‭}‬
‭}‬

‭Output:‬
‭Program 13‬

‭ im:‬ ‭Write‬‭a‬‭program‬‭to‬‭create‬‭a‬‭class‬‭named‬‭shape.‬‭It‬‭should‬‭contain‬‭2‬‭methods-‬
A
‭draw()‬ ‭and‬ ‭erase()‬ ‭which‬ ‭should‬ ‭print‬ ‭“Drawing‬ ‭Shape”‬ ‭and‬ ‭“Erasing‬ ‭Shape”‬
‭respectively.‬ ‭For‬ ‭this‬ ‭class‬ ‭we‬ ‭have‬ ‭three‬‭sub‬‭classes-‬‭Circle,‬‭Triangle‬‭and‬‭Square‬
‭and‬‭each‬‭class‬‭override‬‭the‬‭parent‬‭class‬‭functions-‬‭draw‬‭()‬‭and‬‭erase‬‭().‬‭The‬‭draw()‬
‭method‬ ‭should‬ ‭print‬ ‭“Drawing‬ ‭Circle”,‬ ‭“Drawing‬ ‭Triangle”,‬ ‭“Drawing‬ ‭Square”‬
‭respectively.‬ ‭The‬ ‭erase()‬ ‭method‬ ‭should‬ ‭print‬ ‭“Erasing‬ ‭Circle”,‬ ‭“Erasing‬ ‭Triangle”,‬
‭“Erasing‬ ‭Square”‬ ‭respectively.‬ ‭Create‬ ‭objects‬ ‭of‬ ‭Circle,‬ ‭Triangle‬ ‭and‬ ‭Square‬‭in‬‭the‬
‭following‬‭way‬‭and‬‭observe‬‭the‬‭polymorphic‬‭nature‬‭of‬‭the‬‭class‬‭by‬‭calling‬‭draw()‬‭and‬
‭erase()‬ ‭method‬ ‭using‬ ‭each‬ ‭object.‬ ‭Shape‬ ‭c=new‬ ‭Circle();‬ ‭Shape‬ ‭t=new‬ ‭Triangle();‬
‭Shape s=new Square(); (Polymorphism)‬

‭Theory:‬

‭ olymorphism‬ ‭allows‬ ‭objects‬ ‭of‬ ‭different‬ ‭classes‬ ‭to‬ ‭be‬ ‭treated‬ ‭as‬ ‭objects‬ ‭of‬ ‭a‬
P
‭common‬ ‭superclass,‬ ‭facilitating‬ ‭code‬ ‭reuse‬ ‭and‬ ‭flexibility.‬ ‭This‬ ‭program‬
‭demonstrates polymorphism in a shape class hierarchy.‬

‭Shape Class:‬

‭1.‬ M ‭ ethods:‬ ‭The‬ ‭Shape‬ ‭class‬ ‭defines‬ ‭two‬ ‭methods,‬ ‭draw()‬‭and‬‭erase(),‬‭which‬


‭print "Drawing Shape" and "Erasing Shape", respectively.‬
‭2.‬ ‭Parent‬ ‭Class:‬ ‭Circle,‬ ‭Triangle,‬ ‭and‬ ‭Square‬ ‭inherit‬ ‭from‬ ‭the‬ ‭Shape‬ ‭class,‬
‭sharing common behavior.‬

‭Subclasses: Circle, Triangle, Square:‬

‭1.‬ M ‭ ethod‬ ‭Override:‬ ‭Each‬ ‭subclass‬ ‭overrides‬ ‭the‬‭draw()‬‭and‬‭erase()‬‭methods‬


‭inherited from the Shape class.‬
‭2.‬ ‭Draw‬‭Method:‬‭Overrides‬‭print‬‭"Drawing‬‭Circle",‬‭"Drawing‬‭Triangle",‬‭"Drawing‬
‭Square", respectively.‬
‭3.‬ ‭Erase‬ ‭Method:‬ ‭Overrides‬ ‭print‬ ‭"Erasing‬ ‭Circle",‬‭"Erasing‬‭Triangle",‬‭"Erasing‬
‭Square", respectively.‬

‭Polymorphic Behavior:‬

‭●‬ O ‭ bjects‬ ‭of‬ ‭Circle,‬ ‭Triangle,‬ ‭and‬ ‭Square‬ ‭classes‬ ‭are‬ ‭instantiated‬ ‭using‬ ‭the‬
‭Shape superclass.‬
‭●‬ ‭Calling‬ ‭draw()‬ ‭and‬ ‭erase()‬ ‭methods‬ ‭on‬ ‭these‬ ‭objects‬ ‭demonstrates‬
‭polymorphic‬‭behavior,‬‭executing‬‭the‬‭overridden‬‭methods‬‭based‬‭on‬‭the‬‭actual‬
‭object type.‬
‭Code:‬

‭ ackage Java;‬
p
‭class Shape {‬
‭void draw() {‬
‭System.out.println("Drawing Shape");‬
‭}‬
‭void erase() {‬
‭System.out.println("Erasing Shape");‬
‭}‬
‭}‬
‭class Circle extends Shape {‬
‭void draw() {‬
‭System.out.println("Drawing Circle");‬
‭}‬
‭void erase() {‬
‭System.out.println("Erasing Circle");‬
‭}‬
‭}‬
‭class Triangle extends Shape {‬
‭void draw() {‬
‭System.out.println("Drawing Triangle");‬
‭}‬
‭void erase() {‬
‭System.out.println("Erasing Triangle");‬
‭}‬
‭}‬
‭class Square extends Shape {‬
‭void draw() {‬
‭System.out.println("Drawing Square");‬
‭}‬
‭void erase() {‬
‭System.out.println("Erasing Square");‬
‭}‬
‭}‬
‭public class Program3 {‬
‭public static void main(String[] args) {‬
‭Shape c = new Circle();‬
‭Shape t = new Triangle();‬
‭Shape s = new Square();‬
‭c.draw(); c.erase();‬
‭t.draw(); t.erase();‬
‭s.draw(); s.erase();‬
‭}‬
‭}‬

‭Output:‬
‭Program 14‬

‭ im:‬‭Write‬‭a‬‭Program‬‭to‬‭take‬‭care‬‭of‬‭Number‬‭Format‬‭Exception‬‭if‬‭user‬‭enters‬‭values‬
A
‭other‬ ‭than‬ ‭integer‬ ‭for‬ ‭calculating‬ ‭average‬ ‭marks‬ ‭of‬ ‭2‬ ‭students.‬ ‭The‬ ‭name‬ ‭of‬ ‭the‬
‭students‬ ‭and‬ ‭marks‬ ‭in‬ ‭3‬ ‭subjects‬ ‭are‬ ‭taken‬ ‭from‬ ‭the‬ ‭user‬ ‭while‬ ‭executing‬ ‭the‬
‭program.‬ ‭In‬ ‭the‬ ‭same‬ ‭Program‬ ‭write‬ ‭your‬ ‭own‬ ‭Exception‬ ‭classes‬ ‭to‬ ‭take‬ ‭care‬ ‭of‬
‭Negative values and values out of range (i.e. other than in the range of 0-100)‬

‭Theory:‬

‭ his‬ ‭program‬ ‭is‬ ‭designed‬ ‭to‬ ‭calculate‬ ‭the‬ ‭average‬ ‭marks‬ ‭of‬ ‭two‬ ‭students‬ ‭in‬ ‭three‬
T
‭subjects,‬ ‭taking‬ ‭inputs‬ ‭from‬ ‭the‬ ‭user.‬ ‭It‬ ‭includes‬ ‭error‬ ‭handling‬ ‭mechanisms‬ ‭to‬
‭manage‬ ‭NumberFormatException‬ ‭and‬ ‭custom‬ ‭exceptions‬ ‭for‬ ‭negative‬ ‭values‬ ‭and‬
‭values out of range.‬

‭Input Validation:‬

‭●‬ T ‭ he‬‭program‬‭prompts‬‭the‬‭user‬‭to‬‭input‬‭the‬‭names‬‭and‬‭marks‬‭of‬‭two‬‭students‬
‭in three subjects.‬
‭●‬ ‭Error‬‭handling‬‭is‬‭implemented‬‭to‬‭ensure‬‭that‬‭the‬‭input‬‭values‬‭are‬‭integers‬‭and‬
‭fall within the range of 0-100.‬

‭NumberFormatException Handling:‬

‭●‬ I‭f‬ ‭the‬ ‭user‬ ‭enters‬ ‭non-integer‬ ‭values,‬ ‭a‬ ‭NumberFormatException‬ ‭is‬ ‭caught‬
‭and‬ ‭appropriate‬ ‭error‬ ‭messages‬ ‭are‬ ‭displayed,‬ ‭prompting‬ ‭the‬ ‭user‬ ‭to‬ ‭enter‬
‭valid input.‬

‭Custom Exception Classes:‬

‭●‬ C ‭ ustom‬ ‭exception‬ ‭classes‬ ‭are‬ ‭created‬ ‭to‬ ‭handle‬ ‭negative‬ ‭values‬
‭(NegativeValueException) and values out of range (OutOfRangeException).‬
‭●‬ ‭These‬ ‭exceptions‬ ‭are‬ ‭thrown‬ ‭when‬ ‭the‬ ‭input‬ ‭values‬ ‭violate‬ ‭the‬ ‭specified‬
‭conditions, and corresponding error messages are displayed to the user.‬

‭Average Marks Calculation:‬

‭●‬ A‭ fter‬ ‭validating‬ ‭the‬ ‭input,‬ ‭the‬ ‭program‬ ‭calculates‬‭the‬‭average‬‭marks‬‭of‬‭each‬


‭student in three subjects and displays the results.‬
‭Code:‬

‭ ackage Java;‬
p
‭import java.util.Scanner;‬
‭class ExceptionClass extends Exception {‬
‭public String toString() {‬
‭return "Error! Marks are not in the range(1,100)";‬
‭}‬
‭}‬
‭public class Program4 {‬
‭Scanner s = new Scanner(System.in);‬
‭String name;‬
‭float sum = 0;‬
‭int marks[]=new int[3];‬
‭void input() throws ExceptionClass {‬
‭System.out.print("Enter name of the Student: ");‬
‭name = s.nextLine();‬
‭System.out.print("Enter‬‭the‬‭marks‬‭of‬‭"‬‭+‬‭name‬‭+‬‭"‬‭in‬‭Physics,‬‭Chemistry‬‭and‬‭Maths:‬
‭");‬
‭for (int i = 0; i < 3; i++) {‬
‭marks[i] = Integer.parseInt(s.next());‬
‭if (marks[i] < 0 || marks[i] > 100) {‬
‭throw new ExceptionClass();‬
‭}‬
‭sum += marks[i];‬
‭}‬
‭System.out.println("Average of marks of " + name + " is " + sum / 3);‬
‭}‬
‭public static void main(String[] args) {‬
‭System.out.println("NumberFormatException, Custom Exception in Java");‬
‭Program4 a = new Program4();‬
‭Program4 b = new Program4();‬
‭try {‬
‭a.input();‬
‭b.input();‬
‭}‬
‭catch (NumberFormatException n) {‬
‭System.out.println("NumberFormatException caught " + n.getMessage());‬
‭}‬
‭catch (ExceptionClass e) {‬
‭System.out.println(e);‬
‭}‬
‭}‬
‭}‬
‭Output:‬
‭Program 15‬

‭ im:‬ ‭Write‬ ‭a‬ ‭program‬ ‭that‬ ‭takes‬ ‭as‬ ‭input‬‭the‬‭size‬‭of‬‭the‬‭array‬‭and‬‭the‬‭elements‬‭in‬


A
‭the‬ ‭array.‬ ‭The‬‭program‬‭then‬‭asks‬‭the‬‭user‬‭to‬‭enter‬‭a‬‭particular‬‭index‬‭and‬‭prints‬‭the‬
‭element‬‭at‬‭that‬‭index.‬‭Index‬‭starts‬‭from‬‭zero.This‬‭program‬‭may‬‭generate‬‭Array‬‭Index‬
‭Out‬ ‭Of‬ ‭Bounds‬ ‭Exception‬ ‭or‬ ‭NumberFormatException.‬ ‭Use‬ ‭exception‬ ‭handling‬
‭mechanisms to handle this exception.‬

‭Theory:‬

‭ his‬ ‭program‬ ‭allows‬ ‭users‬ ‭to‬ ‭input‬ ‭the‬ ‭size‬ ‭of‬ ‭an‬ ‭array‬ ‭and‬ ‭its‬ ‭elements,‬ ‭then‬
T
‭prompts‬ ‭for‬ ‭a‬ ‭specific‬ ‭index‬ ‭to‬ ‭retrieve‬ ‭and‬ ‭print‬ ‭the‬ ‭corresponding‬ ‭element.‬ ‭It‬
‭incorporates‬ ‭exception‬ ‭handling‬ ‭mechanisms‬ ‭to‬ ‭manage‬ ‭potential‬
‭ArrayIndexOutOfBoundsException and NumberFormatException.‬

‭Array Input and Index Retrieval:‬

‭●‬ U ‭ sers‬ ‭provide‬ ‭the‬ ‭size‬ ‭of‬ ‭the‬ ‭array‬ ‭and‬ ‭its‬ ‭elements,‬ ‭with‬ ‭indexing‬ ‭starting‬
‭from zero.‬
‭●‬ ‭The‬‭program‬‭prompts‬‭for‬‭a‬‭specific‬‭index‬‭to‬‭retrieve‬‭the‬‭element‬‭stored‬‭at‬‭that‬
‭position in the array.‬

‭Exception Handling:‬

‭●‬ E ‭ rror‬ ‭handling‬ ‭is‬ ‭implemented‬ ‭to‬ ‭address‬ ‭potential‬


‭ArrayIndexOutOfBoundsException and NumberFormatException scenarios.‬
‭●‬ ‭If‬ ‭the‬ ‭user‬ ‭inputs‬ ‭an‬ ‭index‬ ‭that‬ ‭is‬ ‭out‬ ‭of‬ ‭the‬ ‭array's‬ ‭bounds‬ ‭or‬ ‭provides‬
‭non-integer‬ ‭values,‬ ‭appropriate‬ ‭exception‬ ‭handling‬ ‭mechanisms‬ ‭are‬
‭employed.‬

‭Array Index Out Of Bounds Exception:‬

‭●‬ I‭f‬ ‭the‬ ‭user‬ ‭enters‬ ‭an‬ ‭index‬ ‭that‬ ‭exceeds‬ ‭the‬ ‭array's‬ ‭size‬ ‭or‬ ‭is‬ ‭negative,‬ ‭an‬
‭ArrayIndexOutOfBoundsException‬ ‭is‬ ‭caught,‬ ‭and‬ ‭a‬ ‭corresponding‬ ‭error‬
‭message is displayed.‬

‭Number Format Exception:‬

‭●‬ I‭f‬‭the‬‭user‬‭enters‬‭non-integer‬‭values‬‭for‬‭the‬‭index,‬‭a‬‭NumberFormatException‬
‭is caught, and the program prompts the user to enter a valid integer index.‬
‭Code:‬

i‭mport java.util.Scanner;‬
‭public class Program5 {‬
‭public static void main(String[] args) {‬
‭System.out.println("ArrayIndexOutOfBoundsException,‬ ‭NumberFormatException‬
‭in Java");‬
‭try {‬
‭Scanner s = new Scanner(System.in);‬
‭System.out.print("Enter the number of elements in the array: ");‬
‭int n = Integer.parseInt(s.next());‬
‭int arr[] = new int[n];‬
‭System.out.print("Enter the elements of the array: ");‬
‭for (int i = 0; i < n; i++) {‬
‭arr[i] = Integer.parseInt(s.next());‬
‭}‬
‭System.out.print("Enter the index at which element is to be found: ");‬
‭int a = Integer.parseInt(s.next());‬
‭System.out.println("Element at index " + a + " is " + arr[a]);‬
‭}‬
‭catch (ArrayIndexOutOfBoundsException a) {‬
‭System.out.println("ArrayIndexOutOfBoundsException‬ ‭caught‬ ‭"‬ ‭+‬
‭a.getMessage());‬
‭}‬
‭catch (NumberFormatException n) {‬
‭System.out.println("NumberFormatException caught " + n.getMessage());‬
‭}‬
‭}‬
‭}‬

‭Output:‬
‭Program 16‬

‭Aim:‬‭Implement Datagram UDP socket programming in‬‭java.‬

‭Theory:‬

‭●‬ D ‭ atagram‬ ‭UDP‬ ‭(User‬ ‭Datagram‬ ‭Protocol)‬ ‭socket‬ ‭programming‬ ‭in‬ ‭Java‬
‭enables‬ ‭communication‬‭between‬‭two‬‭endpoints‬‭over‬‭a‬‭network‬‭using‬‭UDP,‬‭a‬
‭connectionless protocol.‬
‭●‬ ‭This‬ ‭program‬ ‭demonstrates‬ ‭how‬ ‭to‬ ‭implement‬ ‭UDP‬ ‭socket‬ ‭programming‬ ‭in‬
‭Java for sending and receiving datagrams.‬

‭Socket Initialization:‬

‭●‬ T‭ he‬ ‭program‬ ‭initializes‬ ‭DatagramSocket‬ ‭objects‬ ‭for‬ ‭sending‬ ‭and‬ ‭receiving‬
‭datagrams, specifying the port numbers and optional IP addresses.‬

‭Sending Datagram:‬

‭●‬ U ‭ sing‬ ‭the‬ ‭DatagramSocket‬ ‭object‬ ‭for‬ ‭sending,‬ ‭the‬ ‭program‬ ‭creates‬ ‭a‬
‭DatagramPacket containing the data to be sent and the destination address.‬
‭●‬ ‭The‬ ‭DatagramPacket‬ ‭is‬ ‭then‬ ‭sent‬ ‭using‬ ‭the‬ ‭send()‬ ‭method‬ ‭of‬ ‭the‬
‭DatagramSocket.‬

‭Receiving Datagram:‬

‭●‬ U ‭ sing‬ ‭the‬ ‭DatagramSocket‬ ‭object‬ ‭for‬ ‭receiving,‬ ‭the‬ ‭program‬ ‭creates‬ ‭a‬
‭DatagramPacket to store the received data.‬
‭●‬ ‭The‬ ‭receive()‬ ‭method‬ ‭of‬ ‭the‬ ‭DatagramSocket‬ ‭is‬ ‭used‬ ‭to‬ ‭receive‬ ‭datagrams,‬
‭which are then extracted from the DatagramPacket.‬

‭Error Handling:‬

‭●‬ E‭ xception‬‭handling‬‭mechanisms‬‭are‬‭implemented‬‭to‬‭manage‬‭potential‬‭errors,‬
‭such as IOExceptions that may occur during socket operations.‬
‭Code:‬

‭Server Side:‬

i‭mport java.net.*;‬
‭public class UdpServer {‬
‭public static void main(String[] args) throws Exception {‬
‭int port = 5000;‬
‭DatagramSocket serverSocket = new DatagramSocket(port);‬
‭byte[] receiveData = new byte[1024];‬
‭while (true) {‬
‭DatagramPacket‬ ‭receivePacket‬ ‭=‬ ‭new‬ ‭DatagramPacket(receiveData,‬
‭receiveData.length);‬
‭serverSocket.receive(receivePacket);‬
‭String‬ ‭message‬ ‭=‬ ‭new‬ ‭String(receivePacket.getData(),‬ ‭0,‬
‭receivePacket.getLength());‬
‭System.out.println("Received‬ ‭message‬ ‭from‬ ‭"‬ ‭+‬
‭receivePacket.getAddress().getHostAddress() + ": " +‬
‭message);‬
‭}‬
‭}‬
‭}‬

‭Client Side:‬

i‭mport java.net.*;‬
‭public class UdpClient {‬
‭public static void main(String[] args) throws Exception {‬
‭String message = "Hello from UDP Client!";‬
‭int port = 5000;‬
‭InetAddressserverAddress = InetAddress.getByName("localhost");‬
‭DatagramSocket clientSocket = new DatagramSocket();‬
‭byte[]sendData = message.getBytes();‬
‭DatagramPacket‬ ‭sendPacket‬ ‭=‬ ‭new‬ ‭DatagramPacket(sendData,‬ ‭sendData.length,‬
‭serverAddress, port);‬
‭clientSocket.send(sendPacket);‬
‭System.out.println("Sent message: " + message);‬
‭clientSocket.close();‬
‭}‬
‭}‬
‭Output:‬
‭Program 17‬

‭Aim:‬‭Implement Socket programming for TCP in Java‬‭Server and Client Sockets.‬

‭Theory:‬

‭ CP‬ ‭(Transmission‬ ‭Control‬ ‭Protocol)‬ ‭socket‬ ‭programming‬ ‭in‬ ‭Java‬ ‭facilitates‬


T
‭communication‬ ‭between‬ ‭a‬ ‭server‬ ‭and‬ ‭client‬ ‭over‬ ‭a‬ ‭network,‬ ‭ensuring‬ ‭reliable‬ ‭data‬
‭transmission.‬

‭Server Implementation:‬

‭●‬ T ‭ he‬ ‭server‬ ‭program‬ ‭initializes‬ ‭a‬ ‭ServerSocket‬ ‭object,‬ ‭specifying‬ ‭a‬ ‭port‬
‭number for listening to client connections.‬
‭●‬ ‭It‬ ‭continuously‬ ‭listens‬ ‭for‬ ‭incoming‬ ‭client‬ ‭connections‬ ‭using‬ ‭the‬ ‭accept()‬
‭method of ServerSocket.‬
‭●‬ ‭Upon‬ ‭accepting‬ ‭a‬ ‭client‬ ‭connection,‬ ‭it‬ ‭creates‬ ‭a‬ ‭new‬ ‭Socket‬ ‭object‬ ‭for‬
‭communication with the client.‬
‭●‬ ‭It‬ ‭establishes‬ ‭input‬ ‭and‬ ‭output‬ ‭streams‬ ‭to‬ ‭send‬ ‭and‬ ‭receive‬ ‭data‬ ‭from‬ ‭the‬
‭client.‬
‭●‬ ‭The‬ ‭server‬ ‭performs‬ ‭required‬ ‭data‬ ‭processing‬ ‭or‬ ‭actions‬ ‭based‬ ‭on‬ ‭the‬
‭received data.‬

‭Client Implementation:‬

‭●‬ T ‭ he‬ ‭client‬ ‭program‬ ‭initializes‬ ‭a‬ ‭Socket‬ ‭object,‬ ‭specifying‬ ‭the‬ ‭server's‬ ‭IP‬
‭address and port number.‬
‭●‬ ‭It establishes input and output streams for communication with the server.‬
‭●‬ ‭The‬ ‭client‬ ‭sends‬ ‭data‬ ‭to‬ ‭the‬ ‭server‬ ‭using‬ ‭the‬ ‭output‬ ‭stream‬ ‭and‬ ‭receives‬
‭responses using the input stream.‬
‭Code:‬

‭Server Side:‬

i‭mport java.io.*;‬
‭import java.net.*;‬
‭public class Server {‬
‭public static void main(String[] args) throws IOException {‬
‭int portNumber = 6789;‬
‭try (‬
‭ServerSocket serverSocket = new ServerSocket(portNumber);‬
‭Socket clientSocket = serverSocket.accept();‬
‭BufferedReader‬ ‭in‬ ‭=‬ ‭new‬ ‭BufferedReader(new‬
‭InputStreamReader(clientSocket.getInputStream()));‬
‭PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);‬
‭) {‬
‭System.out.println("Client connected!");‬
‭String message;‬
‭while ((message = in.readLine()) != null) {‬
‭System.out.println("Client: " + message);‬
‭out.println("Server received: " + message);‬
‭}‬
‭} catch (IOException e) {‬
‭System.err.println("Server error: " + e.getMessage());‬
‭}‬
‭}‬
‭}‬

‭Client Side:‬

i‭mport java.io.*;‬
‭import java.net.*;‬
‭public class Client {‬
‭public static void main(String[] args) throws IOException {‬
‭String serverAddress = "localhost";‬
‭int portNumber = 6789;‬
‭try (‬
‭Socket clientSocket = new Socket(serverAddress, portNumber);‬
‭BufferedReader‬ ‭in‬ ‭=‬ ‭new‬ ‭BufferedReader(new‬
‭InputStreamReader(clientSocket.getInputStream()));‬
‭PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);‬
‭BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in))‬
‭) {‬
‭String serverMessage;‬
‭String userMessage;‬
‭while ((serverMessage = in.readLine()) != null) {‬
‭System.out.println("Server: " + serverMessage);‬
‭if (serverMessage.equalsIgnoreCase("quit")) {‬
‭break;‬
‭}‬
‭}‬
‭while ((userMessage = stdIn.readLine()) != null) {‬
‭out.println(userMessage);‬
‭if (userMessage.equalsIgnoreCase("quit")) {‬
‭break;‬
‭}‬
‭serverMessage = in.readLine();‬
‭System.out.println("Server: " + serverMessage);‬
‭}‬
‭} catch (IOException e) {‬
‭System.err.println("Client error: " + e.getMessage());‬
‭}‬
‭}‬
‭}‬

‭Output:‬
‭Program 18‬

‭Aim:‬‭Implement Producer-Consumer Problem using multithreading.‬

‭Theory:‬

‭ he‬ ‭Producer-Consumer‬ ‭problem‬ ‭illustrates‬ ‭a‬ ‭synchronization‬ ‭issue‬ ‭where‬


T
‭producers‬ ‭produce‬ ‭items‬ ‭and‬ ‭add‬ ‭them‬ ‭to‬ ‭a‬ ‭shared‬ ‭buffer,‬ ‭while‬ ‭consumers‬
‭consume‬ ‭items‬ ‭from‬ ‭the‬ ‭buffer.‬ ‭Multithreading‬ ‭is‬ ‭used‬ ‭to‬ ‭concurrently‬ ‭execute‬
‭producer and consumer tasks.‬

‭Thread Synchronization:‬

‭●‬ J‭ ava‬ ‭provides‬ ‭synchronization‬ ‭mechanisms‬ ‭such‬ ‭as‬ ‭locks,‬ ‭conditions,‬ ‭and‬
‭semaphores to coordinate access to shared resources.‬
‭●‬ ‭In‬ ‭this‬ ‭program,‬ ‭synchronization‬ ‭is‬ ‭crucial‬ ‭to‬ ‭prevent‬ ‭race‬ ‭conditions‬ ‭and‬
‭ensure data integrity in the shared buffer.‬

‭Producer Thread:‬

‭●‬ T ‭ he‬ ‭producer‬ ‭thread‬ ‭continuously‬ ‭produces‬ ‭items‬ ‭and‬ ‭adds‬ ‭them‬ ‭to‬ ‭the‬
‭shared buffer.‬
‭●‬ ‭It‬‭notifies‬‭the‬‭consumer‬‭thread‬‭after‬‭producing‬‭an‬‭item,‬‭allowing‬‭it‬‭to‬‭consume‬
‭from the buffer.‬

‭Consumer Thread:‬

‭‬ T
● ‭ he consumer thread continuously consumes items from the shared buffer.‬
‭●‬ ‭It‬‭waits‬‭for‬‭notification‬‭from‬‭the‬‭producer‬‭thread‬‭when‬‭the‬‭buffer‬‭is‬‭non-empty,‬
‭indicating that it can consume an item.‬

‭Buffer Management:‬

‭●‬ T ‭ he‬‭shared‬‭buffer‬‭is‬‭implemented‬‭using‬‭a‬‭data‬‭structure‬‭such‬‭as‬‭an‬‭array‬‭or‬‭a‬
‭queue.‬
‭●‬ ‭Buffer‬ ‭access‬ ‭is‬ ‭synchronized‬ ‭to‬ ‭prevent‬ ‭simultaneous‬ ‭access‬ ‭by‬ ‭producer‬
‭and consumer threads.‬
‭Code:‬

i‭mport java.util.LinkedList;‬
‭public class Program9 {‬
‭public static void main(String[] args) throws InterruptedException {‬
‭System.out.println("Producer-Consumer Problem using Multithreading");‬
‭final PC pc = new PC();‬
‭Thread t1 = new Thread(() -> {‬
‭try {‬
‭pc.produce();‬
‭} catch(InterruptedException e) {‬
‭e.printStackTrace();‬
‭}‬
‭});‬
‭Thread t2 = new Thread(() -> {‬
‭try {‬
‭pc.consume();‬
‭} catch(InterruptedException e) {‬
‭e.printStackTrace();‬
‭}‬
‭});‬
‭t1.start();‬
‭t2.start();‬
‭t1.join();‬
‭t2.join();‬
‭}‬
‭public static class PC {‬
‭LinkedList<Integer> list = new LinkedList <> ();‬
‭int capacity = 2;‬
‭public void produce() throws InterruptedException {‬
‭int value = 0;‬
‭while (true) {‬
‭synchronized(this) {‬
‭while (list.size() == capacity)‬
‭wait();‬
‭System.out.println("Producer produced-" + value);‬
‭list.add(value++);‬
‭notify();‬
‭Thread.sleep(1000);‬
‭}‬
‭}‬
‭}‬
‭public void consume() throws InterruptedException {‬
‭while (true) {‬
‭synchronized(this) {‬
‭while (list.size() == 0)‬
‭wait();‬
‭int val = list.removeFirst();‬
‭System.out.println("Consumer consumed-" + val);‬
‭notify();‬
‭Thread.sleep(1000);‬
‭}‬
‭}‬
‭}‬
‭}‬
‭}‬

‭Output:‬
‭Program 19‬

‭ im:‬ ‭Illustrate‬ ‭Priorities‬ ‭in‬ ‭Multithreading‬ ‭via‬ ‭help‬ ‭of‬ ‭getPriority()‬ ‭and‬ ‭setPriority()‬
A
‭method.‬

‭Theory:‬

I‭n‬ ‭multithreading,‬ ‭thread‬ ‭priorities‬ ‭determine‬ ‭the‬ ‭order‬ ‭in‬ ‭which‬ ‭threads‬ ‭are‬
‭scheduled‬ ‭for‬ ‭execution‬ ‭by‬ ‭the‬ ‭operating‬ ‭system.‬ ‭The‬‭getPriority()‬‭and‬‭setPriority()‬
‭methods in Java allow developers to manipulate thread priorities.‬

‭Understanding Thread Priorities:‬

‭●‬ T ‭ hread‬ ‭priorities‬ ‭are‬ ‭integers‬ ‭ranging‬ ‭from‬ ‭1‬ ‭to‬ ‭10,‬ ‭where‬ ‭1‬ ‭represents‬ ‭the‬
‭lowest priority and 10 represents the highest priority.‬
‭●‬ ‭By‬‭default,‬‭threads‬‭inherit‬‭the‬‭priority‬‭of‬‭their‬‭parent‬‭thread,‬‭usually‬‭set‬‭to‬‭the‬
‭default priority (5).‬

‭getPriority() Method:‬

‭●‬ T‭ he‬‭getPriority()‬‭method‬‭retrieves‬‭the‬‭priority‬‭of‬‭a‬‭thread,‬‭allowing‬‭developers‬
‭to query the current priority setting.‬

‭setPriority() Method:‬

‭●‬ T‭ he‬ ‭setPriority()‬ ‭method‬ ‭sets‬ ‭the‬ ‭priority‬ ‭of‬ ‭a‬‭thread,‬‭enabling‬‭developers‬‭to‬


‭adjust the priority to control thread scheduling.‬

‭Illustrative Example:‬

‭●‬ D ‭ evelopers‬ ‭can‬ ‭create‬ ‭multiple‬ ‭threads‬ ‭with‬ ‭different‬ ‭priorities‬ ‭using‬ ‭the‬
‭setPriority() method.‬
‭●‬ ‭By‬‭observing‬‭the‬‭execution‬‭order‬‭of‬‭threads,‬‭developers‬‭can‬‭understand‬‭how‬
‭thread priorities influence scheduling decisions.‬
‭Code:‬

‭public class Program10 extends Thread {‬


‭public void run() {‬
‭System.out.println("Inside run method");‬
‭}‬
‭public static void main(String[] args) {‬
‭System.out.println("Priorities in Multithreading");‬
‭Program10 t1 = new Program10();‬
‭Program10 t2 = new Program10();‬
‭Program10 t3 = new Program10();‬
‭System.out.println("t1 thread priority: " + t1.getPriority());‬
‭System.out.println("t2 thread priority: " + t2.getPriority());‬
‭System.out.println("t3 thread priority: " + t3.getPriority());‬
‭t1.setPriority(2);‬
‭t2.setPriority(5);‬
‭t3.setPriority(8);‬
‭System.out.println("t1 thread priority: " + t1.getPriority());‬
‭System.out.println("t2 thread priority: " + t2.getPriority());‬
‭System.out.println("t3 thread priority: " + t3.getPriority());‬
‭System.out.println("Currently‬ ‭Executing‬ ‭Thread:‬ ‭"‬ ‭+‬
‭Thread.currentThread().getName());‬
‭System.out.println("Main thread priority: " + Thread.currentThread().getPriority());‬
‭Thread.currentThread().setPriority(10);‬
‭System.out.println("Main thread priority: " + Thread.currentThread().getPriority());‬
‭}‬
‭}‬

‭Output:‬
‭Program 20‬

‭Aim:‬‭Illustrate Deadlock in multithreading.‬

‭Theory:‬

‭ eadlock‬ ‭is‬ ‭a‬ ‭situation‬ ‭in‬ ‭multithreading‬ ‭where‬ ‭two‬ ‭or‬ ‭more‬ ‭threads‬ ‭are‬ ‭blocked‬
D
‭forever, waiting for each other to release resources that they need.‬

‭Resource Acquisition:‬

‭●‬ D‭ eadlock‬ ‭typically‬ ‭occurs‬ ‭when‬ ‭threads‬ ‭acquire‬ ‭resources‬ ‭in‬ ‭a‬
‭non-preemptive‬ ‭manner,‬ ‭meaning‬ ‭they‬ ‭hold‬ ‭onto‬ ‭acquired‬ ‭resources‬ ‭until‬
‭explicitly released.‬

‭Mutual Dependency:‬

‭●‬ D ‭ eadlock‬ ‭arises‬ ‭when‬‭two‬‭or‬‭more‬‭threads‬‭hold‬‭resources‬‭and‬‭wait‬‭for‬‭each‬


‭other to release the resources they need.‬
‭●‬ ‭Each thread remains blocked indefinitely, resulting in a deadlock situation.‬

‭Illustrative Example:‬

‭●‬ A ‭ n‬‭example‬‭of‬‭deadlock‬‭can‬‭be‬‭demonstrated‬‭with‬‭two‬‭threads,‬‭Thread‬‭A‬‭and‬
‭Thread B, both attempting to acquire two locks in a different order.‬
‭●‬ ‭If‬ ‭Thread‬ ‭A‬ ‭holds‬ ‭Lock‬ ‭1‬ ‭and‬ ‭waits‬‭for‬‭Lock‬‭2,‬‭while‬‭Thread‬‭B‬‭holds‬‭Lock‬‭2‬
‭and‬‭waits‬‭for‬‭Lock‬‭1,‬‭a‬‭deadlock‬‭occurs‬‭as‬‭neither‬‭thread‬‭can‬‭proceed‬‭without‬
‭the other releasing the lock it needs.‬

‭Prevention and Resolution:‬

‭●‬ D ‭ eadlocks‬ ‭can‬ ‭be‬ ‭prevented‬ ‭by‬ ‭careful‬ ‭design,‬ ‭avoiding‬ ‭circular‬
‭dependencies‬ ‭and‬ ‭ensuring‬ ‭resource‬ ‭allocation‬ ‭strategies‬ ‭that‬ ‭minimize‬ ‭the‬
‭risk of deadlock.‬
‭●‬ ‭Techniques‬ ‭like‬ ‭timeout‬ ‭mechanisms,‬ ‭resource‬ ‭ordering,‬ ‭and‬ ‭deadlock‬
‭detection algorithms can help in resolving deadlocks.‬
‭Code:‬

‭Demonstrating Deadlock Situation:‬

‭public class Program11a {‬


‭public static Object Lock1 = new Object();‬
‭public static Object Lock2 = new Object();‬
‭public static void main(String args[]) {‬
‭System.out.println("Deadlock Situation");‬
‭ThreadDemo1 T1 = new ThreadDemo1();‬
‭ThreadDemo2 T2 = new ThreadDemo2();‬
‭T1.start();‬
‭T2.start();‬
‭}‬
‭private static class ThreadDemo1 extends Thread {‬
‭public void run() {‬
‭synchronized(Lock1) {‬
‭System.out.println("Thread 1: Holding lock 1...");‬
‭try {‬
‭Thread.sleep(10);‬
‭} catch (InterruptedException e) { }‬
‭System.out.println("Thread 1: Waiting for lock 2...");‬
‭synchronized(Lock2) {‬
‭System.out.println("Thread 1: Holding lock 1 & 2...");‬
‭}‬
‭}‬
‭}‬
‭}‬
‭private static class ThreadDemo2 extends Thread {‬
‭public void run() {‬
‭synchronized(Lock2) {‬
‭System.out.println("Thread 2: Holding lock 2...");‬
‭try {‬
‭Thread.sleep(10);‬
‭} catch (InterruptedException e) { }‬
‭System.out.println("Thread 2: Waiting for lock 1...");‬
‭synchronized(Lock1) {‬
‭System.out.println("Thread 2: Holding lock 1 & 2...");‬
‭}‬
‭}‬
‭}‬
‭} }‬
‭Output:‬

‭Deadlock Solution‬

‭public class Program11b {‬


‭public static Object lock1 = new Object();‬
‭public static Object lock2 = new Object();‬
‭public static void main(String[] args) {‬
‭System.out.println("Deadlock Solution");‬
‭new Thread1().start();‬
‭new Thread2().start();‬
‭}‬
‭private static class Thread1 extends Thread {‬
‭@Override‬
‭public void run() {‬
‭synchronized(lock1) {‬
‭System.out.println("Thread-1 acquired lock1");‬
‭try {‬
‭Thread.sleep(1000);‬
‭} catch (InterruptedException e) {‬
‭System.out.println("Thread-1 interrupted.");‬
‭}‬
‭System.out.println("Thread-1 waiting for lock2");‬
‭synchronized(lock2) {‬
‭System.out.println("Thread-1 acquired lock2");‬
‭try {‬
‭Thread.sleep(1000);‬
‭} catch (InterruptedException e) {‬
‭System.out.println("Thread-1 interrupted.");‬
‭}‬
‭}‬
‭System.out.println("Thread-1 releases lock2");‬
‭}‬
‭System.out.println("Thread-1 releases lock1");‬
‭}‬
‭}‬
‭private static class Thread2 extends Thread {‬
‭@Override‬
‭public void run() {‬
‭synchronized(lock1) {‬
‭System.out.println("Thread-2 acquired lock1");‬
‭try {‬
‭Thread.sleep(1000);‬
‭} catch (InterruptedException e) {‬
‭System.out.println("Thread-2 interrupted.");‬
‭}‬
‭System.out.println("Thread-2 waiting for lock2");‬
‭synchronized(lock2) {‬
‭System.out.println("Thread-2 acquired lock2");‬
‭try {‬
‭Thread.sleep(1000);‬
‭} catch (InterruptedException e) {‬
‭System.out.println("Thread-2 interrupted.");‬
‭}‬
‭}‬
‭System.out.println("Thread-2 releases lock2");‬
‭}‬
‭System.out.println("Thread-2 releases lock1");‬
‭}‬
‭}‬
‭}‬

‭Output:‬
‭Program 21‬

‭Aim:‬‭Implement a program Java Bean to represent person‬‭details‬

‭Theory:‬

J‭ ava‬ ‭Beans‬ ‭are‬ ‭reusable‬ ‭software‬ ‭components‬ ‭that‬ ‭follow‬ ‭specific‬ ‭conventions‬ ‭to‬
‭facilitate‬‭the‬‭development‬‭of‬‭Java‬‭applications.‬‭They‬‭encapsulate‬‭data‬‭and‬‭behavior,‬
‭providing a straightforward way to manage and manipulate objects.‬

‭Person Details Java Bean:‬

‭●‬ T‭ he‬‭program‬‭defines‬‭a‬‭Java‬‭Bean‬‭named‬‭Person‬‭to‬‭represent‬‭details‬‭about‬‭a‬
‭person, such as name, age, gender, and contact information.‬

‭Encapsulation of Data:‬

‭●‬ T‭ he‬ ‭Person‬ ‭Java‬ ‭Bean‬ ‭encapsulates‬ ‭data‬ ‭using‬ ‭private‬ ‭instance‬ ‭variables,‬
‭ensuring data integrity and access control.‬

‭Accessor and Mutator Methods:‬

‭●‬ A‭ ccessor‬‭(get)‬‭and‬‭mutator‬‭(set)‬‭methods‬‭are‬‭implemented‬‭for‬‭each‬‭data‬‭field‬
‭in the Person Java Bean, allowing controlled access to the encapsulated data.‬

‭Serializable Interface:‬

‭●‬ T‭ he‬ ‭Person‬ ‭Java‬ ‭Bean‬ ‭may‬ ‭implement‬ ‭the‬ ‭Serializable‬ ‭interface‬ ‭to‬ ‭support‬
‭serialization,‬ ‭enabling‬ ‭objects‬ ‭to‬ ‭be‬ ‭converted‬ ‭into‬‭a‬‭byte‬‭stream‬‭for‬‭storage‬
‭or transmission.‬

‭Custom Methods:‬

‭●‬ A‭ dditional‬ ‭custom‬ ‭methods‬ ‭can‬ ‭be‬ ‭included‬ ‭in‬ ‭the‬ ‭Person‬ ‭Java‬ ‭Bean‬ ‭to‬
‭perform specific operations or provide functionality related to person details.‬
‭Code:‬

‭ ava Bean Program‬


J
‭import java.io.Serializable;‬
‭public class PersonBean implements Serializable‬
‭{‬
‭private String firstName;‬
‭private String lastName;‬
‭private int age;‬
‭public PersonBean()‬
‭{‬
‭// Default constructor is required for a JavaBean‬
‭}‬
‭// Getter and Setter methods for firstName‬
‭public String getFirstName()‬
‭{‬
‭return firstName;‬
‭}‬
‭public void setFirstName(String firstName)‬
‭{‬
‭this.firstName = firstName;‬
‭}‬
‭// Getter and Setter methods for lastName‬
‭public String getLastName()‬
‭{‬
‭return lastName;‬
‭}‬
‭public void setLastName(String lastName)‬
‭{‬
‭this.lastName = lastName;‬
‭}‬
‭// Getter and Setter methods for age‬
‭public int getAge()‬
‭{‬
‭return age;‬
‭}‬
‭public void setAge(int age)‬
‭{‬
‭this.age = age;‬
‭}‬
‭}‬

‭ ava Bean being Used‬


J
‭public class BeanDemo‬
‭{‬
‭ ublic static void main(String[] args)‬
p
‭{‬
‭// Create an instance of PersonBean‬
‭PersonBean person = new PersonBean();‬

/‭/ Set values using setter methods‬


‭person.setFirstName("Siddhant");‬
‭person.setLastName("Panwar");‬
‭person.setAge(22);‬

/‭/ Get values using getter methods‬


‭System.out.println("First Name: " + person.getFirstName());‬
‭System.out.println("Last Name: " + person.getLastName());‬
‭System.out.println("Age: " + person.getAge());‬
‭}‬
‭}‬

‭Output:‬
‭Program 22‬

‭Aim:‬‭Write a program in java to demonstrate encapsulation‬‭in java beans‬

‭Theory:‬

‭ ncapsulation‬ ‭is‬ ‭a‬ ‭fundamental‬ ‭concept‬ ‭in‬ ‭object-oriented‬ ‭programming‬ ‭that‬


E
‭involves‬‭bundling‬‭data‬‭and‬‭methods‬‭within‬‭a‬‭class‬‭to‬‭control‬‭access‬‭and‬‭ensure‬‭data‬
‭integrity.‬

‭Java Bean Implementation:‬

‭●‬ T‭ he‬ ‭program‬ c‭ reates‬ ‭a‬ ‭Java‬ ‭Bean‬ ‭named‬ ‭Student‬ ‭to‬ ‭demonstrate‬
‭encapsulation,‬ ‭encapsulating‬ ‭student‬ ‭details‬ ‭such‬ ‭as‬ ‭name,‬ ‭age,‬ ‭and‬ ‭roll‬
‭number.‬

‭Private Instance Variables:‬

‭●‬ T‭ he‬‭Student‬‭class‬‭encapsulates‬‭data‬‭using‬‭private‬‭instance‬‭variables‬‭(name,‬
‭age, rollNumber), restricting direct access from outside the class.‬

‭Accessor and Mutator Methods:‬

‭●‬ A‭ ccessor‬ ‭(get)‬ ‭and‬ ‭mutator‬ ‭(set)‬ ‭methods‬ ‭are‬ ‭provided‬ ‭for‬ ‭each‬ ‭private‬
‭instance variable, allowing controlled access to the encapsulated data.‬

‭Data Validation:‬

‭●‬ M‭ utator‬ ‭methods‬ ‭may‬ ‭include‬ ‭data‬ ‭validation‬ ‭logic‬ ‭to‬ ‭ensure‬ ‭that‬ ‭only‬ ‭valid‬
‭data is set for the encapsulated variables, enhancing data integrity.‬

‭Encapsulation Benefits:‬

‭●‬ E‭ ncapsulation‬ ‭ensures‬ ‭that‬ ‭the‬ ‭internal‬ ‭state‬ ‭of‬ ‭the‬ ‭Student‬ ‭object‬ ‭is‬
‭protected, promoting data hiding and reducing coupling between components.‬
‭ ode:‬
C
‭class Student {‬
‭private String name;‬
‭private int age;‬
‭private double gpa;‬
‭public Student() { }‬
‭public Student(String name, int age, double gpa) {‬
‭this.name = name;‬
‭this.age = age;‬
‭if (gpa >= 0.0 && gpa <= 10.0) {‬
‭this.gpa = gpa;‬
‭} else {‬
‭System.out.println("Error: GPA must be between 0.0 and 10.0.");‬
‭}‬
‭}‬
‭public String getName() {‬
‭return name;‬
‭}‬
‭public void setName(String name) {‬
‭if (name != null && !name.isEmpty()) {‬
‭this.name = name;‬
‭} else {‬
‭System.out.println("Error: Name cannot be empty.");‬
‭}‬
‭}‬
‭public int getAge() {‬
‭return age;‬
‭}‬
‭public void setAge(int age) {‬
‭if (age > 0) {‬
‭this.age = age;‬
‭} else {‬
‭System.out.println("Error: Age must be positive.");‬
‭}‬
‭}‬
‭public double getGpa() {‬
‭return gpa;‬
‭}‬
‭public void setGpa(double gpa) {‬
‭if (gpa >= 0.0 && gpa <= 10.0) {‬
‭this.gpa = gpa;‬
‭} else {‬
‭System.out.println("Error: GPA must be between 0.0 and 10.0.");‬
‭}‬
}‭ ‬
‭public String display() {‬
‭return‬‭"Hello,‬‭my‬‭name‬‭is‬‭"‬‭+‬‭getName()‬‭+‬‭".\nI‬‭am‬‭"‬‭+‬‭getAge()‬‭+‬‭"‬‭years‬‭old‬‭and‬
‭my GPA is " + getGpa();‬
‭}‬
‭}‬
‭public class Program13 {‬
‭public static void main(String[] args) {‬
‭System.out.println("Encapsulation in Java Bean");‬
‭Student student = new Student("Kshitiz Sharma", 20, 8.8);‬
‭System.out.println(student.display());‬
‭student.setName("");‬
‭student.setAge(-5);‬
‭student.setGpa(9.0);‬
‭}‬
‭}‬

‭Output:‬
‭Program 23‬

‭ im:‬ ‭Create‬ ‭a‬ ‭database‬ ‭in‬ ‭MySQL‬ ‭using‬ ‭JSP‬ ‭and‬ ‭perform‬ ‭insertion‬ ‭and‬ ‭retrieval‬
A
‭operations.‬

‭Theory:‬

‭ his‬ ‭program‬ ‭demonstrates‬‭the‬‭integration‬‭of‬‭JavaServer‬‭Pages‬‭(JSP)‬‭with‬‭MySQL‬


T
‭to create a database, perform insertion, and retrieval operations.‬

‭Database Creation:‬

‭●‬ J‭ SP‬‭is‬‭utilized‬‭to‬‭execute‬‭SQL‬‭queries‬‭to‬‭create‬‭a‬‭database‬‭and‬‭define‬‭tables‬
‭with specified schema and constraints.‬

‭Insertion Operation:‬

‭●‬ J‭ SP‬‭is‬‭employed‬‭to‬‭execute‬‭SQL‬‭INSERT‬‭queries‬‭to‬‭add‬‭data‬‭records‬‭into‬‭the‬
‭database tables.‬
‭●‬ ‭User‬ ‭input‬ ‭or‬ ‭predefined‬ ‭data‬ ‭can‬ ‭be‬ ‭used‬ ‭for‬ ‭insertion,‬ ‭ensuring‬ ‭dynamic‬
‭data population.‬

‭Retrieval Operation:‬

‭●‬ S ‭ QL‬‭SELECT‬‭queries‬‭are‬‭executed‬‭in‬‭JSP‬‭to‬‭retrieve‬‭data‬‭from‬‭the‬‭database‬
‭tables.‬
‭●‬ ‭Retrieved‬ ‭data‬ ‭can‬ ‭be‬ ‭displayed‬ ‭on‬ ‭the‬ ‭web‬ ‭page‬ ‭or‬ ‭processed‬ ‭further‬ ‭as‬
‭needed.‬

‭Error Handling:‬

‭●‬ E‭ xception‬‭handling‬‭mechanisms‬‭are‬‭implemented‬‭in‬‭JSP‬‭to‬‭manage‬‭potential‬
‭errors during database operations, ensuring robustness and reliability.‬
‭Code:‬

‭index.jsp‬

‭ %@‬
< ‭page‬ ‭language="java"‬ ‭contentType="text/html;‬ ‭charset=UTF-8"‬
‭pageEncoding="UTF-8"%>‬
‭<!DOCTYPE html>‬
‭<html>‬
‭<head>‬
‭<meta charset="UTF-8">‬
‭<title>Insert User</title>‬
‭</head>‬
‭<body>‬
‭<h2>Insert User</h2>‬
‭<form action="insert.jsp" method="post">‬
‭Username: <input type="text" name="username"><br>‬
‭Email: <input type="text" name="email"><br>‬
‭<input type="submit" value="Submit">‬
‭</form>‬
‭</body>‬
‭</html>‬

‭insert.jsp:‬

‭ %@‬
< ‭page‬ ‭language="java"‬ ‭contentType="text/html;‬ ‭charset=UTF-8"‬
‭pageEncoding="UTF-8"%>‬
‭<%@ page import="java.sql.*" %>‬
‭<%@ page import="java.io.PrintWriter" %>‬
‭<%@ page import="java.io.IOException" %>‬
‭<%‬
‭String username = request.getParameter("username");‬
‭String email = request.getParameter("email");‬
‭try {‬
‭Class.forName("com.mysql.jdbc.Driver");‬
‭Connection‬ ‭con‬ ‭=‬
‭DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "root", "");‬
‭Statement stmt = con.createStatement();‬
‭String sql = "INSERT INTO users (username, email) VALUES (?, ?)";‬
‭PreparedStatement pstmt = con.prepareStatement(sql);‬
‭pstmt.setString(1, username);‬
‭pstmt.setString(2, email);‬
‭pstmt.executeUpdate();‬
‭out.println("User inserted successfully.");‬
‭pstmt.close();‬
c‭ on.close();‬
‭} catch (Exception e) {‬
‭out.println("Error: " + e.getMessage()); }‬
‭%>‬

‭retrieve.jsp:‬

‭ %@‬
< ‭page‬ ‭language="java"‬ ‭contentType="text/html;‬ ‭charset=UTF-8"‬
‭pageEncoding="UTF-8"%>‬
‭<%@ page import="java.sql.*" %>‬
‭<%@ page import="java.io.PrintWriter" %>‬
‭<%@ page import="java.io.IOException" %>‬
‭<%‬
‭try {‬
‭Class.forName("com.mysql.jdbc.Driver");‬
‭Connection‬ ‭con‬ ‭=‬
‭DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "root", "");‬
‭Statement stmt = con.createStatement();‬
‭String sql = "SELECT * FROM users";‬
‭ResultSet rs = stmt.executeQuery(sql);‬
‭out.println("<h2>User List</h2>");‬
‭out.println("<table‬
‭border='1'><tr><th>ID</th><th>Username</th><th>Email</th></tr>");‬
‭while (rs.next()) {‬
‭out.println("<tr><td>"‬‭+‬‭rs.getInt("id")‬‭+‬‭"</td><td>"‬‭+‬‭rs.getString("username")‬‭+‬
‭"</td><td>" + rs.getString("email") + "</td></tr>");‬
‭}‬
‭out.println("</table>");‬
‭rs.close();‬
‭stmt.close();‬
‭Output:‬
‭Program 24‬

‭Aim:‬‭Create a Java JSP login and Sign Up form with‬‭Session using MySQL.‬

‭Theory:‬

‭ his‬‭program‬‭demonstrates‬‭the‬‭development‬‭of‬‭a‬‭web‬‭application‬‭using‬‭JavaServer‬
T
‭Pages‬‭(JSP)‬‭to‬‭implement‬‭login‬‭and‬‭sign‬‭up‬‭functionality‬‭with‬‭session‬‭management,‬
‭backed by a MySQL database.‬

‭Login Functionality:‬

‭●‬ U ‭ sers‬ ‭can‬ ‭enter‬ ‭their‬ ‭credentials‬ ‭(username‬ ‭and‬ ‭password)‬ ‭into‬ ‭the‬ ‭login‬
‭form.‬
‭●‬ ‭Upon‬ ‭submission,‬ ‭the‬ ‭program‬ ‭verifies‬ ‭the‬ ‭entered‬ ‭credentials‬ ‭against‬ ‭the‬
‭data stored in the MySQL database.‬
‭●‬ ‭If the credentials match, a session is created to maintain the user's login state.‬

‭Sign Up Functionality:‬

‭●‬ U ‭ sers‬ ‭can‬ ‭register‬ ‭by‬ ‭providing‬ ‭required‬ ‭information‬ ‭(username,‬ ‭password,‬
‭email, etc.) in the sign-up form.‬
‭●‬ ‭Upon‬ ‭submission,‬ ‭the‬ ‭program‬ ‭stores‬ ‭the‬ ‭user's‬ ‭information‬ ‭in‬ ‭the‬ ‭MySQL‬
‭database for future login.‬

‭Session Management:‬

‭●‬ A ‭ ‬‭session‬‭is‬‭created‬‭upon‬‭successful‬‭login,‬‭allowing‬‭users‬‭to‬‭access‬‭restricted‬
‭areas of the application without reauthentication.‬
‭●‬ ‭Sessions are managed to ensure security and prevent unauthorized access.‬

‭MySQL Database Integration:‬

‭●‬ T‭ he‬ ‭program‬ ‭connects‬ ‭to‬ ‭a‬ ‭MySQL‬ ‭database‬ ‭to‬ ‭store‬ ‭user‬ ‭credentials‬ ‭and‬
‭registration details securely.‬
‭Code:‬

‭index.html‬

‭ !DOCTYPE html>‬
<
‭<html>‬
‭<head>‬
‭<meta charset="ISO-8859-1">‬
‭<title>login</title>‬
‭</head>‬
‭<body>‬
‭<form action="login.jsp" method="post">‬
‭User name :<input type="text" name="usr" /><br>‬
‭password :<input type="password" name="password" /><br>‬
‭<input type="submit" />‬
‭</form>‬
‭<p>New user. <a href="register.html">Login Here</a>.‬
‭</body>‬
‭</html>‬

‭login.jsp‬

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


<
‭pageEncoding="ISO-8859-1"%>‬
‭<%@page import="java.sql.*,java.util.*"%>‬
‭<%‬
‭String userid=request.getParameter("userid");‬
‭session.putValue("userid",userid);‬
‭String password=request.getParameter("password");‬
‭Class.forName("com.mysql.jdbc.Driver");‬
‭java.sql.Connection‬ ‭con‬ ‭=‬
‭DriverManager.getConnection("jdbc:mysql://localhost:3306/student","root","");‬
‭Statement st= con.createStatement();‬
‭ResultSet‬ ‭rs=st.executeQuery("select‬ ‭*‬ ‭from‬ ‭users‬ ‭where‬ ‭userid='"+userid+"'‬ ‭and‬
‭password='"+password+"'");‬
‭try{‬
‭rs.next();‬

i‭f(rs.getString("password").equals(password)&&rs.getString("userid").equals(userid))‬
‭{‬
‭out.println("Welcome " +userid);‬
‭}‬
‭else{‬
‭out.println("Invalid password or username.");‬
‭}‬
}‭ ‬
‭catch (Exception e) {‬
‭e.printStackTrace();‬
‭}‬
‭%>‬

‭register.html‬

‭ !DOCTYPE html>‬
<
‭<html>‬
‭<head>‬
‭<meta charset="ISO-8859-1">‬
‭<title>new registration</title>‬
‭</head>‬
‭<body>‬
‭<form action="reg-process.jsp" method="post">‬
‭First name :<input type="text" name="fname" />‬
‭Last name :<input type="text" name="lname" />‬
‭Email ID :<input type="text" name="email" />‬
‭User name :<input type="text" name="userid" />‬
‭password :<input type="password" name="password" />‬
‭<input type="submit" />‬
‭</form>‬
‭</body>‬
‭</html>‬

‭reg-process.jsp‬

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


<
‭pageEncoding="ISO-8859-1"%>‬
‭<%@page import="java.sql.*,java.util.*"%>‬
‭<%‬
‭String fname=request.getParameter("fname");‬
‭String lname=request.getParameter("lname");‬
‭String email=request.getParameter("email");‬
‭String userid=request.getParameter("userid");‬
‭String password=request.getParameter("password");‬
‭try{‬
‭Class.forName("com.mysql.jdbc.Driver");‬
‭Connection‬ ‭conn‬ ‭=‬
‭DriverManager.getConnection("jdbc:mysql://localhost:3306/student", "root", "");‬
‭Statement st=conn.createStatement();‬
i‭nt‬ ‭i=st.executeUpdate("insert‬ ‭into‬
‭users(fname,lname,email,userid,password)values('"+fname+"','"+lname+"','"+email+"'‬
‭,'"+userid+"','"+password+"')");‬
‭out.println("Thank‬ ‭you‬ ‭for‬ ‭register‬ ‭!‬ ‭Please‬ ‭<a‬ ‭href='index.html'>Login</a>‬ ‭to‬
‭continue.");‬
‭}‬
‭catch(Exception e){‬
‭System.out.print(e);‬
‭e.printStackTrace();‬
‭}‬
‭%>‬

‭Output:‬
‭Program 25‬

‭Aim:‬‭Implement Regular Expressions validation before‬‭submitting data in JSP.‬

‭Theory:‬

‭ egular‬ ‭expressions‬ ‭(regex)‬ ‭provide‬ ‭a‬ ‭powerful‬ ‭way‬ ‭to‬ ‭validate‬ ‭and‬ ‭manipulate‬
R
‭strings‬‭in‬‭Java,‬‭including‬‭in‬‭JavaServer‬‭Pages‬‭(JSP),‬‭ensuring‬‭that‬‭user‬‭input‬‭meets‬
‭specified criteria before submission.‬

‭Client-Side Validation:‬

‭●‬ R ‭ egular‬ ‭expressions‬ ‭can‬ ‭be‬ ‭used‬ ‭for‬ ‭client-side‬ ‭validation‬ ‭in‬ ‭JSP‬ ‭forms,‬
‭providing immediate feedback to users without requiring server interaction.‬
‭●‬ ‭JavaScript‬ ‭can‬ ‭be‬ ‭employed‬ ‭to‬ ‭validate‬ ‭input‬ ‭against‬ ‭regex‬ ‭patterns‬ ‭before‬
‭submitting data to the server.‬

‭Server-Side Validation:‬

‭●‬ R ‭ egular‬ ‭expressions‬ ‭can‬ ‭also‬ ‭be‬ ‭utilized‬ ‭for‬ ‭server-side‬ ‭validation‬ ‭in‬ ‭JSP,‬
‭ensuring that data submitted from the client adheres to predefined criteria.‬
‭●‬ ‭In‬‭the‬‭server-side‬‭validation‬‭process,‬‭regex‬‭patterns‬‭are‬‭applied‬‭to‬‭user‬‭input‬
‭to verify its correctness and completeness before processing.‬

‭Error Handling:‬

‭●‬ I‭f‬ ‭user‬ ‭input‬ ‭does‬ ‭not‬ ‭match‬ ‭the‬ ‭specified‬ ‭regex‬ ‭pattern,‬ ‭appropriate‬ ‭error‬
‭messages can be displayed to prompt users to correct their input.‬

‭Enhanced Data Integrity:‬

‭●‬ B‭ y‬ ‭incorporating‬ ‭regular‬ ‭expressions‬ ‭validation‬ ‭in‬ ‭JSP,‬ ‭developers‬ ‭enhance‬


‭data‬‭integrity‬‭and‬‭ensure‬‭that‬‭only‬‭valid‬‭input‬‭is‬‭submitted,‬‭reducing‬‭the‬‭risk‬‭of‬
‭data corruption or misuse.‬
‭ ode:‬
C
‭< !DOCTYPE html >‬
‭<html lang="en">‬
‭<head>‬
‭<meta charset="UTF-8">‬
‭<title>Regualar Expressions Validation</title>‬
‭</head>‬
‭<body>‬
‭<form id="myForm" onsubmit="return validateForm()">‬
‭<label for="name">Name:</label>‬
‭<input type="text" id="name" name="name" required>‬
‭<br>‬
‭<label for="email">Email:</label>‬
‭<input type="text" id="email" name="email" required>‬
‭<br>‬
‭<button type="submit">Submit</button>‬
‭</form>‬
‭<script>‬
‭function validateForm() {‬
‭var name = document.getElementById("name").value;‬
‭var email = document.getElementById("email").value;‬
‭var nameRegex = /^[a-zA-Z ]+$/;‬
‭var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;‬
‭if (!nameRegex.test(name)) {‬
‭alert("Invalid name! Please enter letters and spaces only.");‬
‭return false;‬
‭}if (!emailRegex.test(email)) {‬
‭alert("Invalid email format!");‬
‭return false;‬
‭}return true;‬
‭}‬
‭</script>‬
‭</body>‬
‭</html>‬
‭Output:‬
‭Program 26‬

‭Aim:‬‭Implement Customizable adapter class in a registration‬‭form in JSP.‬

‭Theory:‬

I‭n‬ ‭web‬ ‭development,‬ ‭a‬ ‭registration‬ ‭form‬ ‭is‬ ‭a‬ ‭common‬ ‭feature‬ ‭used‬ ‭to‬ ‭collect‬ ‭user‬
‭information‬‭for‬‭registration‬‭purposes.‬‭By‬‭implementing‬‭a‬‭customizable‬‭adapter‬‭class‬
‭in a JSP registration form, developers can enhance flexibility and maintainability.‬

‭Adapter Class Concept:‬

‭●‬ A ‭ n‬ ‭adapter‬ ‭class‬ ‭acts‬ ‭as‬ ‭an‬ ‭intermediary‬ ‭between‬ ‭the‬ ‭front-end‬ ‭interface‬
‭(JSP form) and the back-end logic (Java servlet or controller).‬
‭●‬ ‭It‬ ‭allows‬ ‭for‬ ‭the‬‭decoupling‬‭of‬‭the‬‭presentation‬‭layer‬‭from‬‭the‬‭business‬‭logic,‬
‭promoting code modularity and reusability.‬

‭Customization Features:‬

‭●‬ T ‭ he‬ ‭customizable‬ ‭adapter‬ ‭class‬ ‭allows‬ ‭developers‬ ‭to‬ ‭modify‬ ‭form‬ ‭fields,‬
‭validation‬ ‭rules,‬ ‭error‬ ‭messages,‬ ‭and‬ ‭submission‬ ‭handling‬ ‭logic‬ ‭without‬
‭directly modifying the JSP code.‬
‭●‬ ‭It‬ ‭enables‬ ‭easy‬ ‭customization‬ ‭of‬ ‭the‬ ‭registration‬ ‭form‬ ‭based‬ ‭on‬ ‭specific‬
‭project requirements or user feedback.‬

‭Separation of Concerns:‬

‭●‬ B‭ y‬ ‭encapsulating‬ ‭registration‬ ‭form‬ ‭logic‬ ‭within‬ ‭the‬‭adapter‬‭class,‬‭developers‬


‭achieve‬ ‭a‬ ‭clean‬ ‭separation‬ ‭of‬ ‭concerns,‬ ‭enhancing‬ ‭code‬ ‭readability‬ ‭and‬
‭maintainability.‬
‭Code:‬

‭register.jsp‬

‭ !DOCTYPE html>‬
<
‭<html>‬

‭<head>‬
‭<title>User Registration</title>‬
‭</head>‬

‭<body>‬
‭<h2>User Registration Form</h2>‬
‭<form action="RegisterServlet" method="post">‬
‭<label for="username">Username:</label>‬
‭<input type="text" id="username" name="username" required><br><br>‬
‭<label for="email">Email:</label>‬
‭<input type="email" id="email" name="email" required><br><br>‬
‭<input type="submit" value="Register">‬
‭</form>‬
‭</body>‬

‭</html>‬

‭RegisterServlet.java‬

i‭mport java.io.IOException;‬
‭import javax.servlet.ServletException;‬
‭import javax.servlet.http.HttpServlet;‬
‭import javax.servlet.http.HttpServletRequest;‬
‭import javax.servlet.http.HttpServletResponse;‬
‭public class RegisterServlet extends HttpServlet {‬
‭protected‬ ‭void‬ ‭doPost(HttpServletRequest‬ ‭request,‬ ‭HttpServletResponse‬‭response)‬
‭throws‬
‭ServletException, IOException {‬
‭// Retrieve form parameters‬
‭String username = request.getParameter("username");‬
‭String email = request.getParameter("email");‬
‭// Call the customizable adapter method‬
‭boolean registrationSuccess = registerUser(username, email);‬
‭// Handle success or failure‬
‭if (registrationSuccess) {‬
‭// Registration successful, redirect to a success page‬
‭response.sendRedirect("registration_success.jsp");‬
}‭ else {‬
‭// Registration failed, redirect to an error page‬
‭response.sendRedirect("registration_error.jsp");‬
‭}‬
‭}‬
‭// Customizable adapter method‬
‭private boolean registerUser(String username, String email) {‬
‭// Customize this method to implement registration logic‬
‭// For example, you could validate inputs, interact with a database, etc.‬
‭// For demonstration purposes, always return true‬
‭return true;‬
‭}‬
‭}‬

‭registration_sucess.jsp‬

‭ !DOCTYPE html>‬
<
‭<html>‬
‭<head>‬
‭<title>Registration Successful</title>‬
‭</head>‬
‭<body>‬
‭<h2>Registration Successful!</h2>‬
‭</body>‬
‭</html>‬

‭Output:‬
‭Program 27‬

‭ im:‬ ‭Implement‬ ‭form‬ ‭validation‬ ‭in‬ ‭marriage‬ ‭application‬ ‭input.html‬ ‭form‬ ‭page‬ ‭using‬
A
‭JavaScript‬
‭1. Person name is required.‬
‭2. Person’s name must have a minimum of 5 characters.‬
‭3. Personage is required.‬
‭4. Personage must be a numeric value.‬
‭5. Personage must be there between 1 to 125.‬

‭Theory:‬

‭ orm‬ ‭validation‬ ‭is‬ ‭crucial‬ ‭in‬ ‭web‬ ‭development‬ ‭to‬ ‭ensure‬ ‭that‬ ‭user‬ ‭input‬ ‭meets‬
F
‭specified‬ ‭criteria‬ ‭before‬ ‭submission.‬ ‭By‬ ‭implementing‬ ‭form‬ ‭validation‬ ‭in‬‭a‬‭marriage‬
‭application‬ ‭input‬ ‭form‬ ‭using‬ ‭JavaScript,‬ ‭developers‬ ‭can‬ ‭enhance‬ ‭user‬ ‭experience‬
‭and data integrity.‬

‭Validation Rules:‬

‭ .‬ P
1 ‭ erson Name Required:‬
‭●‬ ‭JavaScript‬‭code‬‭checks‬‭if‬‭the‬‭person's‬‭name‬‭field‬‭is‬‭empty.‬‭If‬‭empty,‬‭an‬‭error‬
‭message prompts the user to enter their name.‬

‭ .‬ M
2 ‭ inimum Character Length for Name:‬
‭●‬ ‭JavaScript‬ ‭code‬ ‭validates‬ ‭that‬ ‭the‬ ‭person's‬ ‭name‬ ‭has‬ ‭a‬ ‭minimum‬ ‭of‬ ‭5‬
‭characters. If fewer characters are entered, an error message is displayed.‬

‭ .‬ P
3 ‭ erson Age Required:‬
‭●‬ ‭JavaScript‬‭code‬‭ensures‬‭that‬‭the‬‭person's‬‭age‬‭field‬‭is‬‭not‬‭empty.‬‭If‬‭empty,‬‭an‬
‭error message notifies the user to provide their age.‬

‭ .‬ N
4 ‭ umeric Value for Age:‬
‭●‬ ‭JavaScript‬ ‭code‬ ‭verifies‬ ‭that‬ ‭the‬ ‭person's‬ ‭age‬ ‭is‬ ‭a‬ ‭numeric‬ ‭value.‬ ‭If‬
‭non-numeric characters are entered, an error message is shown.‬

‭ .‬ A
5 ‭ ge Range Validation:‬
‭●‬ ‭JavaScript‬‭code‬‭checks‬‭if‬‭the‬‭person's‬‭age‬‭falls‬‭within‬‭the‬‭range‬‭of‬‭1‬‭to‬‭125.‬‭If‬
‭the‬ ‭age‬ ‭is‬ ‭outside‬ ‭this‬ ‭range,‬ ‭an‬ ‭error‬ ‭message‬ ‭informs‬ ‭the‬ ‭user‬ ‭to‬ ‭enter‬ ‭a‬
‭valid age.‬

‭Error Handling:‬
‭●‬ ‭Error‬ ‭messages‬ ‭are‬ ‭dynamically‬‭displayed‬‭near‬‭the‬‭respective‬‭input‬‭fields‬‭to‬
‭guide users on correct input formats or values.‬
‭Code:‬

‭ !DOCTYPE html>‬
<
‭<html lang="en">‬

‭<head>‬
‭<meta charset="UTF-8">‬
‭<meta name="viewport" content="width=device-width, initial-scale=1.0">‬
‭<title>Marriage Application Form</title>‬
‭<style>‬
‭.error {‬
‭color: red;‬
‭}‬

‭.success {‬
‭color: green;‬
‭}‬
‭</style>‬
‭ /head>‬
<

‭<body>‬
‭<h2>Marriage Application Form</h2>‬
‭<form id="marriageForm" onsubmit="return validateForm(event)">‬
‭<label for="personName">Person's Name:</label><br>‬
‭<input type="text" id="personName" name="personName"><br>‬
‭<span id="nameError" class="error"></span><br>‬

‭ label for="personAge">Person's Age:</label><br>‬


<
‭<input type="text" id="personAge" name="personAge"><br>‬
‭<span id="ageError" class="error"></span><br>‬

‭<span id="successMessage" class="success"></span><br>‬

‭ input type="submit" value="Submit">‬


<
‭</form>‬
‭<script>‬
‭function validateForm(event) {‬
‭event.preventDefault(); // Prevent form submission‬

l‭et name = document.getElementById("personName").value.trim();‬


‭let age = document.getElementById("personAge").value.trim();‬
‭let nameError = document.getElementById("nameError");‬
‭let ageError = document.getElementById("ageError");‬
‭let successMessage = document.getElementById("successMessage");‬
‭ ameError.textContent = "";‬
n
‭ageError.textContent = "";‬
‭successMessage.textContent = "";‬

‭if (name === "") {‬


‭nameError.textContent = "Name is required";‬
‭return false;‬
‭} else if (name.length < 5) {‬
‭nameError.textContent = "Name must have at least 5 characters";‬
‭return false;‬
‭}‬

‭if (age === "") {‬


‭ageError.textContent = "Age is required";‬
‭return false;‬
‭} else if (isNaN(age)) {‬
‭ageError.textContent = "Age must be a numeric value";‬
‭return false;‬
‭} else {‬
‭age = parseInt(age);‬
‭if (age < 1 || age > 125) {‬
‭ageError.textContent = "Age must be between 1 and 125";‬
‭return false;‬
‭}‬
‭}‬

s‭ uccessMessage.textContent = "Form submitted successfully!";‬


‭setTimeout(function () {‬
‭successMessage.textContent = "";‬
‭document.getElementById("marriageForm").submit();‬‭//‬‭Submit‬‭the‬‭form‬
‭after success message‬
‭disappears‬
‭}, 3000); // Clear success message after 3 seconds (3000 milliseconds)‬

‭return true;‬
}‭ ‬
‭</script>‬
‭ /body>‬
<

‭</html>‬
‭Output:‬
‭Program 28‬

‭Aim:‬‭Design Servlet Login and Logout using Cookies.‬

‭Theory:‬

‭ ervlet-based‬ ‭login‬ ‭and‬ ‭logout‬ ‭systems‬ ‭are‬ ‭common‬ ‭in‬ ‭web‬ ‭applications‬ ‭to‬
S
‭authenticate‬ ‭users‬ ‭and‬ ‭manage‬ ‭user‬ ‭sessions.‬ ‭Integrating‬ ‭cookies‬ ‭enhances‬ ‭user‬
‭experience by maintaining session state across multiple requests.‬

‭Login Process:‬

‭1.‬ A ‭ uthentication:‬ ‭Upon‬ ‭submitting‬ ‭login‬ ‭credentials,‬ ‭the‬ ‭servlet‬ ‭verifies‬ ‭them‬
‭against stored user data (e.g., in a database).‬
‭2.‬ ‭Cookie‬‭Creation:‬‭If‬‭authentication‬‭is‬‭successful,‬‭the‬‭servlet‬‭creates‬‭a‬‭session‬
‭cookie‬ ‭containing‬ ‭user‬ ‭information‬ ‭(e.g.,‬ ‭user‬ ‭ID‬ ‭or‬ ‭username)‬ ‭and‬ ‭sets‬ ‭an‬
‭expiration time.‬

‭Logout Process:‬

‭1.‬ S ‭ ession‬ ‭Invalidation:‬ ‭When‬ ‭the‬ ‭user‬ ‭logs‬ ‭out,‬ ‭the‬ ‭servlet‬ ‭invalidates‬ ‭the‬
‭session‬ ‭associated‬ ‭with‬ ‭the‬ ‭user,‬ ‭clearing‬ ‭session‬ ‭attributes‬ ‭and‬ ‭destroying‬
‭the session object.‬
‭2.‬ ‭Cookie‬ ‭Deletion:‬ ‭Additionally,‬ ‭the‬ ‭servlet‬ ‭removes‬ ‭the‬ ‭session‬ ‭cookie‬ ‭from‬
‭the‬ ‭client's‬ ‭browser‬ ‭by‬ ‭setting‬ ‭its‬ ‭expiration‬ ‭time‬ ‭to‬ ‭the‬ ‭past‬ ‭or‬ ‭explicitly‬
‭deleting it.‬

‭Error Handling:‬

‭●‬ E‭ rror‬ ‭handling‬ ‭mechanisms‬ ‭are‬ ‭implemented‬ ‭to‬ ‭manage‬ ‭invalid‬ ‭login‬
‭attempts, expired sessions, or other authentication-related issues.‬
‭Code:‬

‭LoginServlet.java‬

i‭mport java.io.IOException;‬
‭import javax.servlet.ServletException;‬
‭import javax.servlet.annotation.WebServlet;‬
‭import javax.servlet.http.Cookie;‬
‭import javax.servlet.http.HttpServlet;‬
‭import javax.servlet.http.HttpServletRequest;‬
‭import javax.servlet.http.HttpServletResponse;‬
‭@WebServlet("/login")‬
‭public class LoginServlet extends HttpServlet {‬
‭private static final long serialVersionUID = 1L;‬
‭protected‬‭void‬‭doPost(HttpServletRequest‬‭request,‬‭HttpServletResponse‬‭response)‬
‭throws‬
‭ServletException, IOException {‬
‭String username = request.getParameter("username");‬
‭String password = request.getParameter("password");‬
‭boolean‬‭isValid‬‭=‬‭username.equals("kshitiz")‬‭&&‬‭password.equals("password123");‬‭//‬
‭Sample‬
‭if (isValid) {‬
‭Cookie cookie = new Cookie("user", username);‬
‭cookie.setMaxAge(60 * 60); // One hour in seconds‬
‭cookie.setPath(request.getContextPath());‬
‭response.addCookie(cookie);‬
‭response.sendRedirect("profile.jsp");‬
‭}‬
‭else {‬
‭response.setContentType("text/html");‬
‭response.getWriter().println("<b>Invalid Login!</b> Please try again.");‬
‭}‬
‭}‬
‭}‬

‭LogoutServlet.java‬

i‭mport java.io.IOException;‬
‭import javax.servlet.ServletException;‬
‭import javax.servlet.annotation.WebServlet;‬
‭import javax.servlet.http.Cookie;‬
‭import javax.servlet.http.HttpServlet;‬
‭import javax.servlet.http.HttpServletRequest;‬
‭import javax.servlet.http.HttpServletResponse;‬
‭ WebServlet("/logout")‬
@
‭public class LogoutServlet extends HttpServlet {‬
‭private static final long serialVersionUID = 1L;‬
‭protected‬‭void‬‭doGet(HttpServletRequest‬‭request,‬‭HttpServletResponse‬‭response)‬
‭throws ServletException,‬
‭IOException {‬
‭Cookie[] cookies = request.getCookies();‬
‭Cookie userCookie = null;‬
‭if (cookies != null) {‬
‭for (Cookie cookie : cookies) {‬
‭if (cookie.getName().equals("user")) {‬
‭userCookie = cookie;‬
‭break;‬
‭}‬
‭}‬
‭}‬
‭if (userCookie != null) {‬
‭userCookie.setMaxAge(0);‬
‭userCookie.setPath(request.getContextPath());‬
‭response.addCookie(userCookie);‬
‭}‬
‭response.sendRedirect("login.jsp");‬
‭}‬
‭}‬

‭profile.jsp:‬

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


<
‭pageEncoding = "UTF-8" %>‬
‭< !DOCTYPE html >‬
‭<html>‬
‭<head>‬
‭<title>Profile Page</title>‬
‭</head>‬
‭<body>‬
‭<%‬
‭Cookie[] cookies=request.getCookies();‬
‭String username=null;‬
‭if (cookies !=null) {‬
‭for (Cookie cookie : cookies) {‬
‭if (cookie.getName().equals("user")) {‬
‭username = cookie.getValue();‬
‭break;‬
‭}‬
}‭ ‬
‭}‬
‭if (username==null) {‬
‭response.sendRedirect("login.jsp");‬
‭return;‬
}‭ ‬
‭%>‬
‭Hi, <%= username %>! <br>‬
‭This is your profile page. You can access protected resources here.‬
‭<br>‬
‭<a href="logout">Logout</a>‬
‭</body>‬
‭</html>‬

‭login.jsp:‬

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


<
‭pageEncoding = "UTF-8" %>‬
‭< !DOCTYPE html >‬
‭<html>‬
‭<head>‬
‭<title>Login Page</title>‬
‭</head>‬
‭<body>‬
‭<% String error = request.getParameter("error"); %>‬
‭<% if (error != null && error.equals("invalid")) { %>‬
‭<b>Invalid Login!</b> Please try again.‬
‭<% } %>‬
‭<br>‬
‭<form action="login" method="post">‬
‭Username: <input type="text" name="username" required><br><br>‬
‭Password: <input type="password" name="password" required><br><br>‬
‭<input type="submit" value="Login">‬
‭</form>‬
‭</body>‬
‭</html>‬
‭Output:‬
‭Program 29‬

‭ im:‬‭Create‬‭a‬‭servlet‬‭that‬‭prints‬‭all‬‭the‬‭request‬‭headers‬‭it‬‭receives,‬‭along‬‭with‬‭their‬
A
‭associated values.‬

‭Theory:‬

‭ ‬ ‭servlet‬ ‭can‬ ‭access‬ ‭and‬ ‭print‬ ‭request‬ ‭headers‬ ‭to‬ ‭gather‬ ‭information‬ ‭about‬ ‭client‬
A
‭requests, such as user-agent details, content type, and cookies.‬

‭Accessing Request Headers:‬

‭1.‬ H ‭ ttpServletRequest‬ ‭Object:‬ ‭The‬ ‭servlet‬ ‭retrieves‬ ‭the‬ ‭HttpServletRequest‬


‭object, which encapsulates the client's request information.‬
‭2.‬ ‭getHeaderNames()‬‭Method:‬‭The‬‭servlet‬‭calls‬‭the‬‭getHeaderNames()‬‭method‬
‭of‬ ‭the‬ ‭HttpServletRequest‬ ‭object‬ ‭to‬ ‭obtain‬ ‭an‬ ‭enumeration‬ ‭of‬ ‭all‬ ‭header‬
‭names.‬
‭3.‬ ‭Iterating‬ ‭Through‬ ‭Headers:‬ ‭Using‬ ‭the‬ ‭enumeration,‬ ‭the‬ ‭servlet‬ ‭iterates‬
‭through‬ ‭each‬ ‭header‬ ‭name‬ ‭and‬ ‭retrieves‬ ‭its‬ ‭associated‬ ‭value‬ ‭using‬ ‭the‬
‭getHeader() method.‬

‭Printing Headers:‬

‭●‬ T‭ he‬‭servlet‬‭prints‬‭each‬‭header‬‭name-value‬‭pair‬‭to‬‭the‬‭servlet‬‭output‬‭stream‬‭or‬
‭logs it for debugging purposes.‬

‭Error Handling:‬

‭●‬ E‭ xception‬ ‭handling‬ ‭mechanisms‬ ‭are‬ ‭implemented‬ ‭to‬ ‭handle‬‭potential‬‭errors,‬


‭such‬‭as‬‭null‬‭pointer‬‭exceptions‬‭when‬‭accessing‬‭headers‬‭that‬‭are‬‭not‬‭present‬
‭in the request.‬
‭Code:‬

i‭mport java.io.IOException;‬
‭import java.io.PrintWriter;‬
‭import javax.servlet.ServletException;‬
‭import javax.servlet.annotation.WebServlet;‬
‭import javax.servlet.http.HttpServlet;‬
‭import javax.servlet.http.HttpServletRequest;‬
‭import javax.servlet.http.HttpServletResponse;‬
‭@WebServlet("/PrintHeadersServlet")‬
‭public class PrintHeadersServlet extends HttpServlet {‬
‭private static final long serialVersionUID = 1L;‬
‭protected void doGet(HttpServletRequest request, HttpServletResponse response)‬
‭throws ServletException, IOException‬
‭{‬
‭response.setContentType("text/html");‬
‭PrintWriter out = response.getWriter();‬
‭out.println("<html>‬

‭<head>‬
‭<title>Request Headers</title>‬
‭</head>‬

‭<body>");‬
‭out.println("<h2>Request Headers:</h2>");‬
‭out.println("<ul>");‬
‭// Get all the header names‬
‭java.util.Enumeration<String> headerNames = request.getHeaderNames();‬
‭while (headerNames.hasMoreElements()) {‬
‭String headerName = headerNames.nextElement();‬
‭// Get all the values for each header name‬
‭java.util.Enumeration<String>‬ ‭headerValues‬ ‭=‬
‭request.getHeaders(headerName);‬
‭while (headerValues.hasMoreElements()) {‬
‭String headerValue = headerValues.nextElement();‬
‭out.println("<li><b>" + headerName + ":</b> " + headerValue + "</li>");‬
‭}‬
‭}‬
‭out.println("</ul>");‬
‭out.println("</body>‬

‭ /html>");‬
<
‭}‬
‭ rotected void doPost(HttpServletRequest request, HttpServletResponse response)‬
p
‭throws ServletException, IOException‬
‭{‬
‭doGet(request, response);‬
‭}‬
‭}‬

‭Output:‬
‭Program 30‬

‭ im:‬‭Create‬‭a‬‭servlet‬‭that‬‭recognizes‬‭a‬‭visitor‬‭for‬‭the‬‭first‬‭time‬‭to‬‭a‬‭web‬‭application‬
A
‭and‬‭responds‬‭by‬‭saying‬‭“Welcome,‬‭you‬‭are‬‭visiting‬‭for‬‭the‬‭first‬‭time”.‬‭When‬‭the‬‭page‬
‭is visited for the second time, it should say “Welcome Back”.‬

‭Theory:‬

‭ ervlets‬ ‭can‬ ‭track‬ ‭visitors‬ ‭to‬ ‭a‬ ‭web‬ ‭application‬ ‭by‬‭utilizing‬‭session‬‭management‬‭to‬


S
‭store visitor information across requests.‬

‭Visitor Recognition Logic:‬

‭1.‬ S ‭ ession‬‭Tracking:‬‭Upon‬‭the‬‭first‬‭visit,‬‭the‬‭servlet‬‭creates‬‭a‬‭session‬‭object‬‭to‬
‭store visitor information.‬
‭2.‬ ‭Session‬‭Attribute:‬‭In‬‭the‬‭session‬‭object,‬‭a‬‭boolean‬‭attribute‬‭(e.g.,‬‭"firstVisit")‬
‭is set to true to indicate the visitor's first visit.‬
‭3.‬ ‭Response‬ ‭Generation:‬ ‭Based‬ ‭on‬ ‭the‬ ‭"firstVisit"‬ ‭attribute,‬ ‭the‬ ‭servlet‬
‭dynamically generates a response message:‬
‭●‬ ‭If‬ ‭"firstVisit"‬ ‭is‬ ‭true,‬ ‭the‬ ‭servlet‬ ‭responds‬ ‭with‬ ‭"Welcome,‬ ‭you‬ ‭are‬
‭visiting for the first time".‬
‭●‬ ‭If‬‭"firstVisit"‬‭is‬‭false‬‭(indicating‬‭a‬‭returning‬‭visitor),‬‭the‬‭servlet‬‭responds‬
‭with "Welcome Back".‬

‭Session Management:‬

‭●‬ T‭ he‬ ‭session‬ ‭object‬ ‭persists‬ ‭across‬ ‭multiple‬ ‭requests‬ ‭from‬ ‭the‬ ‭same‬ ‭client,‬
‭enabling the servlet to maintain visitor state.‬

‭Error Handling:‬

‭●‬ E‭ xception‬ ‭handling‬ ‭mechanisms‬ ‭are‬ ‭implemented‬ ‭to‬ ‭handle‬ ‭potential‬ ‭errors‬
‭during session creation and attribute retrieval.‬
‭Code:‬

i‭mport java.io.IOException;‬
‭import jakarta.servlet.ServletException;‬
‭import jakarta.servlet.annotation.WebServlet;‬
‭import jakarta.servlet.http.HttpServlet;‬
‭import jakarta.servlet.http.HttpServletRequest;‬
‭import jakarta.servlet.http.HttpServletResponse;‬
‭import jakarta.servlet.http.HttpSession;‬
‭@WebServlet("/visit")‬
‭public class FirstTimeVisitor extends HttpServlet {‬
‭protected‬‭void‬‭doGet(HttpServletRequest‬‭request,‬‭HttpServletResponse‬‭response)‬
‭throws ServletException,‬
‭IOException {‬
‭HttpSession session = request.getSession();‬
‭if (session.getAttribute("visited") == null) {‬
‭session.setAttribute("visited", true);‬
‭response.getWriter().println("Welcome, you are visiting for the first time!");‬
‭}‬
‭else {‬
‭response.getWriter().println("Welcome Back!");‬
‭}‬
‭}‬
‭}‬

‭Output:‬
‭Program 31‬

‭Aim:‬‭Create User Registration using Jsp, Servlet and‬‭Jdbc.‬

‭Theory:‬

‭ ser‬‭registration‬‭functionality‬‭is‬‭essential‬‭for‬‭web‬‭applications‬‭to‬‭onboard‬‭new‬‭users.‬
U
‭Combining‬ ‭JSP‬ ‭for‬ ‭presentation,‬ ‭Servlet‬ ‭for‬ ‭handling‬ ‭requests,‬ ‭and‬ ‭JDBC‬ ‭for‬
‭database interaction enables developers to create a robust user registration system.‬

‭Front-End with JSP:‬

‭1.‬ R ‭ egistration‬ ‭Form:‬ ‭A‬ ‭JSP‬ ‭page‬ ‭contains‬ ‭HTML‬ ‭forms‬ ‭for‬ ‭users‬ ‭to‬ ‭input‬
‭registration details such as username, password, email, etc.‬
‭2.‬ ‭Client-Side‬‭Validation:‬‭JavaScript‬‭or‬‭HTML5‬‭validation‬‭ensures‬‭data‬‭integrity‬
‭before submission.‬

‭Back-End with Servlet:‬

‭1.‬ F ‭ orm‬ ‭Submission‬ ‭Handling:‬ ‭A‬ ‭Servlet‬ ‭receives‬ ‭form‬ ‭submission‬ ‭requests‬
‭and processes the user registration data.‬
‭2.‬ ‭Input‬ ‭Sanitization:‬ ‭Servlets‬ ‭sanitize‬ ‭and‬ ‭validate‬ ‭user‬‭input‬‭to‬‭prevent‬‭SQL‬
‭injection and other security vulnerabilities.‬

‭Database Interaction with JDBC:‬

‭1.‬ C ‭ onnection‬ ‭Establishment:‬ ‭JDBC‬ ‭connects‬ ‭the‬ ‭web‬ ‭application‬ ‭to‬ ‭the‬
‭backend database (e.g., MySQL, PostgreSQL).‬
‭2.‬ ‭Data‬ ‭Insertion:‬ ‭The‬ ‭Servlet‬ ‭uses‬ ‭JDBC‬ ‭to‬ ‭execute‬‭SQL‬‭INSERT‬‭queries‬‭to‬
‭add user registration data to the database.‬
‭Code:‬

‭registration.jsp‬

‭ !DOCTYPE html>‬
<
‭<html>‬

‭<head>‬
‭<title>User Registration</title>‬
‭</head>‬

‭<body>‬
‭<h2>User Registration</h2>‬
‭<form action="RegisterServlet" method="post">‬
‭Username: <input type="text" name="username" required><br>‬
‭Password: <input type="password" name="password" required><br>‬
‭<input type="submit" value="Register">‬
‭</form>‬
‭</body>‬

‭</html>‬

‭RegisterServlet.java‬

i‭mport java.io.IOException;‬
‭import java.io.PrintWriter;‬
‭import java.sql.Connection;‬
‭import java.sql.DriverManager;‬
‭import java.sql.PreparedStatement;‬
‭import javax.servlet.ServletException;‬
‭import javax.servlet.annotation.WebServlet;‬
‭import javax.servlet.http.HttpServlet;‬
‭import javax.servlet.http.HttpServletRequest;‬
‭import javax.servlet.http.HttpServletResponse;‬
‭@WebServlet("/RegisterServlet")‬
‭public class RegisterServlet extends HttpServlet {‬
‭private static final long serialVersionUID = 1L;‬
‭protected void doPost(HttpServletRequest request, HttpServletResponse response)‬
‭throws ServletException, IOException {‬
‭response.setContentType("text/html");‬
‭PrintWriter out = response.getWriter();‬
‭String username = request.getParameter("username");‬
‭String password = request.getParameter("password");‬
‭try {‬
‭ lass.forName("com.mysql.cj.jdbc.Driver");‬
C
‭Connection con =‬
‭DriverManager.getConnection("jdbc:mysql://localhost:3306/your_database_name",‬
‭"your_username",‬
‭"your_password");‬
‭PreparedStatement‬ ‭ps‬ ‭=‬ ‭con.prepareStatement("insert‬ ‭into‬
‭users(username,password)‬
‭values(?,?)");‬
‭ps.setString(1, username);‬
‭ps.setString(2, password);‬
‭int i = ps.executeUpdate();‬
‭if (i > 0) {‬
‭out.println("You are successfully registered!");‬
‭}‬
‭} catch (Exception e2) {‬
‭System.out.println(e2);‬
‭}‬
‭out.close();‬
‭}‬
‭}‬

‭Output:‬
‭Program 32‬

‭ im:‬‭Create‬‭Employee‬‭Registration‬‭Form‬‭using‬‭a‬‭combination‬‭of‬‭JSP,‬‭Servlet,‬‭JDBC‬
A
‭and MySQL database.‬

‭Theory:‬

‭ he‬ ‭Employee‬ ‭Registration‬ ‭Form‬ ‭is‬ ‭a‬ ‭crucial‬ ‭feature‬ ‭for‬ ‭organizations‬ ‭to‬ ‭onboard‬
T
‭new‬ ‭employees.‬ ‭By‬ ‭combining‬ ‭JSP‬ ‭for‬ ‭presentation,‬ ‭Servlet‬ ‭for‬ ‭request‬ ‭handling,‬
‭JDBC‬ ‭for‬‭database‬‭interaction,‬‭and‬‭MySQL‬‭for‬‭data‬‭storage,‬‭developers‬‭can‬‭create‬
‭a robust employee registration system.‬

‭Front-End with JSP:‬

‭1.‬ R ‭ egistration‬ ‭Form‬ ‭Design:‬ ‭A‬ ‭JSP‬ ‭page‬ ‭is‬ ‭designed‬ ‭with‬ ‭HTML‬ ‭forms‬ ‭to‬
‭collect employee details like name, email, department, etc.‬
‭2.‬ ‭Client-Side‬‭Validation:‬‭JavaScript‬‭or‬‭HTML5‬‭validation‬‭ensures‬‭data‬‭integrity‬
‭and improves user experience.‬

‭Back-End with Servlet:‬

‭1.‬ F ‭ orm‬ ‭Submission‬ ‭Handling:‬ ‭A‬ ‭Servlet‬ ‭receives‬ ‭form‬ ‭submission‬ ‭requests‬
‭and processes the employee registration data.‬
‭2.‬ ‭Input‬ ‭Sanitization:‬ ‭Servlets‬ ‭sanitize‬ ‭and‬ ‭validate‬ ‭user‬ ‭input‬ ‭to‬ ‭prevent‬
‭security vulnerabilities like SQL injection.‬

‭Database Interaction with JDBC:‬

‭1.‬ C ‭ onnection‬ ‭Establishment:‬ ‭JDBC‬ ‭connects‬ ‭the‬ ‭web‬ ‭application‬ ‭to‬ ‭the‬
‭MySQL database.‬
‭2.‬ ‭Data‬ ‭Insertion:‬ ‭The‬ ‭Servlet‬ ‭uses‬ ‭JDBC‬ ‭to‬ ‭execute‬‭SQL‬‭INSERT‬‭queries‬‭to‬
‭add employee registration data to the MySQL database.‬
‭Code:‬

‭registrationForm.jsp‬

‭ !DOCTYPE html>‬
<
‭<html>‬
‭<head>‬
‭<title>Employee Registration Form</title>‬
‭</head>‬

‭<body>‬
‭<h2>Employee Registration Form</h2>‬
‭<form action="RegistrationServlet" method="post">‬
‭Name: <input type="text" name="name"><br>‬
‭Email: <input type="email" name="email"><br>‬
‭Department: <input type="text" name="department"><br>‬
‭<input type="submit" value="Register">‬
‭</form>‬
‭</body>‬

‭</html>‬

‭RegistrationServlet.java‬

i‭mport java.io.IOException;‬
‭import java.sql.Connection;‬
‭import java.sql.DriverManager;‬
‭import java.sql.PreparedStatement;‬
‭import javax.servlet.ServletException;‬
‭import javax.servlet.annotation.WebServlet;‬
‭import javax.servlet.http.HttpServlet;‬
‭import javax.servlet.http.HttpServletRequest;‬
‭import javax.servlet.http.HttpServletResponse;‬
‭@WebServlet("/RegistrationServlet")‬
‭public class RegistrationServlet extends HttpServlet {‬
‭private static final long serialVersionUID = 1L;‬
‭protected‬ ‭void‬ ‭doPost(HttpServletRequest‬ ‭request,‬ ‭HttpServletResponse‬‭response)‬
‭throws‬
‭ServletException, IOException {‬
‭String name = request.getParameter("name");‬
‭String email = request.getParameter("email");‬
‭String department = request.getParameter("department");‬
‭try {‬
‭Class.forName("com.mysql.jdbc.Driver");‬
‭ onnection con =‬
C
‭DriverManager.getConnection("jdbc:mysql://localhost:3306/yourdatabase",‬
‭"username",‬
‭"password");‬
‭PreparedStatement‬ ‭ps‬ ‭=‬ ‭con.prepareStatement("INSERT‬ ‭INTO‬ ‭employee‬ ‭(name,‬
‭email,‬
‭department) VALUES (?, ?, ?)");‬
‭ps.setString(1, name);‬
‭ps.setString(2, email);‬
‭ps.setString(3, department);‬
‭int rowsAffected = ps.executeUpdate();‬
‭if (rowsAffected > 0) {‬
‭response.sendRedirect("registrationSuccess.jsp");‬
‭} else {‬
‭response.sendRedirect("registrationError.jsp");‬
‭}‬
‭con.close();‬
‭} catch (Exception e) {‬
‭e.printStackTrace();‬
‭}‬
‭}‬
‭}‬

‭registrationSuccess.jsp‬

‭ !DOCTYPE html>‬
<
‭<html>‬
‭<head>‬
‭<title>Registration Success</title>‬
‭</head>‬
‭<body>‬
‭<h2>Registration Successful!</h2>‬
‭<a href="registrationForm.jsp">Go back to Registration Form</a>‬
‭</body>‬
‭</html>‬
‭Output:‬
‭Program 33‬

‭ im:‬‭Write‬‭an‬‭applet‬‭for‬‭event‬‭handling‬‭which‬‭prints‬‭a‬‭message‬‭when‬‭clicked‬‭on‬‭the‬
A
‭button.‬

‭Theory:‬

‭ vent‬‭handling‬‭in‬‭applets‬‭allows‬‭developers‬‭to‬‭respond‬‭to‬‭user‬‭interactions‬‭such‬‭as‬
E
‭mouse‬ ‭clicks,‬ ‭keystrokes,‬ ‭or‬ ‭button‬ ‭presses.‬ ‭Creating‬ ‭an‬ ‭applet‬ ‭for‬‭event‬‭handling‬
‭enables developers to implement interactive functionality and engage users.‬

‭Applet Initialization:‬

‭1.‬ A ‭ pplet‬ ‭Class:‬ ‭The‬ ‭program‬ ‭defines‬ ‭a‬ ‭class‬ ‭that‬ ‭extends‬ ‭the‬
‭java.applet.Applet class.‬
‭2.‬ ‭Initialization:‬ ‭The‬ ‭init()‬ ‭method‬ ‭of‬ ‭the‬ ‭Applet‬ ‭class‬ ‭initializes‬ ‭the‬ ‭applet,‬
‭setting up any necessary resources or parameters.‬

‭Button Creation:‬

‭1.‬ A ‭ WT‬ ‭Button‬ ‭Component:‬ ‭The‬ ‭program‬‭utilizes‬‭the‬‭AWT‬‭Button‬‭component‬


‭to create a clickable button within the applet.‬
‭2.‬ ‭Button‬ ‭Placement:‬ ‭The‬ ‭button‬ ‭is‬ ‭added‬ ‭to‬ ‭the‬ ‭applet's‬ ‭graphical‬ ‭user‬
‭interface, specifying its position and size.‬

‭Event Handling:‬

‭●‬ T ‭ he‬‭program‬‭implements‬‭an‬‭event‬‭listener‬‭for‬‭the‬‭button‬‭component‬‭to‬‭detect‬
‭when the button is clicked.‬
‭●‬ ‭When‬ ‭the‬‭button‬‭is‬‭clicked,‬‭an‬‭event‬‭handler‬‭method‬‭is‬‭invoked‬‭to‬‭perform‬‭a‬
‭specific action, such as printing a message.‬
‭Program 34‬

‭Aim:‬‭Write a program to Pass Parameters to Applet‬‭in Java‬

‭Theory:‬

‭ assing‬‭parameters‬‭to‬‭an‬‭applet‬‭in‬‭Java‬‭allows‬‭developers‬‭to‬‭customize‬‭its‬‭behavior‬
P
‭or‬ ‭appearance‬‭based‬‭on‬‭external‬‭inputs.‬‭This‬‭enhances‬‭the‬‭versatility‬‭and‬‭flexibility‬
‭of the applet.‬

‭Parameter Passing Process:‬

‭1.‬ H ‭ TML‬‭Embedding:‬‭The‬‭applet‬‭is‬‭embedded‬‭within‬‭an‬‭HTML‬‭document‬‭using‬
‭the <applet> tag.‬
‭2.‬ ‭Parameter‬ ‭Specification:‬ ‭Parameters‬‭are‬‭passed‬‭to‬‭the‬‭applet‬‭as‬‭attributes‬
‭within the <applet> tag.‬
‭3.‬ ‭Accessing‬ ‭Parameters:‬ ‭The‬ ‭applet‬ ‭accesses‬ ‭the‬ ‭passed‬‭parameters‬‭using‬
‭the getParameter() method of the java.applet.Applet class.‬

‭Parameter Customization:‬

‭●‬ D ‭ evelopers‬ ‭can‬ ‭pass‬ ‭various‬ ‭types‬ ‭of‬ ‭parameters‬ ‭to‬ ‭the‬ ‭applet,‬ ‭such‬ ‭as‬
‭strings, integers, or boolean values, to control its behavior or appearance.‬
‭●‬ ‭Parameters‬ ‭can‬ ‭specify‬ ‭settings‬ ‭such‬ ‭as‬‭colors,‬‭dimensions,‬‭text‬‭content,‬‭or‬
‭other configurable properties.‬

‭Dynamic Content Generation:‬

‭●‬ B‭ y‬ ‭passing‬ ‭parameters‬ ‭dynamically,‬ ‭developers‬ ‭can‬ ‭create‬ ‭applets‬ ‭that‬


‭generate‬ ‭content‬ ‭based‬ ‭on‬ ‭user‬ ‭inputs‬ ‭or‬ ‭external‬ ‭conditions,‬ ‭enhancing‬
‭interactivity and customization.‬
‭Program 35‬

‭Aim:‬‭Creating a Simple Banner using Applet in Java.‬

‭Theory:‬

‭ pplets‬ ‭in‬ ‭Java‬ ‭provide‬ ‭a‬ ‭platform‬ ‭for‬ ‭creating‬ ‭interactive‬ ‭graphical‬ ‭applications‬
A
‭embedded‬ ‭within‬ ‭web‬ ‭pages.‬ ‭Developing‬ ‭a‬ ‭simple‬ ‭banner‬ ‭using‬ ‭applets‬ ‭enables‬
‭developers to display dynamic content and enhance user engagement.‬

‭Applet Initialization:‬

‭1.‬ A ‭ pplet‬ ‭Class:‬ ‭The‬ ‭program‬ ‭defines‬ ‭a‬ ‭class‬ ‭that‬ ‭extends‬ ‭the‬
‭java.applet.Applet class.‬
‭2.‬ ‭Initialization:‬ ‭The‬ ‭init()‬ ‭method‬ ‭of‬ ‭the‬ ‭Applet‬ ‭class‬ ‭initializes‬ ‭the‬ ‭applet,‬
‭setting up any necessary resources or parameters.‬

‭Banner Design:‬

‭1.‬ G ‭ raphics‬‭Context:‬‭The‬‭program‬‭utilizes‬‭the‬‭Graphics‬‭object‬‭provided‬‭by‬‭the‬
‭applet to draw graphical elements.‬
‭2.‬ ‭Text‬ ‭Rendering:‬ ‭Using‬ ‭methods‬ ‭like‬ ‭drawString(),‬ ‭the‬‭applet‬‭renders‬‭text‬‭to‬
‭create the banner content.‬
‭3.‬ ‭Color‬ ‭and‬ ‭Font:‬ ‭Developers‬ ‭can‬ ‭specify‬ ‭colors‬ ‭and‬ ‭fonts‬ ‭to‬ ‭customize‬ ‭the‬
‭appearance of the banner.‬

‭Animation (Optional):‬

‭●‬ T‭ o‬ ‭create‬‭an‬‭animated‬‭banner,‬‭developers‬‭can‬‭utilize‬‭techniques‬‭like‬‭the‬‭use‬
‭of threads or timers to update the banner content dynamically.‬
‭Program 36‬

‭ im:‬‭Implement‬‭Painting‬‭using‬‭mouseDragged()‬‭method‬‭of‬‭MouseMotionListener‬‭in‬
A
‭Applet.‬

‭Theory:‬

‭ ainting‬ ‭functionality‬ ‭in‬ ‭applets‬ ‭allows‬ ‭users‬ ‭to‬ ‭draw‬ ‭or‬ ‭sketch‬ ‭on‬ ‭a‬ ‭canvas‬ ‭using‬
P
‭mouse‬ ‭interactions.‬ ‭Utilizing‬ ‭the‬ ‭mouseDragged()‬ ‭method‬ ‭of‬ ‭the‬
‭MouseMotionListener‬ ‭interface‬ ‭enables‬ ‭developers‬ ‭to‬ ‭capture‬ ‭mouse‬ ‭movements‬
‭and render them as drawings on the applet's canvas.‬

‭MouseDragged() Method:‬

‭1.‬ M ‭ ouseMotionListener‬ ‭Interface:‬ ‭The‬ ‭applet‬ ‭implements‬ ‭the‬


‭MouseMotionListener interface to listen for mouse motion events.‬
‭2.‬ ‭mouseDragged()‬‭Method:‬‭The‬‭mouseDragged()‬‭method‬‭is‬‭invoked‬‭when‬‭the‬
‭user presses and drags the mouse cursor.‬
‭3.‬ ‭Capturing‬ ‭Coordinates:‬ ‭Inside‬ ‭the‬ ‭mouseDragged()‬ ‭method,‬ ‭the‬ ‭applet‬
‭captures the x and y coordinates of the mouse cursor's current position.‬
‭4.‬ ‭Drawing‬ ‭Operation:‬ ‭Using‬ ‭the‬ ‭captured‬ ‭coordinates,‬ ‭the‬ ‭applet‬ ‭renders‬ ‭a‬
‭line or shape on the canvas, representing the user's drawing.‬

‭Real-Time Interaction:‬

‭●‬ A‭ s‬ ‭the‬ ‭user‬ c‭ ontinues‬ ‭to‬ ‭drag‬ ‭the‬ ‭mouse‬ ‭cursor,‬ ‭the‬ ‭applet‬ ‭dynamically‬
‭updates‬ ‭the‬ ‭drawing‬ ‭on‬ ‭the‬ ‭canvas,‬ ‭providing‬ ‭real-time‬ ‭interaction‬ ‭and‬
‭feedback.‬

You might also like