Advance_Java_Lab_Manual
Advance_Java_Lab_Manual
OF
CIE-306P
MISSION
The Institute shall endeavor to incorporate the following basic missions in the teaching
methodology:
The Institute endeavors to enhance technical and management skills of students so that
they are intellectually capable and competent professionals with Industrial Aptitude to
face the challenges of globalization.
Diversification
Entrepreneurship
The Institute strives to develop potential Engineers and Managers by enhancing their
skills and research capabilities so that they become successful entrepreneurs and
responsible citizens.
MAHARAJA AGRASEN INSTITUTE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
VISION
“To be centre of excellence in education, research and technology
transfer in the field of computer engineering and promote
entrepreneurship and ethical values.”
MISSION
“To foster an open, multidisciplinary and highly collaborative research
environment to produce world-class engineers capable of providing
innovative solutions to real life problems and fulfil societal needs.”
INDEX
1. Introduction to Lab 1
2. Lab Requirements 2
1
2. HARDWARE /SOFTWARE REQUIREMENTS
For Java Programming
JDK, NetBeans ,Tomcat Server
Java Compatible Web Browser
This Compiler has no special hardware requirements as such. Any System with a minimum
4GB RAM and i3 processor can be used for this lab.
2
3. LIST OF EXPERIMENTS (PRESCRIBED BY GGSIPU)
1. Write a Java program to demonstrate the concept of socket programming. (CO1, CO2)
2. Write a Java program to demonstrate the concept of applet programming. (CO1, CO2)
3. Write a Java program to demonstrate the concept of multi-threading. (CO1)
4. Write a Java program to demonstrate the concept of applet. (CO1)
5. Write a Java program to demonstrate the use of Java Beans. (CO3)
6. Write a Java program to insert data into a table using JSP. (CO2, CO3)
7. Write JSP program to implement form data validation. (CO2, CO3)
8. Write a Java program to show user validation using Servlet. (CO2, CO3)
9. Write a program to set cookie information using Servlet. (CO2, CO3)
10. Develop a small web program using Servlets, JSPs with Database connectivity. (CO4)
3
4. Advanced Java Programming (Additional/ Advanced
List of experiments GGSIPU Syllabus)
1. 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.(CO1)
2. 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. (Method overriding)(CO1)
3. Write a program to 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(); (Polymorphism) (CO1)
4. 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) (CO1)
5. 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 NumberFormatException .
Use exception handling mechanisms to handle this exception. (CO1)
6. Implement Datagram UDP socket programming in java. (CO1,CO2)
7. Implement Socket programming for TCP in Java Server and Client Sockets.(CO1,CO2)
8. Write an applet for event handling which prints a message when clicked on the button.(CO1,CO2)
9. Write a program to Pass Parameters to Applet in Java. (CO1)
10. Creating a Simple Banner using Applet in Java.(CO1)
11. Implement Painting using mouseDragged() method of MouseMotionListener in Applet.(CO1)
12. Implement Producer-Consumer Problem using multithreading.(CO1)
13. Illustrate Priorities in Multithreading via help of getPriority() and setPriority() method.(CO1)
17. Create a database in MySQL using JSP and perform insertion and retrieval operations.(CO2)
18. Create a Java JSP login and Sign Up form with Session using MySQL.(CO2)
4
19. Implement Regular Expressions validation before submitting data in JSP.(CO2)
21. Implement form validation in marriage application input.html form page using JavaScript (CO2)
PROJECTS TO BE ALLOTED
Students will be divided into a group of four/five and projects are allotted to those groups. This
project is to be submitted at the end of the semester along with a project report by the individual
student.
List of projects given to the students is summarized as below:
1. Airline Reservation System
2. ATM interface
3. Data visualization software
4. Smart city project
5. Criminal face detection system
6. Currency converter
7. Network packet sniffer
Students can select project work of their own choice subject to the permission of concern faculty.
NOTE: The project is to be made in Java Language preferably.
5
5. FORMAT OF THE LAB RECORD TO BE PREPARED BY
THE STUDENTS
1. The front page of the lab record prepared by the students should have a cover page as displayed
below.
2. The second page in the record should be the index as displayed below.
PRACTICAL RECORD
6
Index
PROJECT DETAILS
1. TITLE :
2. MEMBERS IN THE PROJECT GROUP :
3. PROJECT REPORT ATTACHED :
a) YES b) NO
4. SOFT COPY SUBMITTED :
a) YES b) NO
7
6. MARKING SCHEME FOR PRACTICAL EXAMINATION
There will be two practical exams in each semester.
i. Internal Practical Exam
ii. External Practical Exam
INTERNAL PRACTICAL EXAM
Total Marks:40
Marking of Internal Practical depends on the below rubrics.
8
7. INSTRUCTIONS FOR EACH LAB EXPERIMENT
PROGRAM 1
AIM- Write a Java program to demonstrate the concept of socket programming.
Overview-
Socket Programming
Java Socket programming is used for communication between the applications running on different
JRE.Java Socket programming can be connection-oriented or connection-less.
Socket and ServerSocket classes are used for connection-oriented socket programming and
DatagramSocket and DatagramPacket classes are used for connection-less socket programming.
Here, we are going to make one-way client and server communication. In this application, client sends
a message to the server, server reads the message and prints it. Here, two classes are being used: Socket
and ServerSocket. The Socket class is used to communicate client and server. Through this class, we
can read and write message. The ServerSocket class is used at server-side. The accept() method of
ServerSocket class blocks the console until the client is connected. After the successful connection of
client, it returns the instance of Socket at server-side.
Socket class - A socket is simply an endpoint for communications between the machines. The Socket
class can be used to create a socket.
Important methods
ServerSocket class - The ServerSocket class can be used to create a server socket. This object
is used to establish communication with the clients.
Important methods
9
Figure 1 - Socket API
Creating Server:
To create the server application, we need to create the instance of ServerSocket class. Here, we are
using 6666 port number for the communication between the client and server. You may also choose
any other port number. The accept() method waits for the client. If clients connects with the given port
number, it returns an instance of Socket.
10
Creating Client:
To create the client application, we need to create the instance of Socket class. Here, we need to pass
the IP address or hostname of the Server and a port number. Here, we are using "localhost" because our
server is running on same system.
Let's see a simple of Java socket programming where client sends a text and server receives and prints
it.
File: MyServer.java
1. import java.io.*;
2. import java.net.*;
3. public class MyServer {
4. public static void main(String[] args){
5. try{
6. ServerSocket ss=new ServerSocket(6666);
7. Socket s=ss.accept();//establishes connection
8. DataInputStream dis=new DataInputStream(s.getInputStream());
9. String str=(String)dis.readUTF();
10. System.out.println("message= "+str);
11. ss.close();
12. }catch(Exception e){System.out.println(e);}
13. }
14. }
File: MyClient.java
1. import java.io.*;
2. import java.net.*;
3. public class MyClient {
4. public static void main(String[] args) {
5. try{
6. Socket s=new Socket("localhost",6666);
7. DataOutputStream dout=new DataOutputStream(s.getOutputStream());
8. dout.writeUTF("Hello Server");
9. dout.flush();
10. dout.close();
11. s.close();
11
12. }catch(Exception e){System.out.println(e);}
13. }
14. }
To execute this program open two command prompts and execute each program at each command
prompt as displayed in the below figure.
After running the client application, a message will be displayed on the server console.
12
Q3. How would you handle socket exceptions in your code?
Q4. If you were to design a chat application, would you choose TCP or UDP sockets and why?
Q5. What is the main difference between a server socket and a client socket?
Q6. Can you describe the roles of bind(), listen(), and accept() functions in a socket programming?
Q7. What is a socket timeout and how do you set it in your code?
Q8. Can you explain the role of buffers in socket programming?
Q9. Can you explain the role of the select() function in socket programming?
Q10. Can you explain the use of SO_REUSEADDR and SO_REUSEPORT socket options?
13
PROGRAM 2
Aim- Write a Java program to demonstrate the concept of applet programming.
Applet - A Java application that is integrated into a webpage is called an applet. It functions as a front-
end and is run within the web computer. It makes a page more interactive and dynamic by operating
inside the web browser. Applets are hosted on web servers and inserted into HTML pages via the
OBJECT or APPLET tags.
It can be compared to a tiny application that runs on the address bar. In addition to updating content in
real-time and responding to human input, it may also play basic puzzles or graphics.
The Applet class is contained within java.applet package. The applet contains several methods that offer
you detailed control over the execution of your applet.
java.applet defines three interfaces :
AppletContext,
AudioClip, and
AppletStub.
Basically, in Java we have two types of applications:
1. Standalone Applications: The applications that are executed in the context of a local machine are
called standalone applications. Their applications use w-1 of system resources and the resources are not
sharable. This kind of application contains the main() method.
2.Distributed Applications: The applications that are executed under the control of a browser are
called distributed applications. The amount of resources required is very minimum and the resources
are sharable. These applications will not contain the main() method. To develop a distributed GUI we
use Applet.
Types of Applets –
Java applets can be classified as either local or remote, depending on where they are stored and how
easily they can be accessed.
1. Local Applet- A local applet is created locally and kept on the local machine. When a web page
detects a local applet in the Java system's memory, it does not need to obtain data directly from
the internet in order to function. It is defined or provided by the pathname or folder name. When
constructing an applet, two properties are used: the source folder, which defines the path name,
and the code itself, which defines the filename containing the applet's programming.
2. Remote Applet- The remote applet is stored or accessible on another computer that is linked
to the world over the internet. We must have internet access on the system to be able to obtain
and use the applet that resides on the other machine. We need to be familiar with a remote
applet's Uniform Resource Locator (URL) or web location in order to find and download it.
14
It provides a base class for creating applets and defines several methods that you can
override to control the applet’s behavior during its lifecycle.
2) Lifecycle Methods:
init(): This method is called when an applet is initialized. It’s used for applet
initialization tasks like setting up resources.
start(): Invoked after the init() method or when the applet is revisited. Use it to start
or resume operations.
stop(): Called when the applet is no longer visible or needs to stop its operations.
destroy(): Invoked when the applet is about to be unloaded or destroyed. Cleanup
tasks are typically performed here.
3) Graphics Class (java.awt.Graphics):
Used for rendering and drawing shapes, text, and images on the applet window.
The paint(Graphics g) method of the applet class receives a Graphics object as an
argument that you can use for drawing operations.
4) Event Handling:
Applets can handle user interactions like mouse clicks, keypresses, etc., by
implementing event-handling methods such as mouseClicked(), keyPressed(), etc.
5) Security Restrictions:
Applets are subject to security restrictions imposed by the browser or Java runtime
environment (JRE). They have limited access to resources and can’t perform certain
operations for security reasons.
How to run an Applet Program - An Applet program is compiled in the same way as you have been
compiling your console programs. However, there are two ways to run an applet.
For executing an Applet in an web browser, create short HTML file in the same directory.
Inside body tag of the file, include the following code. (applet tag loads the Applet class)
15
< applet code = "MyApplet" width=400 height=400 >
f:/>appletviewer run.htm
16
Creating Hello World Applet in Java
import java.applet.Applet;
import java.awt.Graphics;
// HelloWorld class extends Applet
public class HelloWorldApplet extends Applet
{
// Overriding paint() method
@Override public void paint (Graphics g)
{
g.drawString ("Hello World", 20, 20);
}
}
ADDITIONAL/PRACTICE PROGRAMS
Q1. Write an applet for event handling which prints a message when clicked on the button.
Q2. Write a program to Pass Parameters to Applet in Java
Q3. Creating a Simple Banner using Applet in Java
Q4. Implement Painting using mouseDragged() method of MouseMotionListener in Applet.
VIVA-VOICE QUESTIONS
Q4. What is the applet security manager, and what does it provide?
17
PROGRAM 3
AIM- Write a Java program to demonstrate the concept of multi-threading.
Multithreading- In Java, Multithreading refers to a process of executing two or more threads
simultaneously for maximum utilization of the CPU. A thread in Java is a lightweight process requiring
fewer resources to create and share the process resources.
Multithreading is a feature in Java that concurrently executes two or more parts of the program for
utilizing the CPU at its maximum. The part of each program is called Thread which is a lightweight
process. According to the definition, it can be deduced that it expands the concept of multitasking in the
program by allowing certain operations to be divided into smaller units using a single application.
Each Thread operates concurrently and permits the execution of multiple tasks inside the same
application.
Java supports multithreading through its built-in features for creating and managing threads. It
provides a Thread class that can be extended to create custom threads or Runnable interface to
define tasks for threads. To use it, you can either extend the Thread class and override
its run() method to define the thread's task or implement the Runnable interface and pass an
instance of the class to the Thread constructor. The start() method is then called to begin the
execution of the thread, which runs concurrently with other threads in the JVM, enabling
multithreading capabilities.
Lifecycle of Thread –
A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and
then dies. The following diagram shows the complete life cycle of a thread.
18
Figure- Lifecycle of thread
New − A new thread begins its life cycle in the new state. It remains in this state until
the program starts the thread. It is also referred to as a born thread.
Runnable − After a newly born thread is started, the thread becomes runnable. A thread
in this state is considered to be executing its task.
Waiting − Sometimes, a thread transitions to the waiting state while the thread waits
for another thread to perform a task. A thread transitions back to the runnable state only
when another thread signals the waiting thread to continue executing.
Timed Waiting − A runnable thread can enter the timed waiting state for a specified
interval of time. A thread in this state transitions back to the runnable state when that
time interval expires or when the event it is waiting for occurs.
Terminated (Dead) − A runnable thread enters the terminated state when it completes
its task or otherwise terminates.
19
"Thread " + Thread.currentThread().getId()
+ " is running");
}
catch (Exception e) {
// Throwing an exception
System.out.println("Exception is caught");
}
}
}
// Main Class
public class Multithread {
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
MultithreadingDemo object
= new MultithreadingDemo();
object.start();
}
}
}
Thread creation by implementing the Runnable Interface
We create a new class which implements java.lang.Runnable interface and override run() method. Then
we instantiate a Thread object and call start() method on this object.
/ Java code for thread creation by implementing
// the Runnable Interface
class MultithreadingDemo implements Runnable {
public void run()
{
try {
// Displaying the thread that is running
System.out.println(
"Thread " + Thread.currentThread().getId()
20
+ " is running");
}
catch (Exception e) {
// Throwing an exception
System.out.println("Exception is caught");
}
}
}
// Main Class
class Multithread {
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
Thread object
= new Thread(new MultithreadingDemo());
object.start();
}
}
}
21
multiThread1.setPriority(Thread.MIN_PRIORITY);
MultiThread multiThread2 = new MultiThread();
multiThread2.setName("Second Thread");
multiThread2.setPriority(Thread.MAX_PRIORITY);
MultiThread multiThread3 = new MultiThread();
multiThread3.setName("Third Thread");
multiThread1.start();
multiThread2.start();
multiThread3.start();
}
}
ADDITIONAL PROGRAMS
Q2. Illustrate Priorities in Multithreading via help of getPriority() and setPriority() method.
VIVA-VOICE QUESTIONS
Q1. Differentiate between process and thread?
Q3. Why must wait() method be called from the synchronized block?
Q4. What is the difference between preemptive scheduling and time slicing?
Q6. Can we make the user thread as daemon thread if the thread is started?
22
PROGRAM-4
JavaBeans is a portable, platform-independent model written in Java Programming Language. Its components are
referred to as beans.
In simple terms, JavaBeans are classes which encapsulate several objects into a single object. It helps in accessing
these object from multiple places. JavaBeans contains several elements like Constructors, Getter/Setter Methods
and much more.
JavaBeans Properties
A JavaBean property is a named attribute that can be accessed by the user of the object. The attribute
can be of any Java data type, including the classes that you define.A JavaBean property may be read,
write, read only, or write only. JavaBean properties are accessed through two methods in the
JavaBean's implementation class –
A read-only attribute will have only a getPropertyName() method, and a write-only attribute will have
only a setPropertyName() method.
23
this.id = id;
}
public int getId()
{
return id;
}
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
}
Next program is written in order to access the JavaBean class that we created above:
Output:
Chandler
Java Beans can be used effectively in JSPs (Java Server Pages) and Servlets, two key
technologies in the world of Java web applications. They can be used to encapsulate data that
can be reused across multiple JSPs or Servlets.
In this example, we’re using the StudentBean we defined earlier. The jsp:useBean tag is used to
instantiate the Bean, and the jsp:setProperty tags are used to set the values of the Bean’s properties.
Finally, the jsp:getProperty tags are used to retrieve and display these values.
24
Using Java Beans in JSPs and Servlets can greatly simplify your code, making it cleaner and easier to
maintain. However, as your applications get more complex, you might find that Java Beans are not
flexible enough to meet your needs. In such cases, you might want to consider using more powerful
alternatives such as POJOs (Plain Old Java Objects) or EJBs (Enterprise JavaBeans).
ADDITIONAL/PRACTICE QUESTIIONS
VIVA-VOICE QUESTIONS
Q3. How and when will the JavaBeans Migration Assistant to ActiveX be available?
Q4. Can both Java applets and JavaBeans components use the InfoBus?
Q5.JavaBeans has mechanisms like bound properties for data transfer between components.
Why is the InfoBus necessary?
Q8. How can you differentiate between the different types of EJBs: Session, Entity, and
Message-Driven Beans?
25
PROGRAM 5
AIM- Write a Java program to insert data into a table using JSP.
The database is used for storing various types of data which are huge and has storing capacity in
gigabytes. JSP can connect with such databases to create and manage the records.
For insert data in MySQL using JSP first we have to create a table in data base.
The INSERT INTO statement is used to insert new data to a MySQL table:
SQL Query
CREATE 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:<br>
<input type="text" name="first_name">
<br>
Last name:<br>
<input type="text" name="last_name">
<br>
City name:<br>
<input type="text" name="city_name">
<br>
Email Id:<br>
<input type="email" name="email">
<br><br>
<input type="submit" value="submit">
26
</form>
</body>
</html>
process.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-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");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root",
"");
Statement st=conn.createStatement();
int i=st.executeUpdate("insert into
users(first_name,last_name,city_name,email)values('"+first_name+"','"+last_name+"','"+city_name+"'
,'"+email+"')");
out.println("Data is successfully inserted!");
}
catch(Exception e)
{
System.out.print(e);
e.printStackTrace();
}
%>
Q2. What do you mean by a scriptlet in JSP? And what is its syntax?
Q5. What does the id and scope attribute mean in the action elements?
Q7. What are the various methods used to read data using JSP?
27
PROGRAM 6
WebLogic JSP form validation tags provide a convenient way to validate the entries an end user makes
to HTML form text fields generated by JSP pages. Using the WebLogic JSP form validation tags
prevents unnecessary and repetitive coding of commonly used validation logic. The validation is
performed by several custom JSP tags that are included with the WebLogic Server distribution.
Verify that required fields have been filled in (Required Field Validator class).
Validate the text in the field against a regular expression (Regular Expression
Validator class).
Compare two fields in the form (Compare Validator class).
Perform custom validation by means of a Java class that you write (Custom Validator class).
WebLogic JSP form validation tags include:
<wl:summary>
<wl:form>
<wl:validator>
When a validation tag determines that data in a field is not been input correctly, the page is re-displayed
and the fields that need to be re-entered are flagged with text or an image to alert the end user. Once the
form is correctly filled out, the end user's browser displays a new page specified by the validation tag.
This section describes the WebLogic form validation tags and their attributes. Note that the prefix used
to reference the tag can be defined in the taglib directive on your JSP page. For clarity, the wl prefix is
used to refer to the WebLogic form validation tags throughout this document.
<wl:summary> - It is the parent tag for validation. Place the opening <wl:summary> tag before any
other element or HTML code in the JSP. Place the closing </wl:summary> tag anywhere after the
closing </wl:form> tag(s).
name—(Optional) Name of a vector variable that holds all validation error messages generated
by the <wl:validator> tags on the JSP page. If you do not define this attribute, the default value,
errorVector, is used. The text of the error message is defined with the errorMessage attribute of
the <wl:validator> tag.
headerText—A variable that contains text that can be displayed on the page. If you only want
this text to appear when errors occur on the page, you can use a scriptlet to test for this condition.
For example:
out.println(headerText);
%>
Where summary is the name of the vector assigned using the name attribute of
the <wl:summary> tag.
28
redirectPage—URL for the page that is displayed if the form validation does not return errors. This
attribute is not required if you specify a URL in the action attribute of the <wl:form> tag.
<wl:form>
The <wl:form> tag is similar to the HTML <form> tag and defines an HTML form that can be
validated using the WebLogic JSP form validation tags. You can define multiple forms on a single
JSP by uniquely identifying each form using the name attribute.
Do not set the action attribute to the same page containing the <wl:form> tag—you will
create an infinite loop causing a StackOverFlow exception.
name—Functions exactly as the name attribute of the HTML <form> tag. Identifies the form
when multiple forms are used on the same page. The name attribute is also useful for
JavaScript references to a form.
<wl:validator> - Use one or more <wl:validator> tags for each form field. If, for instance, you want
to validate the input against a regular expression and also require that something be entered into the
field you would use two <wl:validator> tags, one using the RequiredFieldValidator class and another
using the RegExpValidator class. (You need to use both of these validators because blank values are
evaluated by the Regular Expression Field Validator as valid.)
errorMessage—A string that is stored in the vector variable defined by the name attribute of
the <wl:summary> tag.
expression—When using the RegExpValidator class, the regular expression to be evaluated.
If you are not using RegExpValidator, you can omit this attribute.
fieldToValidate—Name of the form field to be validated. The name of the field is defined with
the name attribute of the HTML <input> tag.
validatorClass—The name of the Java class that executes the validation logic.
a) Look up the value of the field you are validating from the ServletRequest object. For example:
3. Compile the validator class and place the compiled .class file in the WEB-INF/classes directory
of your Web application.
29
4. Use your validator class in a <wl:validator> tag by specifying the class name in the
validatorClass attribute. For example:
validatorClass="mypackage.myCustomValidator">
The CustomizableAdapter class is an abstract class that implements the Customizable interface and
provides the following helper methods:
<wl:summary
name="summary"
redirectPage="successPage.jsp"
>
<html>
<head>
<title>Untitled Document</title>
</head>
<body bgcolor="#FFFFFF">
} %>
30
<% if (summary.size() > 0) {
out.println("<H2>Error Summary:</h2>");
out.println((String)summary.elementAt(i));
out.println("<br>");
} %>
<wl:validator
fieldToValidate="username"
validatorClass="weblogicx.jsp.tags.validators.RequiredFieldValidator"
>
</wl:validator>
<p>
<wl:validator
fieldToValidate="password"
validatorClass="weblogicx.jsp.tags.validators.RequiredFieldValidator"
>
</wl:validator>
<p>
31
Re-enter Password: <input type="password" name="password2">
<wl:validator
fieldToValidate="password,password2"
validatorClass="weblogicx.jsp.tags.validators.CompareValidator"
>
</wl:validator>
<p>
</wl:form>
</wl:summary>
</body>
</html>
ADDITIONAL PROGRAMS-
VIVA-VOICE QUESTIONS
Q1. Which implicit object in JSP represents the client's requested information?
32
PROGRAM 7
Form Validation in Java Servlet | Verifying the pattern and format of form data before it is getting used
in the business logic as inputs are called form validations, otherwise business logic may give invalid
results or exceptions by taking the inputs.
33
Example:- Checking required fields of the form are filled or not, checking whether age types as a
numeric value and e.t.c.
Difference between form validation logic and business logic? In form validation logic, the pattern
and format of the form data will be verified. Whereas business logic/request processing logic takes
form data as inputs and uses them to process the request and generate the results.
Example:-
Example- Develop a html form and validate that data by using a servlet.
Validations:
stno - must contain data and it should contain always int data.
sname - must contain data and no special characters are allowed.
smarks - must contain data and it should contain float data.
Student database:
34
);
web.xml:
<web-app>
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>ValidationServ</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/validation</url-pattern>
</servlet-mapping>
</web-app>
validpro.html:
<html>
<title>Validation Project</title>
<head><center><h2>Student form validation</h2></center></head>
<body bgcolor="#FFE4C4">
<center>
<form name="validpro" action="./validation" method="post">
<table border="1" bgcolor="A9A9A9">
<tr>
<th>Enter student number : </th>
<td><input type="text" name="validpro_sno" value=""></td>
</tr>
<tr>
<th>Enter student name : </th>
<td><input type="text" name="validpro_sname" value=""></td>
</tr>
<tr>
<th>Enter student marks : </th>
<td><input type="text" name="validpro_smarks" value=""></td>
</tr>
<tr>
<table>
<tr>
<td><input type="submit" name="validpro_insert" value="Ins
ert"></td>
<td><input type="reset" name="validpro_clear" value="Clear
"></td>
</tr>
</table>
</tr>
</table>
</form>
</center>
</body>
</html>
ValidationServ.java:
import javax.servlet.*;
35
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
import java.util.*;
36
con.close();
} catch (Exception e) {
res.sendError(503, "PROBLEM IN DATABASE...");
}
}
}
ADDITIONAL/PRACTICE QUESTIONS :
Q1. Implement form validation in marriage application input.html form page using JavaScript
Q2. Implement the following form validations in Election Commission Voter Registration Form
1. The name must be valid. It should not be null (not filled), or empty (only spaces), and the
length of the name should not be lesser than 5 characters.
2. Age must be valid. It should not be null (not filled), or empty( only spaces), and the length
of the name should not be zero.
3. The age should be in numeric format, (not in words, or special characters).
4. The age should not be less than 0 and greater than 125
VIVA-VOICE QUESTIONS
37
Q2. What do you mean by server-side include (SSI) functionality in Servlets?
Q3. Explain the server-side include expansion.
Q4. Define ‘init’ and ‘destroy’ methods in servlets.
Q5. How is retrieving information different in Servlets as compared to CGI?
Q6. What is the life cycle contract that a servlet engine must conform to?
Q7. What do you mean by Servlet Reloading?
Q8. How can a servlet get the name of the server and the port number for a particular request?
Q9. How can a servlet get information about the client machine?
Q10. Explain Request parameters associated with servlets.
38
PROGRAM 8
A cookie is a small piece of information that is persisted between the multiple client
requests. A cookie has a name, a single value, and optional attributes such as a comment,
path and domain qualifiers, a maximum age, and a version number.
Types of Cookie-
1. Non-persistent cookie
It is valid for single session only. It is removed each time when user closes the browser.
2. Persistent cookie
It is valid for multiple session . It is not removed each time when user closes the browser.
It is removed only if user logout or signout.
Cookie class
javax.servlet.http.Cookie class provides the functionality of using cookies. It provides a
lot of useful methods for cookies.
Constructor of Cookie class-
39
For adding cookie or getting the value from the cookie, we need some methods provided by other
interfaces. They are:
1. public void addCookie(Cookie ck):method of HttpServletResponse interface is used to add
cookie in response object.
2. public Cookie[] getCookies():method of HttpServletRequest interface is used to return all the
cookies from the browser.
Let's see the simple code to delete cookie. It is mainly used to logout or signout the user.
1. Cookie ck=new Cookie("user","");//deleting value of cookie
2. ck.setMaxAge(0);//changing the maximum age to 0 seconds
3. response.addCookie(ck);//adding cookie in the response
Cookie ck[]=request.getCookies();
for(int i=0;i<ck.length;i++)
{
out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());//printing name and value of
cookie
}
40
index.html
<form action="servlet1" method="post">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
{
try
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
Cookie ck=new Cookie("uname",n);//creating cookie object
response.addCookie(ck);//adding cookie in the response
//creating submit button
out.print("<form action='servlet2'>");
out.print("<input type='submit' value='go'>");
out.print("</form>");
out.close();
}catch(Exception e){System.out.println(e);}
}
}
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response){
41
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Cookie ck[]=request.getCookies();
out.print("Hello "+ck[0].getValue());
out.close();
}catch(Exception e){System.out.println(e);}
}
}
web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
OUTPUT-
42
ADDITIONAL/PRACTICE PROGRAMS-
VIVA-VOICE QUESTIONS
Q1. How PrintWriter is different from ServletOutputStream?
Q2. What is the difference between a Generic Servlet and HTTP Servlet?
Q3. What is the use of RequestDispatcher Interface?
Q4. Why is init() method is used in Servlets?
43
Q5. What is load-on-startup in Servlet?
Q6. What is a WAR file?
Q7. Can you create a Deadlock condition on a servlet?
Q8. Can we fetch the attributes related to a servlet on a different servlet?
Q9. What do you mean by MIME type?
Q10.What is the difference between ServletConfig and ServletContext?
44
PROGRAM-9
AIM- Develop a small web program using Servlets, JSPs with Database connectivity.
Servlets are mainly used in Dynamic web applications which provides dynamic responses to
client requests. In most cases, Dynamic web applications access a database to provide the client
requested data. We can use Java standard database connection – JDBC in Servlets to perform
database operations.
Servlet – Database connection
A Servlet can generate dynamic HTML by retrieving data from the database and sending it back
to the client as a response. We can also update the database based on data passed in the client
HTTP request. We will create a simple servlet to fetch/retrieve data from the database based on
the client’s request. In this example, we will be using Eclipse IDE and PostgreSQL database.
We need to install the appropriate JDBC driver in our program to connect with the database. As
we are using PostgreSQL database, install “postgresql.jar” file with the latest version from Maven
Repository. After installation, place your jar file under “WebContent -> WEB-INF -> lib” folder.
To access and process the Database operations, we need to import all the required “java.sql”
packages in the program.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
After importing all the packages, we need to register the JDBC driver which we installed into our
program. Registering the driver tells the JVM to load the driver’s class file into the memory so
that we can implement the JDBC operations. We can register the driver by using
“Class.forName()” method:
Class.forName():
try {
// Register PostgreSQL Driver
Class.forName("org.postgresql.Driver");
}
catch (ClassNotFoundException e) {
System.out.println("Unable to load Driver class");
45
// e.printStackTrace(); OR you
// can directly print the stack trace
System.exit(1);
}
After processing the required operations, finally, close all the database connection objects.
stmt.close();
conn.close();
Example
In this example, we will create
A table in PostgreSQL – to fetch the data from it
An HTML form – for the client access
A Servlet class – to process the client request and generate the response.
PostgreSQL table:
Create a table in the PostgreSQL database and insert some records in it like below.
46
PostgreSQL – Table
home.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Home Page</title>
</head>
<body>
<form action="fetch" method="get">
Fetch Mobile phone details:<input type="submit" value="Search" />
</form>
</body>
</html>
Create “home.html” file under “WebContent -> home.html”.
This is the welcome file, where the browser accesses this form page.
Here we are simply displaying a submit button to fetch the data from the database.
In the form tag, mentioned the action “fetch” and method “get” to map the URL to a
specific servlet class when the form is submitted.
Create “FetchServlet.java” under “src” folder.
ADDITIONAL/PRACTICE PROGRAMS
Q1. Create User Registration using Jsp, Servlet and Jdbc.
Q2. Create Employee Registration Form using a combination of JSP, Servlet, JDBC and MySQL
database.
VIVA-VOICE QUESTIONS
47
8. SAMPLE VIVA-VOICE QUESTIONS
1. How does a JIT compiler differ from a standard compiler?
2. Name the access modifiers in Java.
3. What are constructors in Java?
4. When can you use the super keyword?
5. Explain what synchronization is, using a relevant example.
6. Define a Java Class.
7. What's the difference between this () and super ()?
8. Explain what double brace initialization is and its uses.
9. In simple terms, describe a market interface.
10. What's object cloning in Java?
11. Explain the life cycle of a servlet.
12. What are java objects and java applications?
13. Advantages and disadvantages of Java Sockets.
14. Explain the different ways of using thread?
15. What is the difference between ArrayList and vector?
16. What is an Iterator?
17. What is synchronization and why is it important?
18. What is static in java?
19. What if I do not provide the String array as the argument to the method?
20. Can an application have multiple classes having the main method?
21. Do I need to import java.lang package any time? Why?
22. What makes Java platform independent?
23. Explain the difference between the abstract and final keywords?
24. In Java, what are the differences between heap and stack memory?
25. What do the terms autoboxing and unboxing mean in Java?
26. What are wrapper classes in Java?
27. Can you override a private method or static method in Java?
28. What is the difference between equals() and == in Java?
29. Can you write multiple catch blocks under a single try block?
30. In Java, what are the differences between methods and constructors?
31. What is method hiding?
32. What is a singleton class, and how can it be used?
33. What is reflection and why it is useful?
34. Can == be used on enum ?
35. Is Java pass by reference or pass by value?
36. What is Java Bean ?
37. What is the difference between fail-fast and fail-safe?
38. What is the main difference between StringBuilder and StringBuffer?
39. Why does Java have transient fields?
40. Explain Marshalling and Demarshalling?
41. What exactly is marker interface in Java?
42. What is the difference between Serial and Throughput Garbage collector?
43. When to use LinkedList over ArrayList?
44. Explain the difference between ResultSet Vs. RowSet vs in JDBC?
45. Can you get a null ResultSet?
46. Explain the different drivers of JDBC.
47. Explain which is the most commonly used and fastest JDBC driver.
48. What are the data types used for storing images and files in the database table?
49. Explain what DatabaseMetaData is and why would you use it?
50. Explain the differences between JDBC and ODBC?
51. Explain the term connection pooling.
52. Are there any advantages of using a Prepared Statement in Java?
48
53. Explain the meaning of hot backup and cold backup.
54. Explain the differences between Statement and PreparedStatement interface?
55. How can we set a null value in JDBC PreparedStatement?
56. Explain the execution of stored procedures using Callable Statement?
57. Mention the functions of the JDBC Connection interface?
58. Why using cookie to store session info is a better idea than just using session info in the
request ?
59. Which method of the Cookie class is used to set the maximum age of a cookie?
60. What is singleton session bean?
61. What is Session Facade?
62. Name the attributes of javax.ejb.Stateful.
63. Mention the Java types that can be mapped using the @Lob annotation.
64. Compare Java Beans from Microsoft’s Active X Controls?
65. What is a Stored Procedure in JDBC?
66. What is DatabaseMetaData?
67. What is a Prepared Statement?
68. Why JDBC is needed once we have ODBC in hand?
69. Enlist the Declarative Transaction types?
70. Differentiate ‘Stateful Session’ from ‘Entity Bean’ ?
49