0% found this document useful (0 votes)
9 views46 pages

Java File

This document is a practical file for an Advanced Java Programming Lab, detailing various experiments conducted by a student named Yash Julka. It includes a list of programming tasks such as implementing constructors, method overriding, polymorphism, exception handling, socket programming, and JSP. Each experiment is accompanied by aims, overviews, and source code examples demonstrating the concepts in Java.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views46 pages

Java File

This document is a practical file for an Advanced Java Programming Lab, detailing various experiments conducted by a student named Yash Julka. It includes a list of programming tasks such as implementing constructors, method overriding, polymorphism, exception handling, socket programming, and JSP. Each experiment is accompanied by aims, overviews, and source code examples demonstrating the concepts in Java.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

ADVANCED JAVA PROGRAMMING LAB

PRACTICAL FILE

Faculty Name: Ms. Sakshi Jha Student’s Name: Yash Julka

Roll No.: 01814812721

Semester: 6

Group: 6 CST1 AIML

Maharaja Agrasen Institute of Technology


Sector – 22, Rohini, New Delhi – 110085
INDEX
Name: Yash Julka

Enrolment Number: 01814812721

Branch: Computer Science and Technology

Group: 6 CST1 AIML

SNo. Experiment Name Date Marks Signature

R1 R2 R3 R4 R5

1. Write a program to
implement parameterized
constructor in Java.
2. Write a program to
implement method
overriding in Java.
3. Write a program to
implement polymorphism
in Java.
4. Write a program to
implement Exception
handling in Java.
5. Write a program to
implement Exception
handling in Java.
6. Write a program to
implement Socket
Programming in Java.
7. Implement Datagram UDP
socket programming in
java.
8. Implement Socket
programming for TCP in
Java Server and Client
Sockets.
9. Implement Producer-
Consumer Problem using
multithreading.
10. Illustrate Priorities in
Multithreading via help of
getPriority() and
setPriority() method.
11. Illustrate Deadlock in
multithreading.
SNo. Experiment Name Date Marks Signature

R1 R2 R3 R4 R5

12 Write a Java program to


demonstrate the use of Java
Beans.
13. Write a program in java to
demonstrate encapsulation
in java beans.

14. Write a Java program to


insert data into a table using
JSP.

15. Implement Regular


Expressions validation
before submitting data in
JSP.
16. Write JSP program to
implement form data
validation.
17. Write a Java program to
show user validation using
Servlet.
18. Write a program to set
cookie information using
Servlet.
19. Design Servlet Login and
Logout using Cookies

20. Create a servlet that


recognizes a visitor for the
first time to a web
application 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”.

21. Develop a small web


program using Servlets,
JSPs with Database
connectivity.
PROGRAM-1

Aim: Write a program to implement parameterized constructor in Java.

Create a class Box that uses a parameterized constructor to initialize the 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.

Overview: A constructor that has parameters is known as parameterized constructor. If we want to


initialize fields of the class with our own values, then use a parameterized constructor.

Syntax of Parameterized Constructor in Java:

class ClassName {
TypeName variable1;
TypeName variable2;
ClassName(TypeName variable1, TypeName variable2)
{ this.variable1 = variable1;
this.variable2 = variable2;
}
}

