Advanced Java Lab - Complete
Advanced Java Lab - Complete
Advanced Java Lab - Complete
Theory:
J ava Socket programming is used for communication between the applications
running on different JRE. Java Socket programming can beconnection-orientedor
connection-less.
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
classisusedtocommunicateclientandserver.Throughthisclass,wecanreadand
writemessage.TheServerSocketclassisusedatserver-side.Theaccept()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:
import java.io.*;
import java.net.*;
{ try
{ // Create server socket
ServerSocket serverSocket = new ServerSocket(12345);
}
catch (IOException e)
{ e.printStackTrace();
}
});
// Start server and client threads
serverThread.start();
clientThread.start();
}
}
Output:
Program 2
Theory:
Java Applet
ppletisaspecialprogramembeddedinthewebpagetogeneratedynamiccontent.
A
It runs inside the browser and works on the client side.
Advantages of Applet
● pplet is initialised.
A
● Applet is started.
● Applet is painted.
● Applet is stopped.
● Applet is destroyed.
Code:
import 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
Theory:
Thread
threadisalightweightsubprocess,thesmallestunitofprocessing.Itisaseparate
A
path of execution.
hreadsareindependent.Ifthereoccursanexceptioninonethread,itdoesn'taffect
T
other threads. It uses a shared memory area.
Multithreading in Java
owever, weusemultithreadingratherthanmultiprocessingbecausethreadsusea
H
shared memoryarea.Theydon'tallocateseparatememoryareassosavememory,
and context-switching between the threads takes less time than the process.
)Threadsareindependent,soitdoesn'taffectotherthreadsifanexceptionoccurs
3
in a single thread.
Code:
Override
@
public void run() {
System.out.println("Printing from Thread " + getName() + ": " + number);
}
thread1.start();
thread2.start();
}
}
Output:
Program 4
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:
import 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
Theory:
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 objectfrom
multiple places. Moreover, it provides easy maintenance.
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
Override
@
public String toString() {
return "Name: " + name + ", Age: " + age;
}
Output:
Program 6
Theory:
atainsertionintoatableusingJSPenablesdeveloperstodynamicallyaddrecords
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. SubmitButton:Userstriggerthedatainsertionprocessbyclickingasubmit
button within the form.
1. R equest Handling: The JSP page retrieves form parameters using the
request.getParameter() method.
2. Database Connection: JSP establishes aconnectiontothedatabaseusing
JDBC.
3. SQL Execution: JSP executes an SQL INSERT query to add data into the
table.
4. ParameterBinding:ParametersareboundtotheSQLquerytopreventSQL
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
Theory:
Front-End Design:
. H
1 TML Form:The JSP page contains an HTML form thatcollects user input.
2. ValidationRules:Inputfieldsareaccompaniedbyvalidationrulesspecifying
required formats, lengths, or data types.
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:
Output:
Program 8
Theory:
servalidationiscrucialinwebapplicationstoensurethatonlyauthorizeduserscan
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:Theinit()methodoftheHttpServletclassinitializestheservlet,
setting up any necessary resources or parameters.
login.jsp:
import 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:
Login view:
Theory:
● T heprogramaimstodemonstratehowservletscansetcookieinformationto
be stored on the client-side browser.
1. Initialization: The servlet initializes by extending the HttpServlet class and
overriding the doGet() or doPost() method.
2. Creating Cookies: Within the servlet, cookies are createdusingtheCookie
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 sentbacktothe
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:
import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;
@WebServlet("/setCookie")
public class SetCookieServlet extends HttpServlet {
@Override
protectedvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)
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
Theory:
● J SPsareusedtocreatedynamicwebpagesbyembeddingJavacodewithin
HTML markup.
● They provide a user-friendly interface, presenting data fetched from the
database via servlets.
Database Connectivity:
Workflow:
UserServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
if ("register".equals(action)) {
register(request, response);
} else if ("login".equals(action)) {
login(request, response);
}
}
rivatevoidregister(HttpServletRequestrequest,HttpServletResponseresponse)
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");
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");
reparedStatementpst=con.prepareStatement("SELECT*FROMusers
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
dimensionsofabox.ThedimensionsoftheBoxarewidth,height,depth.Theclass
shouldhaveamethodthatcanreturnthevolumeofthebox.Createanobjectofthe
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.
● W ithintheBoxclass,amethodisimplementedtocomputethevolumeofthe
box based on its dimensions.
● Thismethodcalculatesthevolumebymultiplyingthewidth,height,anddepth
of the box.
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 ,tasteandsizeasitsattributes.A
A
method called eat() is created which describes the name of the fruit and its taste.
Inheritthesamein2otherclassAppleandOrangeandoverridetheeat()methodto
represent each fruit taste. (Method overriding)
Theory:
his program demonstrates the concepts of inheritance and method overriding in
T
Javabycreatingabaseclass,Fruit,withattributeslikename,taste,andsize,along
with a method called eat().
● 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 ofthefruitandits
taste.
Method Overriding:
● IntheAppleandOrangeclasses,theeat()methodisoverriddentorepresent
the specific taste of each fruit.
● Methodoverridingallowssubclassestoprovidetheirownimplementationofa
method inherited from the superclass, enabling customization based on the
specific characteristics of each fruit.
Testing Functionality:
● O bjectsoftheAppleandOrangeclassesarecreated,andtheeat()methodis
called to showcase the overridden behavior, demonstrating thedistincttaste
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: Writeaprogramtocreateaclassnamedshape.Itshouldcontain2methods-
A
draw() and erase() which should print “Drawing Shape” and “Erasing Shape”
respectively. For this class we have threesubclasses-Circle,TriangleandSquare
andeachclassoverridetheparentclassfunctions-draw()anderase().Thedraw()
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 Squareinthe
followingwayandobservethepolymorphicnatureoftheclassbycallingdraw()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:
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
polymorphicbehavior,executingtheoverriddenmethodsbasedontheactual
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:WriteaProgramtotakecareofNumberFormatExceptionifuserentersvalues
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 heprogrampromptstheusertoinputthenamesandmarksoftwostudents
in three subjects.
● Errorhandlingisimplementedtoensurethattheinputvaluesareintegersand
fall within the range of 0-100.
NumberFormatException Handling:
● If the user enters non-integer values, a NumberFormatException is caught
and appropriate error messages are displayed, prompting the user to enter
valid input.
● 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.
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("Enterthemarksof"+name+"inPhysics,ChemistryandMaths:
");
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
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.
● U sers provide the size of the array and its elements, with indexing starting
from zero.
● Theprogrampromptsforaspecificindextoretrievetheelementstoredatthat
position in the array.
Exception Handling:
● If 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.
● Iftheuserentersnon-integervaluesfortheindex,aNumberFormatException
is caught, and the program prompts the user to enter a valid integer index.
Code:
import 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
Theory:
● D atagram UDP (User Datagram Protocol) socket programming in Java
enables communicationbetweentwoendpointsoveranetworkusingUDP,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 xceptionhandlingmechanismsareimplementedtomanagepotentialerrors,
such as IOExceptions that may occur during socket operations.
Code:
Server Side:
import 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:
import 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
Theory:
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:
import 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:
import 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
Theory:
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.
● Itnotifiestheconsumerthreadafterproducinganitem,allowingittoconsume
from the buffer.
Consumer Thread:
T
● he consumer thread continuously consumes items from the shared buffer.
● Itwaitsfornotificationfromtheproducerthreadwhenthebufferisnon-empty,
indicating that it can consume an item.
Buffer Management:
● T hesharedbufferisimplementedusingadatastructuresuchasanarrayora
queue.
● Buffer access is synchronized to prevent simultaneous access by producer
and consumer threads.
Code:
import 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:
In multithreading, thread priorities determine the order in which threads are
scheduled for execution by the operating system. ThegetPriority()andsetPriority()
methods in Java allow developers to manipulate thread priorities.
● T hread priorities are integers ranging from 1 to 10, where 1 represents the
lowest priority and 10 represents the highest priority.
● Bydefault,threadsinheritthepriorityoftheirparentthread,usuallysettothe
default priority (5).
getPriority() Method:
● T hegetPriority()methodretrievesthepriorityofathread,allowingdevelopers
to query the current priority setting.
setPriority() Method:
Illustrative Example:
● D evelopers can create multiple threads with different priorities using the
setPriority() method.
● Byobservingtheexecutionorderofthreads,developerscanunderstandhow
thread priorities influence scheduling decisions.
Code:
Output:
Program 20
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:
Illustrative Example:
● A nexampleofdeadlockcanbedemonstratedwithtwothreads,ThreadAand
Thread B, both attempting to acquire two locks in a different order.
● If Thread A holds Lock 1 and waitsforLock2,whileThreadBholdsLock2
andwaitsforLock1,adeadlockoccursasneitherthreadcanproceedwithout
the other releasing the lock it needs.
● 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:
Deadlock Solution
Output:
Program 21
Theory:
J ava Beans are reusable software components that follow specific conventions to
facilitatethedevelopmentofJavaapplications.Theyencapsulatedataandbehavior,
providing a straightforward way to manage and manipulate objects.
● T heprogramdefinesaJavaBeannamedPersontorepresentdetailsabouta
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.
● A ccessor(get)andmutator(set)methodsareimplementedforeachdatafield
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 intoabytestreamforstorage
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:
Output:
Program 22
Theory:
● T he program c reates a Java Bean named Student to demonstrate
encapsulation, encapsulating student details such as name, age, and roll
number.
● T heStudentclassencapsulatesdatausingprivateinstancevariables(name,
age, rollNumber), restricting direct access from outside the class.
● 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,mynameis"+getName()+".\nIam"+getAge()+"yearsoldand
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:
Database Creation:
● J SPisutilizedtoexecuteSQLqueriestocreateadatabaseanddefinetables
with specified schema and constraints.
Insertion Operation:
● J SPisemployedtoexecuteSQLINSERTqueriestoadddatarecordsintothe
database tables.
● User input or predefined data can be used for insertion, ensuring dynamic
data population.
Retrieval Operation:
● S QLSELECTqueriesareexecutedinJSPtoretrievedatafromthedatabase
tables.
● Retrieved data can be displayed on the web page or processed further as
needed.
Error Handling:
● E xceptionhandlingmechanismsareimplementedinJSPtomanagepotential
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 withSession using MySQL.
Theory:
hisprogramdemonstratesthedevelopmentofawebapplicationusingJavaServer
T
Pages(JSP)toimplementloginandsignupfunctionalitywithsessionmanagement,
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 sessioniscreateduponsuccessfullogin,allowinguserstoaccessrestricted
areas of the application without reauthentication.
● Sessions are managed to ensure security and prevent unauthorized access.
● 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
if(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
Output:
Program 25
Theory:
egular expressions (regex) provide a powerful way to validate and manipulate
R
stringsinJava,includinginJavaServerPages(JSP),ensuringthatuserinputmeets
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.
● Intheserver-sidevalidationprocess,regexpatternsareappliedtouserinput
to verify its correctness and completeness before processing.
Error Handling:
● If user input does not match the specified regex pattern, appropriate error
messages can be displayed to prompt users to correct their input.
Theory:
In web development, a registration form is a common feature used to collect user
informationforregistrationpurposes.Byimplementingacustomizableadapterclass
in a JSP registration form, developers can enhance flexibility and maintainability.
● 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 thedecouplingofthepresentationlayerfromthebusinesslogic,
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:
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
import 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, HttpServletResponseresponse)
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 inamarriage
application input form using JavaScript, developers can enhance user experience
and data integrity.
Validation Rules:
. P
1 erson Name Required:
● JavaScriptcodechecksiftheperson'snamefieldisempty.Ifempty,anerror
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:
● JavaScriptcodeensuresthattheperson'sagefieldisnotempty.Ifempty,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:
● JavaScriptcodechecksiftheperson'sagefallswithintherangeof1to125.If
the age is outside this range, an error message informs the user to enter a
valid age.
Error Handling:
● Error messages are dynamicallydisplayedneartherespectiveinputfieldsto
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>
return true;
}
</script>
/body>
<
</html>
Output:
Program 28
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. CookieCreation:Ifauthenticationissuccessful,theservletcreatesasession
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
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protectedvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)
throws
ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
booleanisValid=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
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
WebServlet("/logout")
@
public class LogoutServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protectedvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)
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:
login.jsp:
im:Createaservletthatprintsalltherequestheadersitreceives,alongwiththeir
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.
Printing Headers:
● T heservletprintseachheadername-valuepairtotheservletoutputstreamor
logs it for debugging purposes.
Error Handling:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
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:Createaservletthatrecognizesavisitorforthefirsttimetoawebapplication
A
andrespondsbysaying“Welcome,youarevisitingforthefirsttime”.Whenthepage
is visited for the second time, it should say “Welcome Back”.
Theory:
1. S essionTracking:Uponthefirstvisit,theservletcreatesasessionobjectto
store visitor information.
2. SessionAttribute:Inthesessionobject,abooleanattribute(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"isfalse(indicatingareturningvisitor),theservletresponds
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:
import 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 {
protectedvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)
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
Theory:
serregistrationfunctionalityisessentialforwebapplicationstoonboardnewusers.
U
Combining JSP for presentation, Servlet for handling requests, and JDBC for
database interaction enables developers to create a robust user registration system.
1. R egistration Form: A JSP page contains HTML forms for users to input
registration details such as username, password, email, etc.
2. Client-SideValidation:JavaScriptorHTML5validationensuresdataintegrity
before submission.
1. F orm Submission Handling: A Servlet receives form submission requests
and processes the user registration data.
2. Input Sanitization: Servlets sanitize and validate userinputtopreventSQL
injection and other security vulnerabilities.
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 executeSQLINSERTqueriesto
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
import 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:CreateEmployeeRegistrationFormusingacombinationofJSP,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 fordatabaseinteraction,andMySQLfordatastorage,developerscancreate
a robust employee registration system.
1. R egistration Form Design: A JSP page is designed with HTML forms to
collect employee details like name, email, department, etc.
2. Client-SideValidation:JavaScriptorHTML5validationensuresdataintegrity
and improves user experience.
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.
1. C onnection Establishment: JDBC connects the web application to the
MySQL database.
2. Data Insertion: The Servlet uses JDBC to executeSQLINSERTqueriesto
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
import 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, HttpServletResponseresponse)
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:Writeanappletforeventhandlingwhichprintsamessagewhenclickedonthe
A
button.
Theory:
venthandlinginappletsallowsdeveloperstorespondtouserinteractionssuchas
E
mouse clicks, keystrokes, or button presses. Creating an applet foreventhandling
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:
Event Handling:
● T heprogramimplementsaneventlistenerforthebuttoncomponenttodetect
when the button is clicked.
● When thebuttonisclicked,aneventhandlermethodisinvokedtoperforma
specific action, such as printing a message.
Program 34
Theory:
assingparameterstoanappletinJavaallowsdeveloperstocustomizeitsbehavior
P
or appearancebasedonexternalinputs.Thisenhancestheversatilityandflexibility
of the applet.
1. H TMLEmbedding:TheappletisembeddedwithinanHTMLdocumentusing
the <applet> tag.
2. Parameter Specification: Parametersarepassedtotheappletasattributes
within the <applet> tag.
3. Accessing Parameters: The applet accesses the passedparametersusing
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 ascolors,dimensions,textcontent,or
other configurable properties.
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 raphicsContext:TheprogramutilizestheGraphicsobjectprovidedbythe
applet to draw graphical elements.
2. Text Rendering: Using methods like drawString(), theappletrenderstextto
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 createananimatedbanner,developerscanutilizetechniquesliketheuse
of threads or timers to update the banner content dynamically.
Program 36
im:ImplementPaintingusingmouseDragged()methodofMouseMotionListenerin
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:
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.