Source Code:
package Java;
import [Link];

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)
{ [Link]("Parameterized
Constructor"); Scanner s = new
Scanner([Link]); [Link]("Enter the
dimensions: ");
int
w=[Link]();
int h=[Link]();
int d=[Link]();
Box b = new Box(w,h,d);
[Link]("The volume of the box is: "+ [Link]());
}
}
Output:
PROGRAM-2

Aim: Write a program to implement method overriding in Java.

Create a base class Fruit which has name ,taste and size as its attributes. 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.

Overview: Method overriding is a fundamental concept in object-oriented programming (OOP) that allows a
subclass (child class) to provide a specific implementation for a method inherited from its superclass (parent
class). This enables customization of behavior based on the specific subclass without modifying the superclass
itself.

Syntax of Method Overriding in Java:

class ClassName1 {
TypeName variable1;
TypeName variable2;
returnType method (parameters) {}
}
Class ClassName2 extends
ClassName1{ returnType method
(parameters) {}
}

Source Code:
package Java;

class Fruit {
String
name,taste; int
size;
void eat() {
[Link]("Inside Fruit class");
}
}
class Apple extends Fruit
{ Apple (String n, String t, int
s) { name=n;
taste=t;
size=s;
}
void eat() {
[Link]("Name: "+ name +"\nTaste: "+ taste);
}
}
class Orange extends Fruit
{ Orange (String n, String t, int s)
{ name=n;
taste=t;
size=s;
}
void eat() {
[Link]("Name: "+ name +"\nTaste: "+ taste);
}
}

public class Program2 {


public static void main(String[] args)
{ Apple a = new
Apple("Apple","sour",10);
[Link]("Method
Overriding"); [Link]();
}
}

Output:
PROGRAM-3

Aim: Write a program to implement polymorphism in Java.

Create a class named shape. It should contain 2 methods- 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();

Overview: Polymorphism in Java is a concept by which we can perform a single action in different
ways. Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means
many and "morphs" means forms. So polymorphism means many forms. There are two types of
polymorphism in Java: compile-time polymorphism and runtime polymorphism.

Syntax of polymorphism in Java is:

class ClassName1 {}
class ClassName2 extends ClassName1 {}
ClassName1 cn1 = new ClassName2();

Source Code:
package Java;

class Shape
{ void draw() {
[Link]("Drawing Shape");
}
void erase()
{ [Link]("Erasing
Shape");
}
}
class Circle extends Shape
{ void draw() {
[Link]("Drawing Circle");
}
void erase()
{ [Link]("Erasing
Circle");
}
}
class Triangle extends Shape
{ void draw() {
[Link]("Drawing Triangle");
}
void erase() {
[Link]("Erasing Triangle");
}
}
class Square extends Shape
{ void draw() {
[Link]("Drawing Square");
}
void erase()
{ [Link]("Erasing
Square");
}
}

public class Program3 {


public static void main(String[] args)
{ Shape c = new Circle();
Shape t = new Triangle();
Shape s = new Square();
[Link](); [Link]();
[Link](); [Link]();
[Link](); [Link]();
}
}

Output:
PROGRAM-4

Aim: Write a program to implement Exception handling in Java.

Write a Program to take care of Number Format Exception if user enters values 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).

Overview: An exception is an issue (run time error) that occurred during the execution of a program.
When an exception occurred the program gets terminated abruptly and, the code past the line that
generated the exception never gets [Link] exceptions cover almost all the general types of
exceptions that may occur in the programming. However, we sometimes need to create custom
exceptions.

Syntax of Custom Exception in Java is:

public class CustomException extends Exception


{ public CustomException(String
errorMessage) { super(errorMessage);
}
}

Source Code:
package Java;
import [Link];

class ExceptionClass extends Exception


{ public String toString() {
return "Error! Marks are not in the range(1,100)";
}
}
public class Program4 {
Scanner s = new Scanner([Link]);
String name;
float sum=0;
int marks[]=new int[3];
void input() throws ExceptionClass
{ [Link]("Enter name of the Student:
"); name=[Link]();
[Link]("Enter the marks of "+ name +" in Physics, Chemistry and Maths: "); for
(int i=0;i<3; i++) {
marks[i]=[Link]([Link]());
if (marks[i]<0 || marks[i]>100)
{ throw new ExceptionClass();
}
sum+=marks[i];
}
[Link]("Average of marks of "+ name +" is "+ sum/3);
}
public static void main(String[] args)
{ [Link]("NumberFormatException, Custom Exception in
Java"); Program4 a=new Program4();
Program4 b=new Program4();
try {
a. input();
b. input();
}
catch (NumberFormatException n)
{ [Link]("NumberFormatException caught "+ [Link]());
}
catch (ExceptionClass e) {
[Link](e);
}
}
}

Output:
PROGRAM-5

Aim: Write a program to implement Exception handling in Java.

Write a program that takes as input the size of the array and the elements in 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 Number Format
Exception. Use Exception handling mechanisms to handle this exception.

Overview: An exception is an issue (run time error) that occurred during the execution of a program.
When an exception occurred the program gets terminated abruptly and, the code past the line that
generated the exception never gets executed. The ArrayIndexOutOfBoundsException occurs
whenever we are trying to access any item of an array at an index which is not present in the array. In
other words, the index may be negative or exceed the size of an array. The NumberFormatException
is thrown when we try to convert a string into a numeric value such as float or integer, but the format
of the input string is not appropriate or illegal.

Syntax to handle any Exception in Java is:

try {
// Block of code to try
}
catch (Exception e) {
// Block of code to handle errors
}

Source Code:
import [Link];

public class Program5 {


public static void main(String[] args) {
[Link]("ArrayIndexOutOfBoundsException, NumberFormatException in Java"); try
{
Scanner s = new Scanner([Link]);
[Link]("Enter the number of elements in the array:
"); int n=[Link]([Link]());
int arr[]=new int[n];
[Link]("Enter the elements of the array:
"); for (int i=0;i<n;i++) {
arr[i]=[Link]([Link]());
}
[Link]("Enter the index at which element is to be found: ");
int a=[Link]([Link]());
[Link]("Element at index "+ a +" is "+ arr[a]);
}
catch (ArrayIndexOutOfBoundsException a)
{ [Link]("ArrayIndexOutOfBoundsException caught "+ [Link]()); }
catch (NumberFormatException n) {
[Link]("NumberFormatException caught "+ [Link]());
}
}
}

Output:
PROGRAM-6

Aim: Write a program to implement Socket Programming in Java.

Overview-Socket programming empowers us to establish two-way communication channels between


applications running on different hosts over a network. It enables low-level control over network interactions,
offering flexibility but also requiring careful handling of complexities.

Source code-
// A Java program for a
Client import [Link].*;
import [Link].*;

public class Client {


private Socket socket = null;
private DataInputStream input =
null; private DataOutputStream out =
null; public Client(String address, int
port)
{ try {
socket = new Socket(address, port);
[Link]("Connected");
input = new DataInputStream([Link]);
out = new DataOutputStream(
[Link]());
}
catch (UnknownHostException u)
{ [Link](u);
return;
}
catch (IOException i) {
[Link](i);
return;
}
String line = "";
while (![Link]("Over"))
{ try {
line = [Link]();
[Link](line);
}
catch (IOException i) {
[Link](i);
}
}
try
{ [Link]();
[Link]();
[Link]();

}
catch (IOException i) {
[Link](i);
}
}
public static void main(String args[])
{
Client client = new Client("[Link]", 5000);
}
}

Server side code-


// A Java program for a Server
import [Link].*;
import [Link].*;

public class Server


{ private Socket socket = null;
private ServerSocket server = null;
private DataInputStream in =
null; public Server(int port)
{ try
{
server = new ServerSocket(port);
[Link]("Server started");

[Link]("Waiting for a client ...");

socket = [Link]();
[Link]("Client accepted"); in
= new DataInputStream(
new BufferedInputStream([Link]()));

String line = "";


while (![Link]("Over"))
{
try
{
line = [Link]();
[Link](line);

}
catch(IOException i)
{
[Link](i);
}
}
[Link]("Closing connection");
[Link]();
[Link]();
}
catch(IOException i)
{
[Link](i);
}
}
public static void main(String args[]){Server server = new Server(5000);}}
OUTPUT-
PROGRAM 7

AIM: Implement Datagram UDP socket programming in java.


OVERVIEW:
DatagramSockets are Java’s mechanism for network communication via UDP instead of TCP. Java
provides DatagramSocket to communicate over UDP instead of TCP. It is also built on top of IP.
DatagramSockets can be used to both send and receive packets over the Internet. One of the examples
where UDP is preferred over TCP is the live coverage of TV channels.

Implement Datagram UDP socket programming in java.

SOURCE CODE:

Server side code-

import [Link].*;

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


[Link](receivePacket);
String message = new String([Link](), 0, [Link]());

[Link]("Received message from " + [Link]().getHostAddress() + ": " +


message);

}}

Client side code-

import [Link].*; public class


UdpClient{ public static void
main(String[] args) throws
Exception { String message =
"Hello from UDP Client!"; int
port = 5000;
InetAddress serverAddress = [Link]("localhost"); DatagramSocket
clientSocket = new DatagramSocket(); byte[]sendData = [Link]();
DatagramPacket sendPacket = new DatagramPacket(sendData, [Link], serverAddress,
port); [Link](sendPacket); [Link]("Sent message: " + message);
[Link]();} }

OUTPUT:
PROGRAM 8
AIM: Implement Socket programming for TCP in Java Server and Client Sockets.

OVERVIEW:
The Client-Server Model Establishes a two-way communication between a server program and a client
program.
• TCP Sockets: Uses TCP (Transmission Control Protocol) for reliable data transfer with error.

SOURCE CODE:

Server side code:

import [Link].*; import [Link].*;

public class Server {


public static void main(String[] args) throws IOException { int

portNumber = 6789;

try (
ServerSocket serverSocket = new ServerSocket(portNumber);
Socket clientSocket = [Link]();
BufferedReader in = new BufferedReader(new
InputStreamReader([Link]())); PrintWriter out = new
PrintWriter([Link](), true);

){
[Link]("Client connected!"); String message; while

((message = [Link]()) != null) { [Link]("Client: "

+ message); [Link]("Server received: " + message); }

} catch (IOException e) {

[Link]("Server error: " + [Link]()); }

}}
Client side code:

import [Link].*; import [Link].*; 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([Link]())); PrintWriter out = new
PrintWriter([Link](), true);
BufferedReader stdIn = new BufferedReader(new InputStreamReader([Link]))
){
String serverMessage; String userMessage;
while ((serverMessage = [Link]()) != null) { [Link]("Server: " + serverMessage); if
([Link]("quit")) {break; }} [Link](userMessage);
if ([Link]("quit")) {
break; }
serverMessage = [Link]();
[Link]("Server: " + serverMessage); }
} catch (IOException e) {
[Link]("Client error: " + [Link]()); }
}}

OUTPUT:
PROGRAM-9
AIM: Implement Producer-Consumer Problem using multithreading.
OVERVIEW:
The producer-consumer problem is a fundamental challenge in computer science that arises when two
processes share a limited buffer. One process, the producer, creates data and adds it to the buffer. The
other process, the consumer, removes data from the buffer and processes it. The key difficulty is
ensuring synchronization between the producer and consumer to avoid data loss or corruption. This
problem is a classic example of inter-process communication and is essential for understanding
concurrency control in operating systems.

SOURCE CODE:

import [Link]; import

[Link]; import

[Link]; public class

ProducerConsumer { static class Buffer { private final int

size; private final String[] items; private int head = 0;

private int tail = 0; private final Lock lock = new

ReentrantLock(); private final Condition notFull =

[Link](); private final Condition notEmpty =

[Link](); public Buffer(int size) { [Link] =

size; [Link] = new String[size];

public void produce(String item) throws InterruptedException {

[Link](); try { while ((tail + 1) % size

== head) { // Buffer is full, wait for

consumption [Link]();

items[tail] = item; tail = (tail + 1) % size;


[Link](); // Notify waiting consumer

[Link]("Produced: " + item);

} finally { [Link]();

public String consume() throws InterruptedException {

[Link](); try { while (head == tail) { //

Buffer is empty, wait for production

[Link]();

String item = items[head]; head =

(head + 1) % size;

[Link](); // Notify waiting producer

[Link]("Consumed: " + item); return

item;

} finally { [Link]();

public static void main(String[] args) throws InterruptedException

{ int bufferSize = 5;

Buffer buffer = new Buffer(bufferSize);

Thread producerThread = new Thread(() -> {

String[] items = {"Item 1", "Item 2", "Item 3", "Item 4", "Item
5"}; for (String item : items) { try { [Link](item);

[Link](1000); // Simulate production time

} catch (InterruptedException e) {

[Link]();

});

Thread consumerThread = new Thread(() -> {

while (true) { try

{ [Link]();

[Link](500); // Simulate consumption time

} catch (InterruptedException e) {

[Link]();

} });

[Link](); [Link]();

[Link](); [Link]();

}
OUTPUT:
PROGRAM-10
AIM: Illustrate Priorities in Multithreading via help of getPriority() and
setPriority() method.
OVERVIEW:
Java threads have priorities (1-10) influencing CPU access. getPriority() retrieves the current priority,
while setPriority() attempts to change it (actual priority might be lower due to system restrictions). Use
these methods to create scenarios where higher priority threads are more likely to be scheduled first by
the CPU, showcasing the impact of priority on thread execution order.

SOURCE CODE:
public class PriorityDemo {

public static void main(String[] args) {


Thread highPriorityThread = new Thread(() -> {
[Link]("High Priority Thread: Priority - " +
[Link]().getPriority()); // Simulate some work for
(int i = 0; i < 10000; i++) {
[Link](i);
}
});

Thread lowPriorityThread = new Thread(() -> {


[Link]("Low Priority Thread: Priority - " +
[Link]().getPriority()); // Simulate some work for
(int i = 0; i < 100000; i++) {
[Link](i);
}
});

// Set priorities (might be adjusted by the system)


[Link](Thread.MAX_PRIORITY);
[Link](Thread.MIN_PRIORITY);

[Link](); [Link]();
}
}
OUTPUT:
PROGRAM-11
AIM: Illustrate Deadlock in multithreading.
OVERVIEW:
Deadlock in multithreading occurs when two or more threads are permanently blocked, waiting for
resources held by each other. Imagine Thread A holding Resource 1 and waiting for Resource 2 held by
Thread B. Simultaneously, Thread B holds Resource 2 and waits for Resource 1 held by Thread A.
Neither thread can proceed, creating a deadlock. To avoid this, acquire resources in a consistent order or
use techniques like timeouts to prevent indefinite waiting.

SOURCE CODE:
public class ANUDeadlockDemo {

static Object resource1 = new Object(); static


Object resource2 = new Object();

public static void main(String[] args) {


Thread thread1 = new Thread(() -> { synchronized
(resource1) {
[Link]("Thread 1: Acquired resource 1"); try {
[Link](1000); // Simulate work
} catch (InterruptedException e) {
[Link]();
}
[Link]("Thread 1: Waiting for resource 2"); synchronized
(resource2) {
[Link]("Thread 1: Acquired resource 2 (This should not happen due to
deadlock)");
}
}
});

Thread thread2 = new Thread(() -> { synchronized


(resource2) {
[Link]("Thread 2: Acquired resource 2"); try {
[Link](1000); // Simulate work
} catch (InterruptedException e) {
[Link]();
}
[Link]("Thread 2: Waiting for resource 1"); synchronized
(resource1) {
[Link]("Thread 2: Acquired resource 1 (This should not happen due to
deadlock)");
}
}
});

[Link](); [Link]();
}
}
OUTPUT:
PROGRAM-12
AIM: Illustrate use of java beans.
OVERVIEW:
JavaBeans facilitate reusable software components in Java. They encapsulate functionality,
expose properties accessed via getter/setter methods, and handle events. Supporting
customization and design-time features, they follow a lifecycle model and support serialization.
Adhering to naming conventions, JavaBeans ensure interoperability and platform
independence, enabling portable and versatile
component-based development.

SOURCE CODE:

public class PersonBean {


private String name;
private int age;

public PersonBean() {

// Getter method for name


public String getName() {
return name;
}

// Setter method for name


public void setName(String name) {
[Link] = name;
}

// Getter method for age


public int getAge() {
return age;
}

// Setter method for age


public void setAge(int age) {
[Link] = age;
}
}
// [Link]
public class Main {
public static void main(String[] args) {
// Create an instance of PersonBean
PersonBean person = new PersonBean();

// Set properties using setter methods


[Link]("John");
[Link](30);
// Get properties using getter methods
String name = [Link]();
int age = [Link]();

// Print the values


[Link]("Name: " + name);
[Link]("Age: " + age);
}
}

OUTPUT:
PROGRAM-13
AIM: Illustrate use of encapsulation in java beans.
OVERVIEW:
Encapsulation in JavaBeans involves concealing the internal state of objects by
declaring fields as private and providing public methods to access or modify them.
This safeguards data integrity and controls access to properties, promoting
modular design and facilitating reusable software components with well-defined
interfaces and controlled behavior.

SOURCE CODE:

// [Link]
public class PersonBean {
// Private fields
private String name;
private int age;

// Getter method for name


public String getName() {
return name;
}

// Setter method for name


public void setName(String name) {
// Encapsulation: Validation logic can be added here
[Link] = name;
}

// Getter method for age


public int getAge() {
return age;
}

// Setter method for age


public void setAge(int age) {
// Encapsulation: Validation logic can be added here
[Link] = age;
}
}
// [Link]
public class Main {
public static void main(String[] args) {
// Create an instance of PersonBean
PersonBean person = new PersonBean();

// Set properties using setter methods


[Link]("John");
[Link](30);

// Get properties using getter methods


String name = [Link]();
int age = [Link]();

// Print the values


[Link]("Name: " + name);
[Link]("Age: " + age);

}
}

OUTPUT:
PROGRAM-14
AIM: Write a Java program to insert data into a table using JSP.

OVERVIEW:

In JSP, data insertion into a database table typically involves accepting user input through
HTML forms, processing it using JSP, and executing SQL queries to insert the data into the
database. This process integrates presentation (HTML forms) with logic (JSP) and data
manipulation (SQL), enabling dynamic and interactive web applications with data
persistence capabilities.

SOURCE CODE:

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


<%@ page import="[Link]" %>
<%@ page import="[Link]" %>
<%@ page import="[Link]" %>

<%
// Initialize variables
String name = [Link]("name");
int age = [Link]([Link]("age"));

Connection conn = null;


PreparedStatement pstmt = null;

try {
// Obtain DataSource from JNDI (Java Naming and Directory Interface)
Context initContext = new InitialContext();
Context envContext = (Context)[Link]("java:/comp/env");
DataSource dataSource = (DataSource)[Link]("jdbc/myDataSource");

// Establish database connection


conn = [Link]();

// Prepare SQL statement


String sql = "INSERT INTO my_table (name, age) VALUES (?, ?)";
pstmt = [Link](sql);
[Link](1, name);
[Link](2, age);

// Execute the insert statement


int rowsAffected = [Link]();

// Check if insertion was successful


if (rowsAffected > 0) {
[Link]("Data inserted successfully!");
} else {
[Link]("Failed to insert data.");
}
} catch (Exception e) {
[Link]("Error: " + [Link]());
} finally {
// Close resources
if (pstmt != null) [Link]();
if (conn != null) [Link]();
}
%>

OUTPUT:
PROGRAM-15
AIM: Implement Regular Expressions validation before submitting data in JSP.
OVERVIEW:

In JSP, implementing Regular Expressions (regex) validation before submitting data


involves validating user input against predefined patterns to ensure it matches specific
criteria (e.g., email format, password strength). This enhances data integrity and security
by preventing invalid or malicious inputs. Regex validation in JSP typically occurs on the
client-side using JavaScript or on the server-side using Java.

SOURCE CODE:

<!DOCTYPE html>
<html>
<head>
<title>Regex Validation in JSP</title>
</head>
<body>
<h2>Regex Validation in JSP</h2>
<form action="process" method="post">
Name: <input type="text" name="name" required><br>
Age: <input type="text" name="age" required><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

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

@WebServlet("/process")
public class ProcessServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// Retrieve form data
String name = [Link]("name");
String ageStr = [Link]("age");

// Regular expression patterns


Pattern namePattern = [Link]("^[a-zA-Z\\s]+$");
Pattern agePattern = [Link]("^\\d+$");
// Perform validation
if (![Link](name).matches()) {
[Link]().println("Invalid name. Please enter only letters and spaces.");
return;
}

if (![Link](ageStr).matches()) {
[Link]().println("Invalid age. Please enter only positive integers.");
return;
}

// Convert age to integer


int age = [Link](ageStr);

[Link]().println("Data submitted successfully!");


}
}

OUTPUT:
PROGRAM-16
AIM: Write JSP program to implement form data validation.

OVERVIEW:

To implement form data validation in JSP, validate user inputs against predefined criteria
(e.g., required fields, data formats) using JavaScript or server-side logic. Display error
messages for invalid inputs and prevent form submission until all inputs are valid. This
ensures data integrity and enhances user experience by guiding users to provide correct
input.

SOURCE CODE:

<!DOCTYPE html>
<html>
<head>
<title>Form Data Validation in JSP</title>
</head>
<body>
<h2>Form Data Validation in JSP</h2>
<form action="[Link]" method="post">
Name: <input type="text" name="name" required><br>
Age: <input type="text" name="age" required><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
<%@ page language="java" %>
<%@ page import="[Link]" %>
<%@ page import="[Link].*" %>
<%@ page import="[Link].*" %>

<%
String name = [Link]("name");
String ageStr = [Link]("age");

Pattern namePattern = [Link]("^[a-zA-Z\\s]+$");


Pattern agePattern = [Link]("^\\d+$");

if (name == null || [Link]().isEmpty() || ![Link](name).matches()) {


[Link]("Invalid name. Please enter only letters and spaces.");
} else if (ageStr == null || [Link]().isEmpty() || ![Link](ageStr).matches()) {
[Link]("Invalid age. Please enter only positive integers.");
} else {
[Link]("Data submitted successfully!");
}
%>

OUTPUT:
PROGRAM-17
AIM: Write a Java program to show user validation using Servlet.

OVERVIEW:

In a Java Servlet program for user validation, capture user input from a form, then validate
it server-side using predefined criteria (e.g., username availability, password strength). If
validation fails, display error messages to guide the user. Successful validation allows
further processing (e.g., authentication, data processing). This ensures data integrity and
enhances security.

SOURCE CODE:

import [Link].*;
import [Link].*;
import [Link];
import [Link].*;

@WebServlet("/login")
public class UserValidationServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// Retrieve form data
String username = [Link]("username");
String password = [Link]("password");

// Validate user input (e.g., check if username and password are not empty)
if (username != null && ![Link]() && password != null && ![Link]()) {
// Successful validation, perform further processing (e.g., authentication)
// Add your code here...

// Send success response


[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<html><body>");
[Link]("<h2>Login Successful!</h2>");
[Link]("<p>Welcome, " + username + "!</p>");
[Link]("</body></html>");
} else {
// Validation failed, display error message
[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<html><body>");
[Link]("<h2>Login Failed</h2>");
[Link]("<p>Please provide valid username and password.</p>");
[Link]("</body></html>");
}
}
}

OUTPUT:

If the user submits valid data (non-empty username and password), the output will be:
PROGRAM-18
AIM: Write a program to set cookie information using Servlet using java

OVERVIEW:

To set cookie information using a Servlet, retrieve the HttpServletResponse object in the
servlet, then create a Cookie object with desired name-value pairs and additional
attributes if needed (e.g., expiration time, domain). Add the cookie to the response using
HttpServletResponse's addCookie() method. Once set, the cookie will be sent to the
client's browser with subsequent responses, facilitating state management and user
tracking across sessions.

SOURCE CODE:

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

@WebServlet("/setCookie")
public class SetCookieServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// Create a new cookie
Cookie cookie = new Cookie("username", "john_doe");

// Set additional attributes if needed (e.g., expiration time, domain)


// [Link](3600); // Cookie expires in 1 hour
// [Link](".[Link]");

// Add the cookie to the response


[Link](cookie);

// Send a response to indicate successful cookie setting


[Link]("text/html");
[Link]().println("Cookie set successfully!");
}
}

OUTPUT:
PROGRAM-19
AIM: Design Servlet Login and Logout using Cookies

OVERVIEW:

To design a Servlet login and logout system using cookies, authenticate users by
validating their credentials against a database. Upon successful login, set a session cookie
with a unique identifier. Implement a logout mechanism to invalidate the session cookie.
Cookies facilitate user authentication across requests, providing a seamless login
experience, while logout clears the session, enhancing security and user privacy.

SOURCE CODE:

[Link]:
import [Link].*;
import [Link].*;
import [Link];
import [Link].*;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
String username = [Link]("username");
String password = [Link]("password");

// Validate username and password (usually done against a database)


if ("admin".equals(username) && "password123".equals(password)) {
// Create a session cookie
Cookie sessionCookie = new Cookie("session", "authenticated");
[Link](60 * 30); // Cookie expires in 30 minutes
[Link](sessionCookie);

// Redirect to home page after successful login


[Link]("[Link]");
} else {
// Redirect back to login page with error message
[Link]("[Link]?error=1");
}
}
}

[Link]:
import [Link].*;
import [Link].*;
import [Link];
import [Link].*;

@WebServlet("/logout")
public class LogoutServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// Expire the session cookie
Cookie sessionCookie = new Cookie("session", "");
[Link](0); // Set the cookie age to 0 to expire it immediately
[Link](sessionCookie);

// Redirect to login page after logout


[Link]("[Link]");
}
}

OUTPUT:

The output of the provided Servlets will be observed in the browser. Here's how the program flow and
outputs would appear:

1. Login Attempt:
 User enters username and password and submits the login form.
 If the credentials are correct, the user is redirected to the home page ([Link]).
 If the credentials are incorrect, the user is redirected back to the login page ([Link])
with an error message.
2. Logout:
 When the user clicks on the logout link or button, the LogoutServlet is invoked.
 The session cookie is invalidated, and the user is redirected to the login page ([Link]).
3. Output Display:
 If login is successful, the user sees the home page content.
 If login fails, the user is redirected back to the login page with an error message.
 After logout, the user is redirected to the login page.
PROGRAM-20
AIM: To Create a servlet that recognizes a visitor for the first time to a web application 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”.

OVERVIEW:

To create a servlet recognizing a visitor for the first time, store a unique identifier (e.g., IP
address, browser fingerprint) in a cookie upon the initial visit. On subsequent visits,
retrieve the identifier from the cookie. If the identifier exists, greet the visitor with
"Welcome Back"; otherwise, greet them with "Welcome, you are visiting for the first time".
This approach facilitates personalized greetings based on user visits, enhancing user
experience.

SOURCE CODE:

import [Link].*;
import [Link].*;
import [Link];
import [Link].*;

@WebServlet("/welcome")
public class WelcomeServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// Check if the visitor has visited before by checking for a cookie
Cookie[] cookies = [Link]();
boolean visitedBefore = false;

if (cookies != null) {
for (Cookie cookie : cookies) {
if ([Link]().equals("visited") && [Link]().equals("true")) {
visitedBefore = true;
break;
}
}
}

// Set a cookie to mark the visitor's first visit


if (!visitedBefore) {
Cookie visitedCookie = new Cookie("visited", "true");
[Link](365 * 24 * 60 * 60); // Cookie expires in 1 year
[Link](visitedCookie);
// Respond with "Welcome, you are visiting for the first time"
[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<html><body>");
[Link]("<h2>Welcome, you are visiting for the first time</h2>");
[Link]("</body></html>");
} else {
// Respond with "Welcome Back"
[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<html><body>");
[Link]("<h2>Welcome Back</h2>");
[Link]("</body></html>");
}
}
}

OUTPUT:

When the servlet is accessed for the first time, it sets a cookie to mark the visitor's
first visit and responds with:

Upon subsequent visits, the servlet recognizes the visitor based on the presence
of the cookie and responds with:
PROGRAM-21
AIM: Develop a small web program using Servlets, JSPs with Database connectivity.

OVERVIEW:

To develop a small web program using Servlets, JSPs, and Database connectivity, start by
creating Servlets to handle business logic and interact with the database. Use JSPs to
generate dynamic HTML content for presentation. Establish database connectivity using
JDBC to perform database operations. Servlets retrieve data from the database and
forward it to JSPs for rendering, enabling dynamic web content generation based on
database data.

SOURCE CODE:

[Link] (for database connectivity):


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

public class DatabaseConnector {


private static final String URL = "jdbc:mysql://localhost:3306/mydatabase";
private static final String USER = "username";
private static final String PASSWORD = "password";

public static Connection getConnection() throws SQLException {


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

[Link] (a simple JavaBean representing a user):


public class User {
private String username;
private String email;

// Getters and setters


}

[Link] (Data Access Object for interacting with the database):


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

public class UserDAO {


public User getUserByUsername(String username) throws SQLException {
User user = null;
String query = "SELECT * FROM users WHERE username = ?";
try (Connection conn = [Link]();
PreparedStatement pstmt = [Link](query)) {
[Link](1, username);
try (ResultSet rs = [Link]()) {
if ([Link]()) {
user = new User();
[Link]([Link]("username"));
[Link]([Link]("email"));
}
}
}
return user;
}
}
[Link] (JSP for displaying user details):
<%@ page import="UserDAO" %>
<%@ page import="User" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>User Details</title>
</head>
<body>
<%
String username = (String) [Link]("username");
UserDAO userDAO = new UserDAO();
User user = [Link](username);
%>
<h2>User Details</h2>
<p>Username: <%= [Link]() %></p>
<p>Email: <%= [Link]() %></p>
</body>
</html>

[Link] (Servlet for handling user requests):


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

@WebServlet("/user")
public class UserServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
String username = [Link]("username");
[Link]("username", username);
[Link]("[Link]").forward(request, response);
}}
OUTPUT:

You might also like