0% found this document useful (0 votes)
29 views242 pages

Java Full Notes

java notes

Uploaded by

Ashish Saval
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views242 pages

Java Full Notes

java notes

Uploaded by

Ashish Saval
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 242

UNIT 1 Java

2marks question
1. Define the terms: Event, Event Source, Event Listener, Event class
2. List any four sources of event
3. List the methods of MouseListener, KeyListener interface
4. What is Event Listener interface
5. Define Adapter class.
6. How event handling is achieved in java

5marks question
1) Write a java program to implement mousePressed, mouseReleased and
mouseMoved using MouseAdapter class
2) Write a java program to implement key events
3) Explain any 5 event classes in java
4) what are inner classes. Explain with example
UNIT 2 Java
2marks question
1. Define: JFC's, JFC API, Swings, JComponent class
2. List the features of swings
3. Differentiate between swing and awt
4. List the advantages of JApplet class
5. what is JList

5marks question
1) Write a program that creates a user interface to perform integer divisions.
The user enters two numbers in the textfields, Num1 and Num2. The
division of Num1 and Num2 is displayed in the Result field when the Divide
button is clicked. If Num1 or Num2 were not an integer, the program
would throw a NumberFormatException. If Num2 were Zero, the program
would throw an Arithmetic Exception Display the exception in a message
dialog box 4. Write a Java program to illustrate basic calculator using grid
layout manager.
2) Explain JComponent class in detail
3) Write a java program to demonstrate JApplet or JFrame or JPanel.
4) Write a note on JTabbedPane or JScrollPane.
5) List different types of swing buttons. Explain any two of them or Explain
Togglebuttons in java or Write a program to illustrate use of JCheckBox &
JRadioButton
6) Explain the methods & events associated with JList class.
UNIT 3 Java
2marks question
1. what is JDBC API
2. List any 4 drivers used in JDBC
3. What is savepoint, commit, rollback?
4. What is Metadata? Mention two types of it
5. which are the different kind of exceptions raised in JDBC
6. Differentiate between execute() & executeUpdate() methods
7. List any four JDBC datatypes

5marks question
1) Write a Java program that loads names and phone numbers from a
database file. It takes a name or phone number as input and prints the
corresponding other value.
2) Explain the JDBC architecture with diagram
3) Differentiate between JDBC and ODBC
4) Explain the JDBC driver models with diagram
5) Explain the JDBC driver types.
6) Explain the JDBC connection process in detail OR Give the steps & methods
required for connecting java and DBMS
7) Write a short note on Statement or PreparedStatement or ResultSet
8) Explain Transaction Processing mechanism with example
9) Explain Metadata and ResultSet Metadata
UNIT 4 Java
2marks question
1. Define the terms: web application, Servlet, JSP
2. State advantages of servlet over CGI
3. Differentiate between servlet and jsp
4. What are the exceptions thrown by servlet
5. Name any two prominent servlet packages
6. Differentiate between get() and post() methods
7. what is query string or request string
8. What are cookies, user session and session object
9. what is Deployment Descriptor
10. What is implicit/explicit variable.
11. Define CData

Part B – 5marks question


1) Write a servlet program: Ask the user for a color in a JSP in say "Home.jsp"
file. Display "Hello World" in the chosen color using a servlet, say in
"helloWorld.java". (Hint: use tomcat server).
2) Write a Java program to establish client server communication using TCP/IP
socket.
3) Write a Java servlet program to implement a dynamic HTML using servlet.
(username and password should be accepted using HTML and displayed
using servlet). or Write a pgm for Reading servlet parameters
4) Write a JSP program to find factorial of a given number.
5) Explain life cycle of servlet.
6) Write a note of HttpServlet class. Explain any 5 methods of it.
7) Explain different JSP tags with example
8) Explain: variables and object, methods, control statements or loops in JSP
9) Write a note on: User session or cookies or session object or JAR file
UNIT 5 Java
2marks question
1. Define the terms: Socket, Proxy servers, DNS, Reserved sockets
2. What is URL, URLConnection, HttpURLConnection
3. What do you mean by Datagram class. List any two Datagram classes
4. Define: EJB, EJB Container, EJB class, EJB interface

5marks question
1) Write a Java Program to find the IP address of a given website specified by
the user or Write a java program to display IP address of
“www.google.com”
2) Write a note on InetAaddress class(factory and instance methods)
3) Explain any 3 methods of URLConnection class
4) Write a program to demonstrate HTTPURLConnection
5) Explain the use of DatagramPacket & DatagramSocket class with example
6) Write a short note on EJB or session bean or entity bean or message-driven
bean
7) What is session bean / entity bean / message-driven bean
No. of Printed Pages : 2
41423/D230
!41423D230! Reg. No.

IV Semester B.C.A.4 Degree Examination, May - 2019


ADVANCED JAVA PROGRAMMING
Theory
(RCU Regular 2018-19)

Time : 3 Hours Max. Marks : 80

Instructions : All Sections are compulsory.

SECTION - A

1. Answer all following questions : 2x10=20

(a) What is Event Source and Event Classes ?

(b) List any four JDBC drivers.

(c) What is Servlet ? Mention Servlet Packages.

(d) What do you mean by Datagram ?

(e) Give the syntax to declare variable in JSP.

(f) Define C Data.

(g) Define implicit data and Explicit data.

(h) What is ResultSet ?

(i) Define Deployment Descriptor.

(j) What is EJB ? Mention types of beans.

P.T.O.
41423/D230 2

SECTION - B
Answer any four of the following : 5x4=20
2. Explain swing features.

3. Explain EJB interfaces.

4. Explain Entity Java bean.

5. Explain JDBC architecture.

6. Explain JTextField and JToggle Button.

SECTION - C
Answer any four of the following : 10x4=40
7. Write a JSP program to find factorial of given number.

8. Difference between JDBC vs ODBC.

9. Explain the following :


(a) Result Meta Data
(b) Prepared Statement
(c) Save Point
(d) Database Metadata.

10. Explain Session Java bean and Message Driver Java bean.

11. (a) How to user session in Java Servlet.


(b) Explain JAR fill.

-oOo-

!41423D230!
Second Internal Question Bank
Advanced Java- 5th sem
Note : Questions will be asked for 2 marks and 5 marks
1. Define servlet.
2. What is JSP?
3. Explain the servlet life cycle with an diagram ?
4. What are getAttribute() and setAttribute() in servlets. Give example
5. Explain the following interfaces and their methods provided in the javax.servlet
package
i) Servlet ii) ServletConfig iii) ServletContext iv) ServletRequest v) ServletResponse

6. Explain the following interfaces and their methods provided in the javax.servlet.http package
i) HttpServletRequest ii) HttpServletResponse iii) HttpSession
7. Difference between the following (Any can be asked)
a. Get Vs Post
b. GenericServlet Vs HttpServlet
c. servlet and JSP.

8. State the advantages of servlet over CGI.


9. Differentiate between servlet and JSP.
10. Write a java servlet program to accept username and password using HTML file and display it
using servlet.
11. What is Cookies and what is the use of cookies?
12. Explain the various purposes for which we use session tracking. Also explain in brief the two
ways to handle Session Tracking in servlets.
13. What is the difference between ServletContex and ServletConfig ?
14. Write a program to.
a. Demonstrate session Tracking using servlet
b. Demonstrate Cookies
15. How to create a sessions ? Give example
16. How to bind data to a session ?
17. Explain various JSP components ?
18. What is Request implicit object ? write a program to demonstrate request implicit object ?
19. What is Declaration Tag, java scriplets tag and expression tag in jsp ?
20. Write a java servlet program to add two numbers and display the result.

21. Write a Java Servlet session program prints the session ID, creation time and last accessed
time of the current session.
22. Write a program To Demonstrate getAttribute() and setAttibute()
.
Advance Java Programming Questions
28.3.2015
28.3.2016
16.3.2017
Event Handling

1. What is an Event?
2. What are the components of Event Handling?
3. How events are handled in java?
4. List important event classes and interfaces.
5. List the steps to handle events.
6. What is an adapter class?
7. What is inner class?
8. Write a java swing program to handle keyboard events by using adaptor classes.
9. What are event classes?
10. Write a java program to handle windows event.

Swings

1. What is the difference between swing and awt?


2. What is a component and a container?
3. What is the difference between invokeAndWait and invokeLater in Java?
4. Explain in brief JToggle button.
5. Write a program to demonstrate a JLabel with an Image and text.
6. What is Swing? Explain two key features of swing.
7. Explain the MVC connection.
8. Write a program which contains 3 buttons having labels “One”“Two” and “Three” and one
text field. When user clicks any button its label text appears in the text field.
9. Explain JButton and JTextField class with an example.
10. Write the purpose of the following Swing Components:
a. JTabbedPane
b. JList
c. JScrollPane
d. JComboBox
11. What are containers? Mention different types of it.
12. What is MVC architecture?
13. List different types of swing buttons. Explain any two of them.
14. Write a swing program to illustrate the use of JScrollPane.
15. Name any four top level containers.
16. List any two constructors of JLabel class. Give their syntax.
17. Write a Java program containing a combobox displaying the entries “India”, ”France”,
”Israel” and “Russia”.
18. Explain any five events associated with swing components with syntax; explain the working
of methods associated with these events.
19. Name any four swing Button classes.
JDBC
1. What are the different types of JDBC Statements? With examples.
2. What are SQL warnings?
3. What is a Stored Procedure and how do you call it in JDBC?
4. What is the difference between execute, executeQuery, executeUpdate?
5. What is Connection Pooling ?
6. What is JDBC? What are the common JDBC API components?
7. What is a ResultSet? What are types of ResultSet?
8. What is a SavePoint? Give an example.
9. Explain the different types of JDBC Drivers.
10. Write a swing program to insert student information in the database and retrieve info based
on particular query.
OR
11. Write a JDBC program to display all the records from student table which consist of roll-no,
name and percentage.

12. Explain JDBC Process or List the steps to connect Java application to Database
13. What is a Transaction? Explain Transaction processing in JDBC.
14. Explain JDBC Exceptions.
15. What are the advantages of JDBC?
16. List different Types of Drivers used in JDBC.
17. Which methods are used load the JDBC driver and to connect the J2EE components to the
DBMS ?
18. What is metadata? Mention two types of it.
19. Explain prepared statement object.
20. Write a note on scrollable Resultset.
21. Mention any two Database Meta Data methods.
22. Explain how transaction processing can be achieved with the help of savepoints.
23. Discuss in detail how prepared statement object can be used to make an sql query/statement
dynamic.
24. Write a java program to insert data into STUDENT(roll no, name, address, phone no)
database using prepared statement object. Retrieve information based on particular queries.

Servlet/JSP
1. What are JSP implicit objects?
2. Define servlet.
3. What is JSP?
4. Explain classes and interfaces provided in javax.servlet package.
5. Advantages of JSP over Servlets.
6. Advantages of Servlet in web programming.
7. What is deployment descriptor ?
8. What is Cookies and what is the use of cookies?
9. Explain the various purposes for which we use session tracking. Also explain in brief the two
ways to handle Session Tracking in servlets.
10. What are the five basic types of elements in JSP?
11. What is Java Server Page?
12. How Does JSP work? or Explain the JSP architecture?
13. How to declare variables and objects within my JSP page? Explain with example
14. How to declare methods within my JSP page? Explain with example
15. How to use control statements in jsp code
16. Explain how JSP handles request string posted from an HTML file
17. How JSP differs from Java servlet?
18. Develop a JSP page that displays the current date and time
19. What is the difference between ServletContex and ServletConfig ?
20. Explain the servlet life cycle. Write servlet program to demonstrate life cycle of servlet.
21. Write a Java Servlet which reads two parameters from the web page , say value 1 and value 2
of integer type , find the sum and return the result as a web page.
22. Write a program to.
a. Demonstrate session Tracking using servlet
b. Demonstrate Cookies using JSP.
23. What is the difference between session and cookie?
24. Develop a servlet to accept user name from an HTML form and display a greeting message.
25. How servlet works?
26. Explain how to setup tomcat for servlet development
27. What are the general steps involved in building and testing a servlet
28. Explain the following interfaces and their methods provided in the javax.servlet package
i) Servlet ii) ServletConfig iii) ServletContext iv) ServletRequest v) ServletResponse
29. Explain with example how to read parameters in a servlet?
or
30. Write a servlet program to accept Employee name and phone from an HTML form and
display them in a web page by passing parameters.
or
31. How does a servlet read data entered in an HTML form?
or
32. Write a simple application in which the HTML form can invoke a servlet
33. . Explain the following interfaces and their methods provided in the javax.servlet.http
package
i) HttpServletRequest ii) HttpServletResponse iii) HttpSession
34. Difference between the following
a. Get Vs Post
b. GenericServlet Vs HttpServlet
35. Which two packages constitute servlet API ? List any two interface of it.
36. State the advantages of servlet over CGI.
37. Differentiate between servlet and JSP.
38. Write a java servlet program to accept username and password using HTML file and display
it using servlet.
39. How to use loops in JSP?
40. What are the exceptions thrown by a servlet?
41. Name the interfaces of javax.servlet package.
42. Name the default methods of JSP.
Networking
1. Define socket. How do you create socket in java.
2. What is DNS?
3. Explain InetAddress class and its commonly used methods.
4. Explain instance methods of InetAddress Class.
5. Name the two constructors to create client socket.
6. Explain methods of socket class.
7. How do you create ServerSocket? Give two constructors.
8. Explain in brief Datagram in java.
9. What is DatagramPacket and DatagramSocket? Give constructors.
10. Write a program to create a url to http://rcub.ac.in and examine the properties.
11. Which are the two important methods of DatagramSocket class.
12. Write a note on URLConnection and HttpURLConnection class.
13. Which package contains classes and interfaces for networking? List some classes.
14. What is socket? Mention two methods for socket.
15. What is use of URL class? Explain its basic form and constructor.
16. List any two Datagram classes.
17. Along with syntax explain the significance of factory methods. Write a java program to
display the address www.rcub.ac.in.
18. Explain socket and server socket.
19. Write a short note any two
a. Networking classes and interfaces.
Enterprise Java Beans
1. What is Enterprise Java Beans(EJB)?
2. What are the different types of EJB?
3. Advantages of Enterprise Java Bean.
4. Briefly explain the session bean.
5. What are session beans? Explain the different types.
6. What are the two types of entity beans?
7. What is EJB container?
8. Write a note on EJB interfaces.
9. What is a message driven bean? Explain the process of creating a message driven bean.
BCA V SEM Advanced Java C.A. SATERI

Unit – 1 Event Handling


Normally, a user interacts with an application’s GUI to indicate the tasks that the application should perform.
For example, when you write an e-mail in an e-mail application, clicking the Send button tells the application to
send the e-mail to the specified e-mail addresses. GUIs are event driven. When the user interacts with a GUI
component, the interaction—known as an event—drives the program to perform a task. Some common user
interactions that cause an application to perform a task include clicking a button, typing in a text field, selecting
an item from a menu, closing a window and moving the mouse. The code that performs a task in response to an
event is called an event handler, and the overall process of responding to events is known as event

handling.

Event handling in Java is the procedure that controls an event and performs appropriate action if it occurs.
Event Handling is the mechanism that controls the event and decides what should happen if an event occurs.
This mechanism have the code which is known as event handler that is executed when an event occurs.
Event handling is fundamental to Java programming because it is used to create event driven programs
eg • Applets • GUI based windows application • Web Application.

What are Events ?


Events in Java represent the change in the state of any object. Events occur when the user interacts with the
interface. Clicking a button, moving the mouse, typing a character, selecting an item from a list, and scrolling
the page are all examples of behaviours that cause an event to occur.

1 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

Types Of Events
Foreground Events - Those events which require the direct interaction of user. They are generated as
consequences of a person interacting with the graphical components in Graphical User Interface. For example,
clicking on a button, moving the mouse, entering a character through keyboard,selecting an item from list,
scrolling the page etc.
Background Events - Events can occur that aren’t directly caused by interactions with an interface are known
as background events.
Eg : Operating system interrupts, hardware or software failure, timer expires, an operation completion are
the example of background events.

The Delegation Event Model


The modern approach to handle events is based on the delegation event model. Its concept is quite simple: a
source generates an event and sends it to one or more listeners. In this scheme, the listener simply waits until it
receives an event. Once an event is received, the listener processes the event and then returns. The advantage of
this design is that the application logic that processes events is cleanly separated from the user interface logic
that generates those events. A user interface element is able to ―delegate the processing of an event to a separate
piece of code. In the delegation event model, listeners must register with a source in order to receive an event
notification. This provides an important benefit: notifications are sent only to listeners that want to receive them.

In the delegation event model, listeners must register with a source in order to receive an event notification. This
provides an important benefit: notifications are sent only to listeners that want to receive them.

2 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

Components of Event Handling

• Event Handler - An event handler is a function or method that executes program statements in response
to an event. A software program that processes activities such as keystrokes and mouse movements is
what an event handler is
• Source - The source is an object on which event occurs. Source is responsible for providing information
of the occurred event to it's handler. Java provides as with classes for source object.
• Listener - It is also known as event handler. Listener is responsible for generating response to an event.
From java implementation point of view the listener is also an object. Listener waits until it receives an
event. Once the event is received , the listener process the event an then returns.

3 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

Event Classes
The classes that represent events are at the core of Java’s event handling mechanism. Widely used Event
classes are those defined by AWT and those defined by Swing.
At the root of the Java event class hierarchy is EventObject, which is in java.util. It is the superclass for
all events. Its one constructor is shown here:
EventObject(Object src)

Here, src is the object that generates this event.


EventObject defines two methods: getSource( ) and toString( ). The getSource( ) method returns the
source of the event. Its general form is shown here:
Object getSource( )
As expected, toString( ) returns the string equivalent of the event.
The class AWTEvent, defined within the java.awt package, is a subclass of EventObject. It is the
superclass (either directly or indirectly) of all AWT-based events used by the delegation event model. Its
getID( ) method can be used to determine the type of the event. The signature of this method is shown here:
int getID( )

4 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

Event Listeners
A listener is an object that is notified when an event occurs. It has two major requirements. First, it must have
been registered with one or more sources to receive notifications about specific types of events. Second, it must
implement methods to receive and process these notifications.

The methods that receive and process events are defined in a set of interfaces, such as those found in
java.awt.event. For example, the MouseMotionListener interface defines two methods to receive notifications
when the mouse is dragged or moved. Any object may receive and process one or both of these events if it
provides an implementation of this interface.

5 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

Event Handling includes : ActionEventListener

Action: What user does is known as action. Example, a click over button. Here, click is the action
performed by the user.
Event: The action done by the component when the user’s action takes place is known as event. That is,
event is generated (not seen, it is software) against action.
Listener: It is an interface that handles the event. That is, the event is caught by the listener and when
caught, immediately executes some method filled up with code. Other way, the method called gives life to the
user action.

6 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

For more clarity,


Action by user: Mouse click over a button
Event generated: ActionEvnet
Listener that handles ActionEvent: ActionListener
Method called implicitly: actionPerformed() method.

The code of actionPerformed() contains the actions of what is to be done (like user name and password
validation etc.) when the user clicks a button.

Steps involved in event handling( in above case)


The User clicks the button and the event is generated.
Now the object of concerned event class is created automatically and information about the source and the
event get populated with in same object.
Event object is forwarded to the method of registered listener class.
The method is now get executed and returns.

The ActionListener Interface


This interface defines the actionPerformed( ) method that is invoked when an action event occurs. Its general
form is shown here:
void actionPerformed(ActionEvent ae)
The ContainerListener Interface
This interface contains two methods. When a component is added to a container, componentAdded( ) is
invoked. When a component is removed from a container, componentRemoved( ) is invoked. Their general
forms are shown here:
void componentAdded(ContainerEvent ce)
void componentRemoved(ContainerEvent ce)

The MouseListener Interface


This interface defines five methods. If the mouse is pressed and released at the same point, mouseClicked( ) is
invoked. When the mouse enters a component, the mouseEntered( ) method is called. When it leaves,
mouseExited( ) is called. The mousePressed( ) and mouseReleased( ) methods are invoked when the mouse
is pressed and released, respectively.
The general forms of these methods are shown here:
void mouseClicked(MouseEvent me)
void mouseEntered(MouseEvent me)

7 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

void mouseExited(MouseEvent me)


void mousePressed(MouseEvent me)
void mouseReleased(MouseEvent me)
The WindowListener Interface
This interface defines seven methods. The windowActivated( ) and windowDeactivated( ) methods are
invoked when a window is activated or deactivated, respectively. If a window is iconified, the
windowIconified( ) method is called. When a window is deiconified, the windowDeiconified( ) method is
called. When a window is opened or closed, the windowOpened( ) or windowClosed( ) methods are called,
respectively. The windowClosing( ) method is called when a window is being closed. The general forms of
these methods are
void windowActivated(WindowEvent we)
void windowClosed(WindowEvent we)
void windowClosing(WindowEvent we)
void windowDeactivated(WindowEvent we)
void windowDeiconified(WindowEvent we)
void windowIconified(WindowEvent we)
void windowOpened(WindowEvent we)

Following table lists several commonly used listener interfaces, Event types event source and event handler
and provides a brief description of the methods that they define.

8 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

9 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

Event Sources
A source is an object that generates an event. This occurs when the internal state of thatobject changes in
some way. Sources may generate more than one type of event.
A source must register listeners in order for the listeners to receive notifications about aspecific type of
event.
Each type of event has its own registration method. Here is the general form:

public void addTypeListener (TypeListener el )

Here, Type is the name of the event, and el is a reference to the event listener. For example, the method that
registers a keyboard event listener is called addKeyListener( ). The method that registers a mouse motion
listener is called addMouseMotionListener( ).
When an event occurs, all registered listeners are notified and receive a copy of the event object. This is known
as multicasting the event. In all cases, notifications are sent only to listeners that register to receive them.
Some sources may allow only one listener to register. The general form of such a method is this:

public void addTypeListener(TypeListener el )


Here, Type is the name of the event, and el is a reference to the event listener.
When such an event occurs, the registered listener is notified. This is known as unicasting the event.
A source must also provide a method that allows a listener to unregister an interest in a specific type of event.
The general form of such a method is this:

public void removeTypeListener(TypeListener el )


Here, Type is the name of the event, and el is a reference to the event listener. For example, to remove a keyboard
listener, you would call removeKeyListener( ).
The methods that add or remove listeners are provided by the source that generates events. For example, the
Component class provides methods to add and remove keyboard and mouse event listeners.

The KeyEvent Class


A KeyEvent is generated when keyboard input occurs.

There are three types of key events, which are identified by these integer constants: KEY_PRESSED,
KEY_RELEASED, and KEY_TYPED. The first two events are generated when any key is pressed or

10 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

released. The last event occurs only when a character is generated. Remember, not all keypresses result in
characters. For example, pressing shift does not generate a character.

KeyEvent is a subclass of InputEvent. Here is one of its constructors:


KeyEvent(Component src, int type, long when, int modifiers, int code, char
ch)
Here, src is a reference to the component that generated the event. The type of the event is specified by type.
The system time at which the key was pressed is passed in when. The modifiers argument indicates which
modifiers were pressed when this key event occurred.
The VK constants specify virtual key codes and are independent of any modifiers, such as control, shift, or
alt.The virtual key code, such as VK_UP, VK_A, and so forth, is passed in code. The character equivalent (if
one exists) is passed in ch. If no valid character exists, then ch contains CHAR_UNDEFINED.
For KEY_TYPED events, code will contain VK_UNDEFINED.

The KeyEvent class defines several methods, but probably the most commonly used ones are getKeyChar( ),
which returns the character that was entered, and getKeyCode(), which returns the key code. Their general
forms are shown here:
char getKeyChar( )
int getKeyCode( )
If no valid character is available, then getKeyChar( ) returns CHAR_UNDEFINED. When a KEY_TYPED
event occurs, getKeyCode( ) returns VK_UNDEFINED.

The MouseEvent Class


There are eight types of mouse events. The MouseEvent class defines the following integer constants that
can be used to identify them:

11 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

Here, src is a reference to the component that generated the event. The type of the event is specified by type.
The system time at which the mouse event occurred is passed in when. The modifiers argument indicates which
modifiers were pressed when a mouse event occurred. The coordinates of the mouse are passed in x and y. The
click count is passed in clicks. The triggersPopup flag indicates if this event causes a pop-up menu to appear
on this platform.
Two commonly used methods in this class are getX( ) and getY( ). These return the X and Y coordinates of
the mouse within the component when the event occurred. Their forms are shown here:
int getX( )
int getY( )
Alternatively, you can use the getPoint( ) method to obtain the coordinates of the mouse. It is shown here:
Point getPoint( )
It returns a Point object that contains the X,Y coordinates in its integer members: x and y.
The translatePoint( ) method changes the location of the event. Its form is shown here:

void translatePoint(int x, int y)


Here, the arguments x and y are added to the coordinates of the event.
The getClickCount( ) method obtains the number of mouse clicks for this event. Its signature is shown here:

int getClickCount( )

The TextEvent Class


Instances of this class describe text events. These are generated by text fields and text areas when characters
are entered by a user or program.

TextEvent defines the integer constant TEXT_VALUE_CHANGED.

The one constructor for this class is shown here:

TextEvent(Object src, int type)


Here, src is a reference to the object that generated this event. The type of the event is specified by type.
The TextEvent object does not include the characters currently in the text component that generated the event.
Instead, your program must use other methods associated with the text component to retrieve that information.

12 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

This operation differs from other event objects discussed in this section. Think of a text event notification as a
signal to a listener that it should retrieve information from a specific text component.

The WindowEvent Class


There are ten types of window events. The WindowEvent class defines integer constants that can be used
to identify them. The constants and their meanings are shown here:

WindowEvent is a subclass of ComponentEvent. It defines several constructors. The first is


WindowEvent(Window src, int type)
Here, src is a reference to the object that generated this event. The type of the event is type. The next three
constructors offer more detailed control:
WindowEvent(Window src, int type, Window other)
WindowEvent(Window src, int type, int fromState, int toState)
WindowEvent(Window src, int type, Window other, int fromState, int toState)
Here, other specifies the opposite window when a focus or activation event occurs. The fromState specifies the
prior state of the window, and toState specifies the new state that the window will have when a window state
change occurs.
A commonly used method in this class is getWindow( ). It returns the Window object that generated the event.
Its general form is shown here:

13 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

Window getWindow( )
WindowEvent also defines methods that return the opposite window (when a focus or activation event has
occurred), the previous window state, and the current window state. These methods are shown here:

Window getOppositeWindow( )
int getOldState( )
int getNewState( )

Program to demonstrate event handling


import java.awt.*;
import java.awt.event.*;
class EventHandling extends Frame implements ActionListener
{
TextField textField;
EventHandling ()
{
textField = new TextField ();
textField.setBounds (60, 50, 170, 20);
// setBounds method is used to provide position and size of the component, bounds are x,y cordinates in the
container and width,height of the button object
Button button = new Button ("Show");
button.setBounds (90, 140, 75, 40);
//button.setBackground(Color.red);
// Registering component with listener this refers to current instance
button.addActionListener (this);
// add Components
add (button);
add (textField);
setSize (250, 250);
setLayout (null);
// set visibility

14 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

setVisible (true);
}
// implementing method of actionListener
public void actionPerformed (ActionEvent e)
{
// Setting text to field
textField.setText ("Hello World");
}
public static void main (String args[])
{
new EventHandling ();
}
}

Steps of writing event handling program(explaination of above program)

• Create Text-Field and Button components.

• Registered the button component with respective event. i.e. ActionEvent by addActionListener().

• setBounds method is used to provide position and size of component.

• Registering component with listener Passing other class as reference.

• Add Components to frame.

15 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

• Set Visibility of frame.

Handling Mouse Events Example Program


// Demonstrate the mouse event handlers.
import java.awt.*;
import java.awt.event.*;
class MouseDemo extends Frame implements MouseListener
{
String msg="";
MouseDemo()
{
addMouseListener(this);
}
public void mouseClicked(MouseEvent me)
{
msg="mouse clicked"; repaint();
}
public void mouseEntered(MouseEvent me)
{ msg="mouse entered";repaint();
}
public void mouseExited(MouseEvent me){
msg="mouse exited";repaint();
}
public void mousePressed(MouseEvent me){
msg="mouse pressed";repaint();
}
public void mouseReleased(MouseEvent me){
msg="mouse released";repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,200,200);
}
}
class MouseEventsExample
{
public static void main(String arg[])
{
MouseDemo d=new MouseDemo();

16 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

d.setSize(400,400);
d.setVisible(true);
d.setTitle("Mouse Events Demo Program");
d.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
}
}

17 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

LayoutManagers
• The LayoutManagers are used to arrange components in a particular manner.
• The Java LayoutManagers facilitates us to control the positioning and size of the components in GUI
forms.
• LayoutManager is an interface that is implemented by all the classes of layout managers.
There are the following classes that represent the layout managers:
java.awt.BorderLayout
java.awt.FlowLayout
java.awt.GridLayout
java.awt.CardLayout
java.awt.GridBagLayout
javax.swing.BoxLayout
javax.swing.GroupLayout
javax.swing.ScrollPaneLayout
javax.swing.SpringLayout

FlowLayout
FlowLayout is useful to arrange the components in a line one after the other. When a line is filled with
components, they are automatically placed in a next line. This is the default layout in applets.
Constructors of FlowLayout class
FlowLayout(): creates a flow layout with centered alignment and a default 5 unit horizontal and vertical gap.
FlowLayout(int align): creates a flow layout with the given alignment and a default 5 unit horizontal and
vertical gap.
FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given alignment and the given
horizontal and vertical gap.

FlowLayout.LEFT
FlowLayout.RIGHT
FlowLayout.CENTER
FlowLayout.LEADING
FlowLayout.TRAILING

18 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

Example:
Example of FlowLayout class: Using FlowLayout(int align, int hgap, int vgap) constructor
import java.awt.*;
import javax.swing.*;

public class FlowLayoutExample1


{
JFrame frameObj;
// constructor
FlowLayoutExample1()
{
// creating a frame object
frameObj = new JFrame();
// creating the buttons
JButton b1 = new JButton("1");
JButton b2 = new JButton("2");
JButton b3 = new JButton("3");
JButton b4 = new JButton("4");
JButton b5 = new JButton("5");
JButton b6 = new JButton("6");
JButton b7 = new JButton("7");
JButton b8 = new JButton("8");
JButton b9 = new JButton("9");
JButton b10 = new JButton("10");

// adding the buttons to frame


frameObj.add(b1); frameObj.add(b2); frameObj.add(b3); frameObj.add(b4);
frameObj.add(b5); frameObj.add(b6); frameObj.add(b7); frameObj.add(b8);
frameObj.add(b9); frameObj.add(b10);
// parameterized constructor is used
// where alignment is left
// horizontal gap is 20 units and vertical gap is 25 units.
frameObj.setLayout(new FlowLayout(FlowLayout.LEFT, 20, 25));

frameObj.setSize(300, 300);

19 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

frameObj.setVisible(true);
}
// main method
public static void main(String argvs[])
{
new FlowLayoutExample1();
}
}

BorderLayout
BorderLayout is useful to arrange the components in the four borders of the frame as well as in the centre. The
borders are identified with the names of the directions. The top border is specified as ‗North‘, the right side border
as ‗East‘, the bottom one as ‗South‘ and the left one as ‗West‘. The centre is represented as ‗Centre‘.
Constructors:
BorderLayout( )
BorderLayout(int horz, int vert)
The first form creates a default border layout. The second allows you to specify the horizontal and vertical space left
between components in horz and vert, respectively.
BorderLayout defines the following constants that specify the regions:
BorderLayout.CENTER
BorderLayout.SOUTH
BorderLayout.EAST
BorderLayout.WEST
BorderLayout.NORTH

20 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

When adding components, you will use these constants with the following form of add( ), which is defined by
Container:
void add(Component compObj, Object region)
Here, compObj is the component to be added, and region specifies where the component will be added.
Example of BorderLayout class: Using BorderLayout(int hgap, int vgap) constructor

import java.awt.*;
import javax.swing.*;
public class BorderLayoutExample
{
JFrame jframe;
// constructor
BorderLayoutExample()
{
// creating a Frame
jframe = new JFrame();
// create buttons
JButton btn1 = new JButton("NORTH");
JButton btn2 = new JButton("SOUTH");
JButton btn3 = new JButton("EAST");
JButton btn4 = new JButton("WEST");
JButton btn5 = new JButton("CENTER");
// creating an object of the BorderLayout class using
// the parameterized constructor where the horizontal gap is 20
// and vertical gap is 15. The gap will be evident when buttons are placed
// in the frame
jframe.setLayout(new BorderLayout(20, 15));
jframe.add(btn1, BorderLayout.NORTH);
jframe.add(btn2, BorderLayout.SOUTH);
jframe.add(btn3, BorderLayout.EAST);
jframe.add(btn4, BorderLayout.WEST);

21 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

jframe.add(btn5, BorderLayout.CENTER);
jframe.setSize(300,300);
jframe.setVisible(true);
}
// main method
public static void main(String argvs[])
{
new BorderLayoutExample();
}
}

GridLayout:
GridLayout is useful to divide the container into a 2D grid form that contains several rows and columns. The
container is divided into equal-sized rectangle; and one component is placed in each rectangle. It looks like below

22 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

Example:
import java.awt.*;
import java.awt.event.*;
class MyFrame extends Frame
{
Button b1,b2,b3,b4;
MyFrame()
{
setLayout(new GridLayout(2,2,20,20));
b1=new Button("PVP");
b2=new Button("VRSEC");
b3=new Button("BEC");
b4=new Button("RVR&JC");
add(b1 );
add(b2);
add(b3);
add(b4);
}
}
class GridDemo
{
public static void main(String arg[])
{
MyFrame f=new MyFrame();

23 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

f.setSize(400,400);
f.setTitle("Event Handling Programs...");
f.setVisible(true);

f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
}
}

Adapter Classes
What is the problem with listener interfaces?

Actually problem does not occur with every listener, but occurs with a few. A few listeners contain more than
one abstract method. For example, WindowListener, used for frame closing, comes with 7 abstract methods.
We are interested in only one abstract method to close the frame, but being WindowListener is an interface,
we are forced to override remaining 6 methods also, just at least with empty body. This is the only problem,
else fine. Some listeners like ActionListener comes with only one abstract method and with them no problem
at all.

Java provides a special feature, called an adapter class, that can simplify the creation of event handlers in
certain situations. An adapter class provides an empty implementation of all methods in an event listener
interface. Adapter classes are useful when you want to receive and process only some of the events that are
handled by a particular event listener interface.

Java adapter classes provide the default implementation of listener interfaces. If you inherit the adapter class,
you will not be forced to provide the implementation of all the methods of listener interfaces. So it saves code.

Adapters are replacement to listeners. The advantage with adapter is we can override any number of
methods we would like and not all.

24 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

For example: Suppose we are interested in setting up only one listener interface method windowClosing() of
the WindowListener interface that causes the program to terminate. In that case, we would not only need to
provide code for windowClosing() method but also need to write empty bodies for the other methods available
in the WindowListener interface.

class WindowEventFrame extends Frame implements WindowListener {


..................
public void windowClosing(WindowEvent e){
System.exit(0);
}
publicvoid windowOpened(WindowEvent e){}
publicvoid windowClosed(WindowEvent e){}
publicvoid windowActivated(WindowEvent e){}
publicvoid windowDeactivated(WindowEvent e){}
publicvoid windowlconified(WindowEvent e){}
publicvoid windowDeiconified(WindowEvent e){}
..................
}

To avoid this unnecessary code, the java.awt.event package provides adapter classes for various event-listener
types.

• Now instead of implementing an event listener interface, you can extend the corresponding event
adapter class and define only those methods in which you are interested.

class MyWindowAdapter extends WindowAdapter {


public void windowClosing(WindowEvent e){
System.exit(0);
}
}

Any listener has more than one abstract method has got a corresponding adapter class. For example,
MouseListener with 5 abstract methods has got a corresponding adapter known as MouseAdapter. But

25 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

ActionListener and ItemListener do not have corresponding adapter class as they contain only one abstract
method.

26 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

Example

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
class AdapterExample extends JFrame
{
AdapterExample()
{
this.addWindowListener( new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
}
class AdapterClassJavaExample
{
public static void main(String [] args)
{
AdapterExample frame = new AdapterExample();
frame.setTitle("Adapter Class Java Example");
frame.setBounds(100,200,200,200);
frame.setVisible(true);
}
}

27 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

Java Inner Classes (Nested Classes)


An inner class is a class defined within another class, or even within an expression.

Listener classes are generally designed with just one purpose in mind: the creation of the listener object for
some GUI object (e.g., a button, window, checkbox, etc...). Given this relationship, separating the code for the
Listener class from the code for the class of the related GUI object seems to, in a certain sense, work against the
notion of the benefits of code encapsulation.

Fortunately, in Java, within the scope of one class, we are allowed to define one or more inner classes(or
nested classes).

Such inner classes can be defined inside the framing class, but outside its methods -- or it may even be defined
inside a method, and they can reference data and methods defined in the outer class in which it nests.

Importance of using Inner Class in Event Handling


What if you want to use an adapter class, but do not want your public class to inherit from an adapter class? For
example, suppose you write an applet, and you want your Applet subclass to contain some code to handle mouse
events. Since the Java language does not permit multiple inheritance, your class cannot extend both the Applet and
MouseAdapter classes. A solution is to define an inner class a class inside of your Applet subclass that extends the
MouseAdapter class.

Inner classes can also be useful for event listeners that implement one or more interfaces directly.

Syntax

class Java_Outer_class{

//code

class Java_Inner_class{

//code

28 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

• An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the
methods and fields of its enclosing instance.

• To instantiate an inner class, you must first instantiate the outer class.

Then, create the inner object within the outer object with this syntax:

• OuterClass.InnerClass innerObject = outerObject.new InnerClass();

EXAMPLE
class OuterClass
{
int x = 10;
class InnerClass
{
int y = 5;
}
}
public class MyMainClass
{ public static void main(String[] args)
{
OuterClass myOuter = new OuterClass();
OuterClass.InnerClass myIn = myOuter.new InnerClass();
System.out.println(myIn.y + myOuter.x);
}
}
// Outputs 15 (5 + 10)

29 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advance Java C.A. SATERI

Unit- 2 Java Swings


Java Swing is a part of Java Foundation Classes (JFC) that is used to create window-based applications. It is
built on the top of AWT (Abstract Windowing Toolkit) API and entirely written in java.
AWT is used for creating GUI in Java. However, the AWT components are internally depends on native methods
like C functions and operating system equivalent and hence problems related to portability arise (look and feel.
Ex. Windows window and MAC window). And, also AWT components are heavy weight. It means AWT
components take more system resources like memory and processor time. Due to this, Java soft people felt it is
better to redevelop AWT package without internally taking the help of native methods. Hence all the classes of
AWT are extended to form new classes and a new class library is created. This library is called JFC (Java
Foundation Classes).

Java Foundation Classes (JFC)


JFC is an extension of original AWT. It contains classes that are completely portable, since the entire JFC is
developed in pure Java.

Some of the features of JFC are:


1. JFC components are light-weight: Means they utilize minimum resources.
2. JFC components have same look and feel on all platforms. Once a component is created, it looks same on any
OS.
3. JFC offers “pluggable look and feel” feature, which allows the programmer to change look and feel as suited
for platform. For, ex if the programmer wants to display window-style button on Windows OS, and Unix style
buttons on Unix, it is possible.
4. JFC does not replace AWT, but JFC is an extension to AWT. All the classes of JFC are derived from AWT
and hence all the methods in AWT are also applicable in JFC.
So, JFC represents class library developed in pure Java which is an extension to AWT and swing is one package
in JFC, which helps to develop GUIs and the name of the package is
import javax.swing.*;
Here x represents that it is an ‘extended package’ whose classes are derived from AWT package.

MVC Architecture
In MVC terminology,
 Model corresponds to the state information associated with the component (data). For example, in the case of
a check box, the model contains a field that indicates if the box is checked or unchecked.
 The view visual appearance of the component based upon model data.

1 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advance Java C.A. SATERI

The controller acts as an interface between view and model. It intercepts all the requests i.e. receives input and
commands to Model / View to change accordingly.
Although the MVC architecture and the principles behind it are conceptually
sound, the high level of separation between the view and the controller is not
beneficial for Swing components. Instead, Swing uses a modified version of
MVC that combines the view and the controller into a single logical entity
called the UI delegate. For this reason, Swing’s approach is called either the
Model-Delegate architecture or the Separable Model architecture.
So let’s review: each Swing component contains a model and a UI delegate.
The model is responsible for maintaining information about the component’s
state. The UI delegate is responsible for maintaining information about how to
draw the component on the screen. In addition, the UI delegate reacts to various
events.

Difference between AWT and Swings


AWT Swing

It is a collection of GUI components and other It is built on top of the AWT API. It is a part of
related services required for GUI programming Oracle’s Java Foundation Classes (JFC) to create java
in java. based front end and GUI applications.

The AWT Component classes are provided by The Swing component classes are provided by the
the java.awt package. javax.swing package.

The Components used in AWT are mainly The Components used in Swing are not dependent on
dependent on the operating system. the operating system. It is completely scripted in Java.

2 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advance Java C.A. SATERI

The AWT is heavyweight since it uses the The Swing is mostly lightweight since it doesn't need
resources of the operating system. any Operating system object for processing.

Does not support pluggable look and feel Support pluggable look and feel

Execution is slower Execution is faster

Has less advanced components Has more advanced components

Components require more memory space Components do not require much memory space

Programmer has to import javax.awt package to Programmer has to import javax.swing package to
develop GUI applications develop GUI applications

Java Swing Hierarchy


The following figure shows hierarchy of classes of javax.swing.

3 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advance Java C.A. SATERI

Containers:
A Container class can be described as a special component that can hold the gathering of the components. An
area that can hold elements.
It is basically a screen where the where the components are placed at their specific locations. Thus it contains
and controls the layout of components.
There are four types of containers in Java AWT:
Window
Panel
Frame
Dialog

Window
A Window object is a top-level window with no borders and no menubar. The default layout for a window is
BorderLayout. A window must have either a frame, dialog, or another window defined as its owner when it's
constructed. We need to create an instance of Window class to create this container.

Frame
• The frame is a subclass of Window. The Frame is the container that contain title bar and border and can
have menu bars. It can have other components like button, textfield, label, etc. In other words, AWT
applications are mostly created using frame container.
• Frame is most widely used container while developing an AWT application.
• The frame will be visible only when the two methods – setSize( ) and setVisible( ) are set.

Panel: Panel class is a subclass of Container and is a super class of Applet. When screen output is redirected
to an applet, it is drawn on the surface of the Panel object. In, essence panel is a window that does not contain a
title bar, menu bar or border.

4 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advance Java C.A. SATERI

Swing defines two types of containers.


1. Top-level containers/ Root containers: The top level containers are JFrame, JApplet,JWindow, and
JDialog. As the name implies, a top-level container must be at the top of a containment hierarchy. A top-
level container is not contained within any other container. the top-level containers are heavyweight.
Because they inherit AWT classes Component and Container.
2. Whenever we create a top level container four sub-level containers are automatically created:

Glass pane (JGlass)


Root pane (JRootPane)
Layered pane (JLayeredPane)
Content pane

Glass pane: This is the first pane and is very close to the monitor’s screen. Any components to be displayed in
the foreground are attached to this glass pane. To reach this glass pane we use getGlassPane() method of JFrame
class, which return Component class object.

Root Pane: This pane is below the glass pane. Any components to be displayed in the background are displayed
in this frame. To go to the root pane, we can use getRootPane() method of JFrame class, which returns JRootPane
object.

Layered pane: This pane is below the root pane. When we want to take several components as a group, we
attach them in the layered pane. We can reach this pane by calling getLayeredPane() method of JFrame class
which returns JLayeredPane class object.

Conent pane: This is bottom most of all, Individual components are attached to this pane. To reach this pane,
we can call getContentPane() method of JFrame class which returns Container class object.

5 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advance Java C.A. SATERI

2. Lightweight containers – containers do inherit JComponent. An example of a lightweight


container is JPanel, which is a general-purpose container. Lightweight containers are often used to
organize and manage groups of related components.

Creating Panel

Creating a JFrame
Frame represents a window with a title bar and borders. Frame becomes the basis for creating the GUIs for an
application because all the components go into the frame.

To create a frame, we have to create an object to JFrame class in swing as

JFrame jf=new JFrame(); // create a frame without title


JFrame jf=new JFrame(“title”); // create a frame with title
To close the frame, use setDefaultCloseOperation() method of JFrame class
setDefaultCloseOperation(constant)

where constant values are

6 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advance Java C.A. SATERI

7 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advance Java C.A. SATERI

Components
• Anything that can be placed on a user interface and can be made visible or resized.
• Components are basic building blocks of an application. Swing has a wide range of various
components, including buttons, check boxes, sliders, and checkboxes.

Various components are shown :

JComponent:
The class JComponent is the base class for all Swing components except top-level

8 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advance Java C.A. SATERI

containers. To use a component that inherits from JComponent, you must place the
component in a containment hierarchy whose root is a top-level SWING container.

The JButton Class


The JButton class provides the functionality of a push button. JButton allows an icon, a string, or both to be
associated with the push button. Some of its constructors are
shown here:
JButton(Icon i)
JButton(String s)
JButton(String s, Icon i)
Here, s and i are the string and icon used for the button.
• A Buttoncan be implemented in the application by calling one of its constructors.
• JButton okBtn = new JButton("Ok");

9 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advance Java C.A. SATERI

Example to demonstrate the use of Button


import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class testswing extends JFrame
{
testswing()
{
JButton bt1 = new JButton("Yes"); //Creating a Yes Button.
JButton bt2 = new JButton("No"); //Creating a No Button.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) //setting close operation.
setLayout(new FlowLayout()); //setting layout using FlowLayout object
setSize(400, 400); //setting size of Jframe
add(bt1); //adding Yes button to frame.
add(bt2); //adding No button to frame.
setVisible(true);
}
public static void main(String[] args)
{
new testswing();
}
}

10 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advance Java C.A. SATERI

TextField
• JTextField renders an editable single-line text box. A user can input non-formatted text in the box.
• To initialize the text field, call its constructor and pass an optional integer parameter to it. This parameter
sets the width of the box measured by the number of columns.
• It does not limit the number of characters that can be input in the box.
Syntax
• JTextField(int cols)
• JTextField(String str, int cols)
• JTextField(String str)

JTextField txtBox = new JTextField(20);


It renders a text box of 20 column width.

Program to Demonstrate TextField


import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class MyTextField extends JFrame
{
public MyTextField()
{
JTextField jtf = new JTextField(20); //creating JTextField.
add(jtf); //adding JTextField to frame.
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setVisible(true);

11 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advance Java C.A. SATERI

}
public static void main(String[] args)
{
new MyTextField();
}
}

JLabel

• JLabel class is used to render a read-only text label or images on the UI. It does not generate any event.

• JLabel textLbl = new JLabel("This is a text label.");

Syntax
• Label()
Creates an empty label
• Label(String labeltext)
Creates a label with a given text
• Label(String labeltext, int alignment)
Creates a label with given alignment where alignment can be Label.LEFT, Label.RIGHT or
Label.CENTER

Important Methods:
Icon getIcon()
String getText()
void setIcon(Icon icon)
void setText(String s)

12 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advance Java C.A. SATERI

Program to demonstrate use of Label


import javax.swing.*;
class SLabelDemo1
{
public static void main(String args[])
{
JFrame label_f= new JFrame("studytonight ==> Label Demo");
JLabel label_l1,label_l2;
label_l1=new JLabel("Welcome to studytonight.com");
label_l1.setBounds(50,50, 200,30);
label_l2=new JLabel("How are You?");
label_l2.setBounds(50,100, 200,30);
label_f.add(label_l1);
label_f.add(label_l2);
label_f.setSize(300,300);
label_f.setLayout(null);
label_f.setVisible(true);
}
}

TextArea
JTextArea class renders a multi-line text box. Similar to the JTextField, a user can input non-formatted text in
the field.
The constructor for JTextArea also expects two integer parameters which define the height and width of the text-
area in columns. It does not restrict the number of characters that the user can input in the text-area.
JTextArea txtArea = new JTextArea("This text is default text for text area.", 5, 20);
The above code renders a multi-line text-area of height 5 rows and width 20 columns, with default text initialized
in the text-area.

The JTextArea Contains 4 constructors. They are as following:

13 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advance Java C.A. SATERI

TextArea( ) Creates a new TextArea


TextArea(String s)
TextArea(int rows, int cols)
Creates a new TextArea with given number of rows and columns
TextArea(String text, int rows, int cols)
Creates a new TextArea with given string, given number of rows and columns

Program to demonstrate the use of Text Area


import javax.swing.*;
public class STextAreaDemo1
{
STextAreaDemo1()
{
JFrame textArea_f= new JFrame();
JTextArea textArea_area=new JTextArea("Welcome to studytonight.com ");
textArea_area.setBounds(10,30, 200,200);
textArea_f.add(textArea_area);
textArea_f.setSize(400,400);
textArea_f.setLayout(null);
textArea_f.setVisible(true);
}
public static void main(String args[])
{
new STextAreaDemo1();
}
}

14 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advance Java C.A. SATERI

CheckBox
•Used for multi-option user input that the user may select or deselect by clicking them.
•CheckBox renders a check-box with a label. The check-box has two states – on/off. When selected, the
state is on and a small tick is displayed in the box.
• CheckBox chkBox = new JCheckBox("Show Help", true);
• It returns a checkbox with the label Show Help. Notice the second parameter in the constructor. It is a
boolean value that indicates the default state of the check-box. True means the check-box is defaulted
to on state.
Some of its constructors are shown here:
JCheckBox(Icon i)
JCheckBox(Icon i, boolean state)
JCheckBox(String s)
JCheckBox(String s, boolean state)
JCheckBox(String s, Icon i)
JCheckBox(String s, Icon i, boolean state)
Here, i is the icon for the button. The text is specified by s. If state is true, the check box is initially selected.
Otherwise, it is not.
The state of the check box can be changed via the following method:

15 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advance Java C.A. SATERI

void setSelected(boolean state)


Here, state is true if the check box should be checked.
When a check box is selected or deselected, an item event is generated. This is
handled by itemStateChanged( ). Inside itemStateChanged( ), the getItem( ) method gets the JCheckBox object
that generated the event. The getText( ) method gets the text for that check box and uses it to set the text inside
the text field.
Program to demonstrate CheckBox
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Test extends JFrame
{
public Test()
{
JCheckBox jcb = new JCheckBox("yes"); //creating JCheckBox.
add(jcb); //adding JCheckBox to frame.
jcb = new JCheckBox("no"); //creating JCheckBox.
add(jcb); //adding JCheckBox to frame.
jcb = new JCheckBox("maybe"); //creating JCheckBox.
add(jcb); //adding JCheckBox to frame.
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setVisible(true);
}
public static void main(String[] args)
{ new Test();
} }

16 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advance Java C.A. SATERI

ComboBox
• Combo box is used to create a drop-down menu. Combo box is a combination of text fields and drop-
down list.
• String[] cityStrings = { "Mumbai", "London", "New York", "Sydney", "Tokyo" }; JComboBox cities =
new JComboBox(cityList); cities.setSelectedIndex(3);
• The default selected option can be specified through the setSelectedIndex method. The above code sets
Sydney as the default selected option.

Two of JComboBox’s constructors are shown here:


JComboBox( )
JComboBox(Vector v)
Here, v is a vector that initializes the combo box. Items are added to the list of choices
via the addItem( ) method, whose signature is shown here:
void addItem(Object obj)

17 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advance Java C.A. SATERI

Here, obj is the object to be added to the combo box.


By default, a JComboBox component is created in read-only mode, which means the
user can only pick one item from the fixed options in the drop-down list. If we want to allow
the user to provide his own option, we can simply use the setEditable() method to make the
combo box editable.

Program to demonstrate the use of ComboBox


import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Test extends JFrame
{
String name[] = {"Abhi","Adam","Alex","Ashkay"}; //list of name.
public Test()
{
JComboBox jc = new JComboBox(name); //initialzing combo box with list of name.
add(jc); //adding JComboBox to frame.
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setVisible(true);
}
public static void main(String[] args)
{
new Test();
}
}

18 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advance Java C.A. SATERI

Radio Button
Radio button is a group of related button in which only one can be selected.
ButtonGroup radioGroup = new ButtonGroup();
JRadioButton rb1 = new JRadioButton("Easy", true);
JRadioButton rb2 = new JRadioButton("Medium");
JRadioButton rb3 = new JRadioButton("Hard");
radioGroup.add(rb1);
radioGroup.add(rb2);
radioGroup.add(rb3);
The above code creates a button group and three radio button elements. All three elements are then added to
the group. This ensures that only one option out of the available options in the group can be selected at a time.
The default selected option is set to Easy.
Some of its constructors are shown here:
JRadioButton(Icon i)
JRadioButton(Icon i, boolean state)
JRadioButton(String s)
JRadioButton(String s, boolean state)
JRadioButton(String s, Icon i)
JRadioButton(String s, Icon i, boolean state)
Here, i is the icon for the button. The text is specified by s. If state is true, the button
is initially selected. Otherwise, it is not.
Radio buttons must be configured into a group. Only one of the buttons in that group
can be selected at any time. For example, if a user presses a radio button that is in a group,
any previously selected button in that group is automatically deselected. The ButtonGroup
class is instantiated to create a button group. Its default constructor is invoked for this
purpose. Elements are then added to the button group via the following method:
void add(AbstractButton ab)
Here, ab is a reference to the button to be added to the group.
Radio button presses generate action events that are handled by actionPerformed( ).
The getActionCommand( ) method returns the text that is associated with a radio button and
uses it to set the text field.

19 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advance Java C.A. SATERI

Program to demonstrate the use of Radio Button


import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Test extends JFrame
{
public Test()
{
JRadioButton jcb = new JRadioButton("A"); //creating JRadioButton.
add(jcb); //adding JRadioButton to frame.
jcb = new JRadioButton("B"); //creating JRadioButton.
add(jcb); //adding JRadioButton to frame.
jcb = new JRadioButton("C"); //creating JRadioButton.
add(jcb); //adding JRadioButton to frame.
jcb = new JRadioButton("none");
add(jcb);
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setVisible(true);
}
public static void main(String[] args)
{
new Test();
} }

20 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advance Java C.A. SATERI

List
List component renders a scrollable list of elements. A user can select a value or multiple values from the list.
This select behavior is defined in the code by the developer.
DefaultListItem cityList = new DefaultListItem(); cityList.addElement("Mumbai"):
cityList.addElement("London"):
cityList.addElement("New York"):
cityList.addElement("Sydney"):
cityList.addElement("Tokyo"):
JList cities = new JList(cityList);
cities.setSelectionModel(ListSelectionModel.SINGLE_SELECTION);
The above code renders a list of cities with 5 items in the list. The selection restriction is set to
SINGLE_SELECTION. If multiple selections is to be allowed, set the behavior to
MULTIPLE_INTERVAL_SELECTION.
Constructors
• JList()
• JList(Object arr[])
• JList(Vector v)
– Methods
• getSelectedIndex() – returns selected item index
• getSelectedValue() – to know which item is selected in the list
• getSelectedIndices() – returns selected items into an array
• getSelectedValues() – returns selected items names into an array

JList generates ListSelectionEvent


– ListSelectionListener
• void valueChanged(ListSelectionEvent)
– Package is javax.swing.event.*;

Example :

21 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advance Java C.A. SATERI

import javax.swing.*;
public class SListDemo
{
SListDemo()
{
JFrame list_f= new JFrame();
DefaultListModel<String> list_l1 = new DefaultListModel<>();
list_l1.addElement("Red");
list_l1.addElement("Pink");
list_l1.addElement("Blue");
list_l1.addElement("Black");
JList<String> list1 = new JList<>(list_l1);
list1.setBounds(100,100, 75,75);
list_f.add(list1);
list_f.setSize(400,400);
list_f.setLayout(null);
list_f.setVisible(true);
}
public static void main(String args[])
{
new SListDemo();
}
}

22 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advance Java C.A. SATERI

Menu Bar
Creating Menu

Menus are placed on a menu bar, which is attached to a frame. The object of MenuItem class adds a simple
labeled menu item on menu. The items used in a menu must belong to the MenuItem or any of its subclass.

The object of Menu class is a pull down menu component which is displayed on the menu bar. It inherits the
MenuItem class.

import java.awt.*;
class MenuExample
{
MenuExample(){
Frame f= new Frame("Menu and MenuItem Example");
MenuBar mb=new MenuBar();
Menu menu=new Menu("Menu");
Menu submenu=new Menu("Sub Menu");
MenuItem i1=new MenuItem("Item 1");
MenuItem i2=new MenuItem("Item 2");
MenuItem i3=new MenuItem("Item 3");
MenuItem i4=new MenuItem("Item 4");
MenuItem i5=new MenuItem("Item 5");
menu.add(i1);
menu.add(i2);
menu.add(i3);
submenu.add(i4);
submenu.add(i5);
menu.add(submenu);
mb.add(menu);
f.setMenuBar(mb);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}

23 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advance Java C.A. SATERI

public static void main(String args[])


{
new MenuExample();
} }

JScrollPane
• A JscrollPane is used to make scrollable view of a component. When screen size is limited, we use a
scroll pane to display a large component or a component whose size can change dynamically.
• When screen size is limited, we use a scroll pane to display a large component or a component whose
size can change dynamically.
• JScrollPane component should be inside the container like JFrame or Jpanel.

24 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advance Java C.A. SATERI

import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class Jscrollpane {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
JTextArea tArea = new JTextArea(10,10);

25 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advance Java C.A. SATERI

JScrollPane scrollPane = new


JScrollPane(tArea,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLL
BAR_ALWAYS);
panel.add(scrollPane);
frame.setContentPane(panel);
frame.setSize(500, 500);
frame.setLocationByPlatform(true);
frame.setVisible(true); } }

Can be also written as below :


• JScrollPane scrollPane = new JScrollPane(tArea);
• scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
• scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
• scrollPane.setColumnHeaderView(labelColumn);
• scrollPane.setRowHeaderView(labelRow);

Examples
SetBounds Method

26 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advance Java C.A. SATERI

The layout managers are used to automatically decide the position and size of the added components. In the
absence of a layout manager, the position and size of the components have to be set manually.
The setBounds() method is used in such a situation to set the position and size. To specify the position and size
of the components manually, the layout manager of the frame can be null.

The setBounds() method needs four arguments. The first two arguments are x and y coordinates of the top-
left corner of the component, the third argument is the width of the component and the fourth argument is
the height of the component.

Syntax

setBounds(int x-coordinate, int y-coordinate, int width, int height)

Java Swing Example

import javax.swing.*;
public class SwingApp {
SwingApp()
{
JFrame f = new JFrame();

JLabel firstName = new JLabel("First Name");


firstName.setBounds(20, 50, 80, 20);

JLabel lastName = new JLabel("Last Name");


lastName.setBounds(20, 80, 80, 20);

JLabel dob = new JLabel("Date of Birth");


dob.setBounds(20, 110, 80, 20);

JTextField firstNameTF = new JTextField();


firstNameTF.setBounds(120, 50, 100, 20);

JTextField lastNameTF = new JTextField();


lastNameTF.setBounds(120, 80, 100, 20);

JTextField dobTF = new JTextField();

27 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advance Java C.A. SATERI

dobTF.setBounds(120, 110, 100, 20);

JButton sbmt = new JButton("Submit");


sbmt.setBounds(20, 160, 100, 30);

JButton reset = new JButton("Reset");


reset.setBounds(120,160,100,30);

f.add(firstName);
f.add(lastName);
f.add(dob);
f.add(firstNameTF);
f.add(lastNameTF);
f.add(dobTF);
f.add(sbmt);
f.add(reset);

f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}

public static void main(String[] args) {


// TODO Auto-generated method stub
SwingApp s = new SwingApp();
}
}

28 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advance Java C.A. SATERI

Message Box in Java


• The Message Box in Java is the pop-up that appears on the screen for displaying some information to
the user and waits for confirmation from the user.
• Message dialogs are created with the JOptionPane.showMessageDialog() method.
• The term JOptionPane is the Java-provided class that provides users the privilege to show message
dialogue boxes.

The JOptionPane Class


You can create a standard dialog box using one of several static methods belonging to the JOptionPane class.
These include:
• showMessageDialog(), which relays a message to the user.
• showConfirmDialog(), which asks a question that requires confirmation.
• showInputDialog(), which prompts a user for input.
• showOptionDialog(), which is a combination of the three other methods.

Program to demonstrate the use of MessageBox


import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class JOptionPaneApp


{
JOptionPaneApp()

29 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advance Java C.A. SATERI

{
JFrame frame = new JFrame();
JOptionPane.showMessageDialog(frame, "This is a JOptionPane message window.");
}

public static void main(String[] args)


{
new JOptionPaneApp();
}
}

The message type is one of the following constants :


• ERROR_MESSAGE
• WARNING_MESSAGE
• QUESTION_MESSAGE
• INFORMATION_MESSAGE

import javax.swing.*;
public class OptionPaneExample {
OptionPaneExample()
{
JFrame frame = new JFrame();
JOptionPane.showMessageDialog(f,"Successfully Updated.","Alert",JOptionPane.WARNING_MESSA
GE);
}
public static void main(String[] args) {
new OptionPaneExample();
}
}

30 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advance Java C.A. SATERI

JOptionPane.showMessageDialog(frame, "This is a JOptionPane error message window.", "Error",


JOptionPane.ERROR_MESSAGE);

import javax.swing.*;
public class OptionPaneExample {
JFrame f;
OptionPaneExample()
{
f=new JFrame();
String name=JOptionPane.showInputDialog(f,"Enter Name");
}
public static void main(String[] args) {
new OptionPaneExample();
}
}

Program to demonstrate Event Handling and MessageBox


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class Demo extends JFrame implements ActionListener


{
// Declaration of object of JButton class.
JButton b1;

// Constructor of Demo class


Demo()
{

31 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advance Java C.A. SATERI

// Setting layout as null of JFrame.


this.setLayout(null);

// Initialization of object of "JButton" class.


b1 = new JButton("Button 1");

// Setting Bounds of a JButton.


b1.setBounds(130, 05, 100, 50);

//"this" keyword in java refers to current object.


// Adding JButton on JFrame.
this.add(b1);

// Adding Listener toJButton.


b1.addActionListener(this);
}
public void actionPerformed(ActionEvent evt)
{
if (evt.getSource() == b1)
{
// Code To popup an ERROR_MESSAGE Dialog.
JOptionPane.showMessageDialog(this, "Enter a valid Number","ERROR",
JOptionPane.ERROR_MESSAGE);
}
}
}

class MessageDialogs1 {

// Driver code
public static void main(String args[])
{
// Creating Object of demo class.
Demo f = new Demo();

// Setting Bounds of a Frame.


f.setBounds(200, 200, 400, 300);

// Setting Resizable status of frame as false


f.setResizable(false);

// Setting Visible status of frame as true.


f.setVisible(true);

32 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advance Java C.A. SATERI

}
}

33 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

Unit – 3 JDBC
The term JDBC is an abbreviation for Java Database Connectivity. It is a built-in API available in Java that is
used to connect with databases and execute queries.

JDBC API can be used to do the following:


• Directly connect to a database
• Creating SQL statements and queries
• Execute queries in the database
• Retrieve database objects such as Tables, Indices, etc. from the database.
• Viewing & Modifying the resulting records.

JDBC has four major components that are used for the interaction with the database.
1. JDBC API :
Using the JDBC API, applications can execute SQL.
statements, retrieve results, and propagate changes back to an underlying data source.

2. JDBC Test Suite :


The JDBC driver test suite helps you to determine that JDBC drivers will run your program. These tests are
not comprehensive or exhaustive, but they do exercise many of the important features in the JDBC API.

3. JDBC Driver Manger :


The JDBC DriverManager class defines objects which can connect Java applications to a JDBC driver.

4. JDBC ODBC Bridge Driver :


The Java Software Bridge provides JDBC access via ODBC drivers. Note that you need to load ODBC binary
code onto each client machine that uses this driver.

JDBC Architecture
JDBC supports two types of processing models for accessing database i.e. two-tier and three-tier.
1. Two-tier Architecture
This architecture helps java program or application to directly communicate with the database. It needs a JDBC
driver to communicate with a specific database. Query or request is sent by the user to the database and results are
received back by the user.
2. Three-tier Architecture
In this, there is no direct communication. Requests are sent to the middle tier i.e. HTML browser sends a request
to java application which is then further sent to the database. Database processes the request and sends the result
back to the middle tier which then communicates with the user.

1 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

The JDBC Architecture has two layers, they are:


• JDBC API
• JDBC Driver API

2 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

• JDBC API: JDBC API provides various interfaces and methods to establish easy connection with
different databases also used to perform various operations like: connect, read, write and store data in
the database. Provides connection from Application to JDBC Manager.
• JDBC Driver API - JDBC Driver is a software component that enables java application to
interact with the database. Supports the connection between JDBC Manager and the Driver.

Why Should We Use JDBC


• Before JDBC, ODBC API was the database API to connect and execute the query with the database.
• But, ODBC API uses ODBC driver which is written in C language i.e. platform dependent and
unsecured. That is why Java has defined its own API that is JDBC API that uses JDBC drivers written
in Java language.
• To connect to a database from a Java program, you must use a JDBC driver made specifically for the
database to which you want to connect.
• To connect to a MySQL database, you must download a MySQL JDBC driver.
• To connect to an Oracle database, you must download an Oracle JDBC driver.

Types of JDBC Drivers


There are two packages i.e., java.sql and javax.sql that are known for JDBC connections and executions. Java
uses JDBC drivers to connect with any database. They are of 4 types:
• Type 1 Driver: JDBC-ODBC Bridge.
• Type 2 Driver: Native-API Driver (Partly Java driver).
• Type 3 Driver: Network-Protocol Driver (Pure Java driver for database Middleware).
• Type 4 Driver: Native-Protocol Driver (Pure Java driver directly connected to database).

Type 1 Driver: JDBC-ODBC Bridge


The JDBC type 1 driver which is also known as a JDBC-ODBC Bridge is a converter which converts JDBC
methods into ODBC function calls. The driver is a platform dependent because it uses ODBC which is depends
on native libraries of the operating system and also the driver needs other installation for example, ODBC must be
installed on the computer and the database must support ODBC driver.
Type 1 is the simplest compare to all other driver but it’s a platform specific i.e. only on Microsoft platform. The
JDBC-ODBC Bridge is used only when there is no PURE-JAVA driver available for a particular database.
When Java first came out, this was a useful driver because most databases only supported ODBC access but now
this type of driver is recommended only for experimental use or when no other alternative is available.

3 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

Process:
Java Application → JDBC APIs → JDBC Driver Manager → Type 1 Driver → ODBC Driver → Database library APIs →
Database.
Advantage:
1. Connect to almost any database on any system, for which ODBC driver is installed.
2. Its an easy for installation as well as easy(simplest) to use as compare the all other driver.
Disadvantage:
1. The ODBC Driver needs to be installed on the client machine.
2. It is a not a purely platform independent because its use ODBC which is depends on native libraries of the operating
system on client machine.
3. Not suitable for applets because the ODBC driver needs to be installed on the client machine.

Type 2 Driver: Native-API Driver (Partly Java driver):-


The JDBC type 2 driver is uses the libraries of the database which is available at client side and this driver
converts the JDBC method calls into native calls of the database so this driver is also known as a Native-API
driver.

4 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

Process:
Java Application → JDBC APIs → JDBC Driver Manager → Type 2 Driver → Vendor Client Database library
APIs → Database
Advantage:
1. There is no implantation of JDBC-ODBC Bridge so it’s faster than a type 1 driver; hence the performance is
better as compare the type 1 driver (JDBC-ODBC Bridge).
Disadvantage:
1. On the client machine require the extra installation because this driver uses the vendor client libraries.
2. The Client side software needed so cannot use such type of driver in the web-based application.
3. Not all databases have the client side library.
4. This driver supports all JAVA applications except applets.

Type 3 Driver: Network-Protocol Driver (Pure Java driver for database Middleware):-
The JDBC type 3 driver uses the middle tier(application server) between the calling program and the database and
this middle tier converts JDBC method calls into the vendor specific database protocol and the same driver can be
used for multiple databases also so it’s also known as a Network-Protocol driver as well as a JAVA driver for
database middleware.

Process:
• Java Application → JDBC APIs → JDBC Driver Manager → Type 2 Driver → Vendor Client
Database library APIs → Database
Advantage:
• 1. There is no need for the vendor database library on the client machine because the middleware is
database independent and it communicates with client.
• 2. Type 3 driver can be used in any web application as well as on internet also because there is no any
software require at client side.

5 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

• 3. A single driver can handle any database at client side so there is no need a separate driver for each
database.
• 4. No client side library is required because of application server that can perform many tasks like
auditing, load balancing, logging etc.

Disadvantage:
1. On the client machine require the extra installation because this driver uses the vendor client libraries.
2. The Client side software needed so cannot use such type of driver in the web-based application.
3. Not all databases have the client side library.
4. This driver supports all JAVA applications except applets.

Type 4 Driver: Native-Protocol Driver (Pure Java driver directly connected to database):-
The JDBC type 4 driver converts JDBC method calls directly into the vendor specific database protocol and in
between do not need to be converted any other formatted system so this is the fastest way to communicate quires
to DBMS and it is completely written in JAVA because of that this is also known as the “direct to database Pure
JAVA driver”.

Process:
Java Application → JDBC APIs → JDBC Driver Manager → Type 4 Driver (Pure JAVA Driver) → Database Server
Advantage:
1.Better performance than all other drivers.
2.It is a 100% pure JAVA Driver so it’s a platform independence.
3. No translation or middleware layers are used so consider as a faster than other drivers.
4. The all process of the application-to-database connection can manage by JVM so the debugging is also managed easily.
Disadvantage:
1. There is a separate driver needed for each database at the client side.
2. Drivers are Database dependent, as different database vendors use different network protocols

6 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

Which Driver to use When?

• If you are accessing one type of database, such as Oracle, Sybase, or IBM, the preferred driver type is
type-4.
• If your Java application is accessing multiple types of databases at the same time, type 3 is the
preferred driver.
• Type 2 drivers are useful in situations, where a type 3 or type 4 driver is not available yet for your
database.
• The type 1 driver is not considered a deployment-level driver, and is typically used for development
and testing purposes only. And used only when type 2, type 3 and type 4 are not available.

Comparision between Types of drivers

7 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

JDBC Process
• The JDBC process consists of 5 steps as below.
• 1. Loading the JDBC driver.
• 2. Establish the connection to DBMS.
• 3. Create and execute the statements.
• 4. Processing the data returned by DBMS.
• 5. Close the connection with the DBMS.

1. Loading the JDBC driver


• To load the driver, you need to load the appropriate class, make a driver instance and register it
• with the JDBC driver manager. Use Class.forName(String) method. This method takes a string
• representing a fully qualified class name and loads the corresponding class.
• Example: Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
• Class.forName(“oracle.jdbc.OracleDriver"); type 4 driver of oracle
• Class.forName(“oracle.jdbc.driver.OracleDriver”);

2. Establishing a connection to Database


• Once you have loaded the JDBC driver, you need to specify the location of the database server.
• Generally, the url format is: jdbc:odbc:studentinfo plus server host, port number and database name.
• To make the actual network connection, pass the URL, the database username, and the password to the
getConnection( ) method of the DriverManager class, as illustrated in the following.

8 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

Example
• String username = "mca";
• String password = "rnsit";
• Connection con = DriverManager.getConnection(url, username, password);
• getconnection() method : The getConnection(String url, Properties info) method of
Java DriverManager class attempts to establish a connection to the database by using
the given database url.
• The appropriate driver from the set of registered JDBC drivers is selected. Properties
are implementation-defined as to which value will take precedence.
Example
String URL = "jdbc:oracle:thin:@amrood:1521:EMP";
String USER = "username";
String PASS = "password"
Connection conn = DriverManager.getConnection(URL, USER, PASS);
String URL = "jdbc:oracle:thin:username/password@amrood:1521:EMP";
Connection conn = DriverManager.getConnection(URL);
Connection con = DriverManager.getConnection(“URL”,”USERNAME”,”PASSWORD”)
Class.forName(“oracle.jdbc.driver.OracleDriver”);
DriverManager.getConnection(“jdbc:oracle:thin:@localhost:1521:XE”,”scott”,”tiger”); - type 4

3. Prepare, send and execute query


• SQL commands are instructions. It is used to communicate with the database. It is also used to
perform specific tasks, functions, and queries of data.
• Various Operations of database – divided into multiple categories

Types of SQL Commands

9 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

Data Definition Language (DDL)


• DDL changes the structure of the table like creating a table, deleting a table, altering a table, etc.
Data Manipulation Language
• DML commands are used to modify the database. It is responsible for all form of changes in the
database.
Data Control Language
• DCL commands are used to grant and take back authority from any database user.
Transaction Control Language
• TCL commands can only use with DML commands like INSERT, DELETE and UPDATE only.
• These operations are automatically committed in the database that's why they cannot be used while
creating tables or dropping them.
Data Query Language
• DQL is used to fetch the data from the database.
From java developer point of view only two queries are required –

Select queries – Are DQL eg- select * from employees;


Non-select queries – Are DML eg – insert, delete, update

Which Methods will be used in programs will be decided on this division.

Basic SQL commands


To create a table
• CREATE TABLE EMPLOYEE (
• CODE INT NOT NULL,
• NAME VARCHAR (15) NOT NULL,
• AGE INT NOT NULL,
• PRIMARY KEY (CODE)
• );
To insert rows into table
• INSERT INTO Students VALUES(12, ‘sudarshan', 4, '1996-10-12');

To delete/drop table
drop table employees;

DELETE FROM Students WHERE StudentId = 11;

To update data
UPDATE Students
SET DepartmentId = 3
WHERE StudentId = 6;

10 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

Retrieving data

SELECT * FROM Students;


SELECT * FROM Students WHERE StudentId = 6;

Create and execute the statements


A Statement object is used to send queries and commands to the database and is created from the Connection.
String query = "SELECT * FROM student";
ResultSet res = stmt.executeQuery(query);
To modify the database, use executeUpdate( ) instead of executeQuery( ), and supply a string that uses UPDATE,
INSERT, or DELETE.

Statement object
Statement object is used to send the queries to the database.
Statement stmt = con.createStatement();
Once you have a Statement object, you can use it to send SQL queries by using the executeQuery method, which
returns an object of type ResultSet.
Execute sql methods
• executeQuery()
• executeUpdate()
• execute()

executeQuery() executeUpdate() execute()

This method is use to execute the


SQL statements which retrieve This statement is used to execute SQL
some data from database. statements which update or modify
This method can
Eg : ResultSet rs = database.
be use for any
st.executequery(“select * from int rowcount =
kind of SQL
students”); stmt.executeUpdate("INSERT INTO
statements.
Emp VALUES(6000,'Jones')");

These methods must be call on statement object.


• boolean execute(String SQL) : Returns a boolean value of true if a ResultSet object can
be retrieved; otherwise, it returns false. Use this method to execute SQL DDL statements
or when you need to use truly dynamic SQL.

Example: Statement st=con.createStatement( );


st.execute(“select * from student”);

11 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

• int executeUpdate(String SQL) : Returns the numbers of rows affected by the execution
of the SQL statement. Use this method to execute SQL statements for which you expect
to get a number of rows affected - for example, an INSERT, UPDATE, or DELETE
statement.
Example: Statement st=con.createStatement( );
int i=st.executeUpdate(“select * from student”);
Here value of i represent number of records selected.

• ResultSet executeQuery(String SQL) : Returns a ResultSet object. Use this method


when you expect to get a result set, as you would with a SELECT statement.
Example: Statement st=con.createStatement( );
ResultSet res;
res = st.execute(“select * from student”);

4. Processing the data returned by DBMS


The simplest way to handle the results is to process them one row at a time, using the ResultSet’s next( ) method
to move through the table a row at a time. Within a row, ResultSet provides various getXxx( ) methods that take a
column index or column name as an argument and return the result as a variety of different Java types. For
example, use getInt( ) if the value should be an integer, getString( ) for a String, and so on for most other data
types. If you just want to display the results, you can use getString( ) regardless of the actual column type.

Note that the first column in a ResultSet row has index 1, not 0.
Example:
while(res.next())
{
System.out.println(res.getString(1) + " " + res.getString(2) + " " + res.getString(3));
}

5. Close the connection with DBMS


To close the connection explicitly, you should do:
con.close( );
You should postpone this step if you expect to perform additional database operations, since the overhead of
opening a connection is usually large. In fact, reusing existing connections is such an important optimization.

Executing Statements Once a Statement object is created, we can use it to execute a SQL statement with one of its
three execute methods.

Execute sql methods


• executeQuery()
• executeUpdate()
• execute()

12 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

executeQuery() executeUpdate() execute()

This method is use to execute the


SQL statements which retrieve This statement is used to execute SQL
some data from database. statements which update or modify
This method can
Eg : ResultSet rs = database.
be use for any kind
st.executequery(“select * from int rowcount =
of SQL
students”); stmt.executeUpdate("INSERT INTO
statements.
Emp VALUES(6000,'Jones')");

Examples :

Execution
1. Go to oracle and type select * from employees; // error
2. desc employees; //error
3. Go to command prompt and compile and run the program
javac CreateTableDemo.java
java CreateTableDemo
4. Now go to oracle and repeat first two steps.

13 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

ResultSet
• The ResultSet object contains the data returned by the database. executeQuery( ) method returns
the ResultSet object that contains the data was requested by the query.
• The ResultSet object contains methods that are used to copy data from ResultSet into java
collection object or variable for further processing.
• Data in a ResultSet object is logically organized into a virtual table consisting of rows and
columns. In addition to data, it also contains meta data such as column name, column type etc.
• The ResultSet uses a virtual cursor to point to a row of a virtual table. A J2EE component must
move the virtual cursor to each row and the other methods of ResultSet object to interact with the
data stored in columns in that row.
• The virtual cursor is positioned above the first row of the data when the ResultSet is returned by
the executeQuery( ) method. So virtual cursor must be moved to first row using next( ) method.
• The next( ) method returns a Boolean true if row contains the data, otherwise, a Boolean value
false is returned indicating that no more rows exists in the ResultSet.
• Once the virtual cursor points to a row, the getXXX( ) method is used to copy data from the row
to variable.

Example: Statement stmt = connection.createStatement();


String selectquery = "select * from user";
ResultSet res = stmt.executeQuery(selectquery);
while(res.next( ))
{
System.out.print("User ID :" + res.getInt(1)+ " ");
System.out.println("User Name :" + res.getString(2));
}

ACCESSING THE RECORDS FROM ResultSet


Example :
String query = "SELECT COF_NAME, PRICE FROM COFFEES";
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String s = rs.getString("COF_NAME");
float n = rs.getFloat("PRICE");
System.out.println(s + " " + n);

14 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

}
Output :
• Colombian 7.99
• French_Roast 8.99
• Espresso 9.99
• Colombian_Decaf 8.99
• French_Roast_Decaf 9.99

The second way is to give the column index (number of the column), with 1 signifying the first column, 2 , the
second, and so on. Using the column number instead of the column name looks like this:
String s = rs.getString(1);
float n = rs.getFloat(2);
The first line of code gets the value in the first column of the current row of rs (column COF_NAME ),
converts it to a Java String object, and assigns it to s .
The second line of code gets the value stored in the second column of the current row of rs , converts it to a
Java float , and assigns it to n .
Note that the first column in a ResultSet row has index 1, not 0.

Example:
while(res.next())
{
System.out.println(res.getString(1) + " " + res.getString(2)
+ " " + res.getString(3));
}

Extracting and Displaying


import java.sql.*;
class JavaTester{
public static void main(String args[]){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/'yourDBname'","username","userpassword");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
con.close();
}
catch(Exception e){ System.out.println(e);}

15 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

}
}

Scrollable ResultSet
Until JDBC 2.1 API, the virtual cursor can be moved only downwards. Now virtual cursor can
be moved backwards or even positioned at a specific row. Such ResultSet are called Scrollable
ResultSet.
The statement object that is created using the createStatement( ) of Connection object must be set
up to handle a scrollable ResultSet by passing one of the 3 constants below.
• TYPE_FORWARD_ONLY:-restricts the cursor movement downward only.
• TYPE_SCROLL_SENSITIVE:- permits cursor to move both directions.
• TYPE_SCROLL_INSENSITIVE:- permits cursor to move both directions.
And makes the ResultSet insensitive to changes made by another J2EE component to data in the table whose rows
are reflected in the ResultSet.

16 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

Updatable ResultSet
Rows contained in the ResultSet can be updatable similar to how rows in table can be updated.
This is made possible by passing the createStatement ( ) method of the Connection object
CONCUR_UPDATABLE. Alternatively, the CONCUR_READ_ONLY constant can be passed to the
createStatement ( ) method to prevent the ResultSet being updated.

There are 3 ways in which a ResultSet can be changed. These are


* updating values in a row
* deleting a row
* inserting a new row
All of these changes are accomplished by using methods of the Statement object.

Update ResultSet
Once the executeQuery( ) method of the statement object returns a ResultSet, the updateXXX() method is used to
change the value of a column in the current row of the ResultSet. XXX in updateXXX( ) replaced with the data
type of the column that is to be updated.
updateXXX( ) requires 2 arguments.
 First is either a number or name of the column,
 and the second parameter is the value that will replace.

A value in a column can be replaced with NULL value by using updateNull( ) method. It takes
one parameter that is the column number in the current row of the ResultSet. It doesn’t accept the
column name as a parameter.
The updateRow( ) method is called after updateXXX( ) methods are called. The updateRow( )
changes the values in the columns of current row of the ResultSet based on the values of updateXXX( ) methods.

Example: result.updateInt(1, 105);


result.updateString(2, "Anil");
result.updateRow();

Insert ResultSet
Inserting a row into the ResultSet is accomplished using same technique as is used in update the ResultSet. The
updateXXX( ) is used to specify the column and value that will be placed into the column of the ResultSet.
The insertRow( ) method is called after the updateXXX( ) methods, which causes a new row to
be inserted into the ResultSet having the values that reflect the parameters in the updateXXX( )
methods.

Example: result.updateInt(1, 115);


result.updateString(2, "Naveen");
result.insertRow();

17 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

Delete a row in ResultSet


The deleteRow( ) method is used to remove a row from a ResultSet. It is used to eliminate rows
in processing. The deleteRow( ) method is passed an integer that contains the number of the row
to be deleted.
A good practice is to use the absolute( ) method to move the cursor to the row in the ResultSet
that should be deleted. The deleteRow( ) method is then passed a zero integer indicating the
current row must be deleted.

Example: result.absolute(3);
result.deleteRow(0);

Use of ResultSet.getXXX() Methods to Retrieve JDBC Types

18 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

JDBC Statements
• Once a connection is obtained we can interact with the database.
• The java application submits its request using jdbc statements.
• The JDBC statement interface defines the methods and properties that enable you to send SQL commands and
receive data from your database.

There are 3 interfaces or types of statement:


• Statement
• PreparedStatement
• CallableStatement

Statement
• Statement object is used when we are using a static query. It is created using createStatement ( )
method in Connection class.
• Example: Statement st=null;
• St=con.createStatement( );
• It immediately executes the query without compilation.

PreparedStatement
Use PreparedStatement object when we are using query with different parameters. So it must be compiled before
execution.

PreparedStatement pst = null;


String SQL = "Update Student SET name = ? WHERE usn = ?";
pst = conn.prepareStatement(SQL);
All parameters in JDBC are represented by the ? symbol, which is known as the parameter marker. You must
supply values for every parameter before executing the SQL statement.

The setXXX( ) methods bind values to the parameters, where XXX represents the Java data type
of the value you wish to bind to the input parameter. If you forget to supply the values, you will

19 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

receive a SQLException. setXXX( ) method takes two arguments representing position of marker (?) and value to
replace respectively.
Each parameter marker is referred to by its ordinal position. The first marker represents position 1, the next
position 2, and so forth.
pst.setString(1, ”Babu”);
pst.setString(2,”s105”);
All of the Statement object's methods for interacting with the database (a) execute(), (b)
executeQuery(), and (c) executeUpdate() also work with the PreparedStatement object.

Methods used in Prepared Statements

Examples on prepared statements


Example of PreparedStatement interface that inserts the record. First of all create table as given below:

create table emp(id number(10),name varchar2(50));

import java.sql.*;
class InsertPrepared{
public static void main(String args[]){
try{

20 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

Class.forName("oracle.jdbc.driver.OracleDriver");

Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");

PreparedStatement stmt=con.prepareStatement("insert into Emp values(?,?)");


stmt.setInt(1,101);//1 specifies the first parameter in the query
stmt.setString(2,"Ratan");

int i=stmt.executeUpdate();
System.out.println(i+" records inserted");

con.close();

}catch(Exception e){ System.out.println(e);}

}
}
Example of PreparedStatement interface that updates the record

PreparedStatement stmt=con.prepareStatement("update emp set name=? where id=?"); stmt.setString(1,”sudarsha


n");//1 specifies the first parameter in the query i.e. name
stmt.setInt(2,101);
int i=stmt.executeUpdate();
System.out.println(i+" records updated");

Example of PreparedStatement interface that deletes the record


PreparedStatement stmt=con.prepareStatement("delete from emp where id=?");
stmt.setInt(1,101);
int i=stmt.executeUpdate();
System.out.println(i+" records deleted");

CallableStatement
As a Connection object creates the Statement and PreparedStatement objects, it also creates the
CallableStatement object which would be used to execute a call to a database stored procedure.
It is created using prepareCall ( ) method in Connection class.
CallableStatement cstmt = null;
String SQL = "{call getAllData}";
cstmt = conn.prepareCall (SQL);
Here getAllData is a stored procedure defined in database, which contains multiple SQL queries and gets
executed when stored procedure is called.

21 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

JDBC Transaction Processing


• Transaction represents a single unit of work.
• The sequence of actions (SQL statements) is treated as a single unit that is known as a transaction.
• Transaction Management is important for RDBMS-oriented applications to maintain data integrity and
consistency.
• While performing the transaction, we will use getXXX and setXXX methods to retrieve and set the data in
the ResultSet object. XXX represents the data types of the columns.

If your JDBC Connection is in auto-commit mode, which it is by default, then every SQL statement is committed
to the database upon its completion.
That may be fine for simple applications, but there are three reasons why you may want to turn off auto-commit
and manage your own transactions:
 To increase performance
 To maintain the integrity of business processes
 To use distributed transactions
Transactions enable you to control if, and when, changes are applied to the database. It treats a single SQL
statement or a group of SQL statements as one logical unit, and if any statement fails, the whole transaction
fails.
The ACID properties describes the transaction management well. ACID stands for Atomicity,
Consistency, isolation and durability.
Atomicity: If all queries are executed successfully, data will be committed, else won’t.
Consistency : ensures bringing the database from one consistent state to another consistent state.
Isolation: ensures that transaction is isolated from other transaction.
Durability: If the transaction is committed once, it will remain always committed, even in the event of errors,
power loss etc.

Advantage of Transaction Management

fast performance It makes the performance fast because database is hit at the time of commit.

22 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

There are three most important functions in Transaction Management.

Commit(): After the execution of the SQL statements, we want to make the changes permanent in the
Database. We should call the commit() method. Normally, what is commit means it will make the changes
permanently in the Database. We can’t undo/ revoke the changes. But we can change the data in the Database.

Rollback(): Rollback undoes the changes till the last commit or mentioned savepoint. Sometimes we may
want to undo the changes. For example, we have one nested query, one part has been executed successfully,
and the other has thrown some exception. At that time, we want to undo the changes done by the first part, we
should call Rollback() method to do that if an exception has occurred.

Savepoint(): Savepoint helps to create checkpoint in a transaction and it allows to perform a rollback to that
particular savepoint. Any savepoint that has been created for a transaction will be automatically destroyed and
become invalid once the transaction is committed or rolled back.

Methods Of Transaction Management


1. Void setAutoCommit(boolean status) : It is true by default means each transaction is committed by
default.
2. void commit() : commits the transaction.
3. void rollback() : cancels the transaction
4. setSavepoint() Method : Savepoint gives you additional control over the transaction. When you set a
savepoint in the transaction (a group of SQL statements), you can use the rollback() method to undo all the
changes till the savepoint or after the savepoint(). setSavepoint() method is used to create a new savepoint.

23 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

5. releaseSavepoint() Method : It is used to delete the created savepoint.


To enable manual- transaction support instead of the auto-commit mode that the JDBC driver uses by default,
use the Connection object's setAutoCommit() method. If you pass a Boolean false to setAutoCommit( ), you
turn off auto-commit. You can pass a boolean true to turn it back on again.
For example, if you have a Connection object named conn, code the following to turn off autocommit:
conn.setAutoCommit(false);

Commit & Rollback


• Once you are done with your changes and you want to commit the changes then call commit()
• method on connection object as follows:
conn.commit( );
• Otherwise, to roll back updates to the database made using the Connection named conn, use the
• following code:
conn.rollback( );

Simple example of transaction management in jdbc using Statement


import java.sql.*;
class FetchRecords{
public static void main(String args[])throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
con.setAutoCommit(false);

Statement stmt=con.createStatement();
stmt.executeUpdate("insert into user values(190,'abhi',40000)");
stmt.executeUpdate("insert into user values(191,'umesh',50000)");

con.commit();
con.close();
}}

24 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

Example:
try
{
conn.setAutoCommit(false);
Statement stmt = conn.createStatement();
String SQL = "INSERT INTO Employees " + "VALUES (106, 'Diya')";

stmt.executeUpdate(SQL);
// If there is no error.
conn.commit();
}
catch(SQLException se)

{
// If there is any error.
conn.rollback();
}

Example of transaction management in jdbc using PreparedStatement


import java.sql.*;
import java.io.*;
class TM{
public static void main(String args[]){
try{

Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
con.setAutoCommit(false);

PreparedStatement ps=con.prepareStatement("insert into user420 values(?,?,?)");

25 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));


while(true){
System.out.println("enter id");
String s1=br.readLine();
int id=Integer.parseInt(s1);

System.out.println("enter name");
String name=br.readLine();

System.out.println("enter salary");
String s3=br.readLine();
int salary=Integer.parseInt(s3);

ps.setInt(1,id);
ps.setString(2,name);
ps.setInt(3,salary);
ps.executeUpdate();

System.out.println("commit/rollback");
String answer=br.readLine();
if(answer.equals("commit")){
con.commit();
}
if(answer.equals("rollback")){
con.rollback();
}
System.out.println("Want to add more records y/n");

26 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

String ans=br.readLine();
if(ans.equals("n")){
break;
}

}
con.commit();
System.out.println("record successfully saved");

con.close();//before closing connection commit() is called


}catch(Exception e){System.out.println(e);}

}}

Using Savepoints
• When you set a savepoint you define a logical rollback point within a transaction. If an error occurs
past a savepoint, you can use the rollback method to undo either all the changes or only the changes
made after the savepoint.
The Connection object has two new methods that help you manage savepoints:
setSavepoint(String savepointName): defines a new savepoint. It also returns a Savepoint object.
releaseSavepoint(Savepoint savepointName): deletes a savepoint. Notice that it requires a Savepoint object
as a parameter. This object is usually a savepoint generated by the setSavepoint() method.

Example :
Try
{
conn.setAutoCommit(false);
Statement stmt = conn.createStatement();
//set a Savepoint
Savepoint savepoint1 = conn.setSavepoint("Savepoint1");

27 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

String SQL = "INSERT INTO Employees "+"VALUES (106, 'Diya')";


stmt.executeUpdate(SQL);
//Submit a malformed SQL statement that breaks
String SQL = "INSERT INTO Employees” + "VALUES (107, 'Sita')";
stmt.executeUpdate(SQL);
// If there is no error, commit the changes.
conn.commit();
}
catch(SQLException se)
{
// If there is any error.
conn.rollback(savepoint1);
}

Metadata
Data about data is called metadata. That means data about column names, data type names of database
software etc. It means information about your data that does not interest the end users at all, but which you
need to know in order to handle the data.
J2EE component can access metadata by using Metadata interface.
In JDBC there are 2 Metadata interfaces available.
 DatabaseMetaData
 ResultSetMetaData

DatabaseMetaData
• The DatabaseMetaData class relates to the Connection class.
• The DatabaseMetaData class provides methods that tell you about the database for a
given Connection object.
• A J2EE component retrieves the metadata about the database by calling the
getMetaData( )
• Method of Connection object. The getMetaData( ) method returns a DatabaseMetaData
object that contains the information about the database and its components.
DatabaseMetaData dm = connection.getMetaData();

28 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

• we can call methods on it to obtain the meta data about the database.

ResultSetMetaData
• It is used to gather more information about database table that is represented by JBDC ResultSet
object. It is used to get no of columns, column name, column data types, etc., information from
database table.
• J2EE component retrieves the metadata about the ResultSet by calling the getMetaData( ) method of
ResultSet object.
• ResultSet rs =st.executeQuery(“select * from emp”);
• ResultSetMetaData rm = res.getMetaData();

29 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

Example :
import java.sql.*;
class Dbmd{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");

Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
DatabaseMetaData dbmd=con.getMetaData();

System.out.println("Driver Name: "+dbmd.getDriverName());


System.out.println("Driver Version: "+dbmd.getDriverVersion());
System.out.println("UserName: "+dbmd.getUserName());
System.out.println("Database Product Name: "+dbmd.getDatabaseProductName());
System.out.println("Database Product Version: "+dbmd.getDatabaseProductVersion());

con.close();
}catch(Exception e){ System.out.println(e);}
}
}

Output :

30 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

JDBC Data Types


• The JDBC driver converts the Java data type to the appropriate JDBC type before sending it to the
database. It uses a default mapping for most data types. For example, a Java int is converted to an SQL
INTEGER. Default mappings were created to provide consistency between drivers.

• The following table summarizes the default JDBC data type that the Java data type is converted to
when you call the setXXX() method of the PreparedStatement or CallableStatement object or the
ResultSet.updateXXX() method.

JDBC Exceptions Exception handling allows you to handle exceptional conditions such as program-defined
errors in a controlled fashion. JDBC Exception handling is very similar to Java Exception handling but for
JDBC, the most common exception is SQLException.

31 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

There are 3 kinds of exceptions that are thrown by JDBC methods:

• SQLException

• SQLWarning

• DataTruncation Exception

SQLException SQLException commonly reflect a SQL syntax error in the query and thrown by many of
methods contained in the java.sql package. This exception is most commonly caused by connectivity issues
with the database. A SQLException can occur both in the driver and the database. When such an exception
occurs, an object of type SQLException will be passed to the catch clause. The passed SQLException object
has the following methods available for retrieving additional information about the exception:

32 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

SQLWarning
The SQLWarning throws warnings received by the connection from the DBMS. The getWarning( ) method of
Connection object retrieves the warning and getNextWarning( )method of the Connection object retrieves
subsequent warnings.

DataTruncation Exception
A DataTruncation exception is thrown whenever data is lost due to truncation of the data value.

33 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

Unit – 4 Servlets
The various Web application development technologies are
 HTML
 Common Gateway Interface (CGI)
 Java Servlet
 Java Server Pages (JSP)
 ASP.NET
 PHP
CGI :The Common Gateway Interface (CGI) is a standard for writing programs that can interact through a
Web server with a client running a Web browser.A CGI program can be written in any language,
including Java, that can be executed by your Web server.

Java Servlets : are server-side Java programs help in developing powerful, efficient, platform-independent,
and dynamic Web applications. initialization code is executed only once unlike CGI scripts.

JSP(Java Server Pages): Technology is a powerful successor of the Servlet technology.is built on top of
the Servlet API to rapidly develop server-side and platform independent dynamic Web pages using HTML,
XML, and Java code.

What are Servlets ?


 Servlet technology is used to create a web application which resides at server side and generates a dynamic
web page.
 Servlets are java programs that runs on server and capable of handling request and generating dynamic
response.
 Java Servlets are programs that runs on the Java-enabled web server or application server.
 Using Servlets, you can collect input from users through web page forms, and process the request, produce
the response, then send response back to the web server.
 Before Servlet, CGI (Common Gateway Interface) scripting language was common as a server-side
programming language. However, there were many disadvantages to this technology.

How Servlet works?


1. Client sends a request to server
2. Server starts a servlet
3. Servlet computes a result for server and does not quit.
4. Server returns response to client
5. Another client sends a request
6. Server calls the servlet again etc.

1 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

Servlets offer several advantages in comparison with the CGI


 Performance is significantly better.
 Servlets execute within the address space of a Web server. It is not necessary to create a separate process
to handle each client request.
 Servlets are platform-independent because they are written in Java.
 Java security manager on the server enforces a set of restrictions to protect the resources on a server
machine. So servlets are trusted.

 The full functionality of the Java class libraries is available to a servlet. It can communicate with
applets, databases, or other software via the sockets and RMI mechanisms that you have seen already.

What are the disadvatages/drawback of CGI?


• Each time a CGI script is called, a separate process is created.
 It was also expensive to open and close database connections for each client request.
 CGI programs were not platform independent.
 Once CGI program terminates, all data used by the process is lost and can not be used by the other CGI
programs.
 Only defines interface, no supporting infrastructure (security, sessions, persistence, etc.)

Servlets – Life Cycle


The javax.servlet.Servlet interface defines the three methods known as life-cycle method. These are:
init(), service(), destroy() – defined in javax.servlet.Servlet interface
A servlet life cycle can be defined as the entire process from its creation till the destruction. The following are
the paths followed by a servlet
1. Loads the servlet when it is first requested.
2. The servlet is initialized by calling the init () method.
3. The servlet calls service() method to process a client's request.
4. The servlet is terminated by calling the destroy() method.
5. Finally, servlet is garbage collected by the garbage collector of the JVM.

2 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

1. The init() method


The init method is called only once. When a servlet is first loaded, the init() method is invoked. This
allows the servlet to perform any setup processing such as opening files or establishing connections to their
servers. If a servlet is permanently installed in server, it loads when the server strts to run, otherwise, the
server activates a servlet when it receives the first client request.

The init method definition looks like this:


public void init() throws ServletException
{
// Initialization code...
}

2. The service() Method


The service() method is the main method to perform the actual task. The servlet container (i.e. web server) calls
the service() method to handle requests coming from the client( browsers) and to write the formatted response
back to the client with two parameters.
1.A ServletRequest object with data from the client.
2. A ServletResponse represents the servlets reply back to the client.

3 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

The doGet() and doPost() are most frequently used methods with in each service request.
Here is the signature of these two methods.

4 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

What is the Get method?


• Get method main job is asking the server for the resources. Get is one of the simplest HTTP
method. Get method has a size limitation of 1024 characters.

What is the Post method?


• Post method is Provide information. by using post we can send as well as request data to the
server.
doGet() is called in response to an HTTP GET request. This happens with some HTML FORMs (those with
METHOD=”GET” specified in the FORM tag).
doPost() is called in response to an HTTP POST request. This happens with some HTML FORMs (those with
METHOD="POST" specified in the FORM tag).

3. The destroy() method


The destroy() method is called only once at the end of the life cycle of a servlet. This method gives your servlet
a chance to close database connections, halt background threads, write cookie lists or hit counts to disk, and
perform other such cleanup activities.
After the destroy() method is called, the servlet object is marked for garbage collection. The destroy method
definition looks like this:

5 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

What you need to run servlets?


• JDK 1.2 or higher.

• A servlet-compatible webserver. (E.g. Tomcat )

• Create a directory structure

• Create a Servlet

• Compile the Servlet

• Create a deployment descriptor

• Start the server and deploy the project

• Access the servlet

6 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

Using Tomcat for Servlet Development


To create servlets, you will need access to a servlet development environment. One such used is Tomcat.
Tomcat is the Servlet Engine that handles servlet requests. Tomcat is open source (and therefore free). It
contains the class libraries, documentation and runtime support that you will need to create and test servlets.
You can download tomcat from jakarta.apache.org.
Installing the Tomcat server
The Java software Development Kit(JDK) should be installed on your computer before installing tomcat.
Then install Tomcat server. The default location for Tomcat5.5 is
C:\Program Files\Apache Software Foundation\Tomcat 5.5\
To Start Tomcat
Tomcat must be running before you try to execute a servlet.
Select start | Programs Menu | Apache Tomcat 5.5 | Monitor Tomcat, then a tomcat icon appears on the right
bottom tray of the task bar. Right click on the icon and choose start service.
Test Tomcat
You can test whether the tomcat is runing or not by requesting on a web browser
http://localhost:8080

7 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

Set two environment variables:


Tomcat uses an environmental variable JAVA_HOME to indicate the location of the JDK top-level directory.
You may need to set the environmental variable JAVA_HOME to the top-level directory in which the Java
Development Kit is installed( say C:\JDK1.5).
The directory C:\Program Files\Apache Software Foundation\Tomcat 5.5\common\lib contains servlet-api.jar.
This jar file contains the classes and interfaces that are needed to buils servlet. To make this file accessible,
update your CLASSPATH envirinment variable so that it includes
C:\Program Files\Apache Software Foundation\Tomcat 5.5\common\lib\servlet-api.jar
Placing the compiled servlet class file in the proper Tomcat directory:
Once you have compiled a servlet, you must enable the tomcat to find it. Copy the servlet class file into the
following directory:
C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\servlets-examples\WEB-INF\classes
Add Servlet Name & mapping to the web.xml :
Add the servlet’s name and mapping to the web.xml file located in the follwing directory.
C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\servlets-examples\WEB-INF
For example assuming the first example, called HelloWorld, you will add the following lines in the section that
defines the servlet.
<servlet>

8 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

<servlet-name>HelloWorld</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>
Next, add the following lines to the section that defines the servlet mappings
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/servlet/HelloWorld</url-pattern>
</servlet-mapping>
Follow the same general procedure for all the examples.

Steps involved in building and testing a servlet


1. Create and compile the servlet source code. Then copy the servlet’s class file to the proper
directory, and add the servlet’s name and mappings to the proper web.xml file
2. Start Tomcat
3. Start a Web browser and request the servlet.

9 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

Explanation: Here this file should be named as HelloWorld.java.


It is extending GenericServlet. So the related packages are imported.
→ Run javac HelloWorld.java from the command line.
→ Class file should be located in the web application’s classes folder:

service() is the method by which we manipulate the client’s request and responses. It has two arguments. First,
req is an object that is implementing the ServletRequest interface and secondly, resp is an object that is
implementing the ServletResponse interface. These are used to handle the request and responses. Other methods
that are usually called to handle data are doPost, doPut, doTrace, doHead, etc.
It is throwing two exceptions: IOException and ServletException. IOException usually arises when the servlet
is loaded to the web and ServletException can occur anytime. So it has to be handled.
resp.setContentType("text/html");
This statement sets the MIME header using the method setContentType() in the response.
PrintWriter out=resp.getWriter();
Here we are getting hold of a handle to write into the output stream. You get a handle by using the method
getWriter() which is implemented by the java.io.PrintWriter class.
We write HTML to the output, e.g.,

out.println ("<html>");

out.println ("<head><title> Test </title></head>");

write the greeting


out.println("Hello World ");
Compiling a Servlet
HelloWorld.java compiles to HelloWorld.class.
C:\<tomcat home>\webapps\servlets-examples\WEB-INF\classes
Adding Servlet Name & mapping to the web.xml
❑ Consider a Servlet residing in folder

webapps\servlets-examples\WEB-INF\classes\HelloWorld.class
❑ Assign a name to the servlet in web.xml

10 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI


<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>

11 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

What is web.xml

The web.xml file specifies various config. parameter such as:

• the name used to invoke the servlet

• description of the servlet

• the class name of the servlet class

Sample file entry

12 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

What is Servlet API


Two packages contain the classes and interfaces that are required to build servlets. These are:
• javax.servlet
• javax.servlet.http

They constitute the Servlet API. These packages are not part of the java core packages. Instead, they are
standard extensions provided by Tomcat.

Java Servlet Development Kit


• JSDK (Java Servlet Development/Developers Kit) is a package containing all the classes and interfaces
needed to develop servlets. JSDK also contains a web server and servlet engine to test your creations.
• Servlet API: is used to create and manage servlets. consists of various interfaces, classes, and methods.
classes ad methods are available in the following packages:
• javax.servlet
• javax.servlet.http

13 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

javax.servlet Package
The javax.servlet package contains a number of classes and interfaces that establish the framework in which
servlet operate. It contains the classes necessary for a standard, protocol-independent servlet. The following
table summarizes the core interfaces that are provided in this package.

The Servlet interface


All servlets must implement the Servlet interface. It declares the init(), service(), and destroy() methods that are
called by the server during the life cycle of a servlet. The methods defined by Servlet are shown below.

14 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

The ServletConfig interface


The ServletConfig interface allows a servlet to obtain configuration data when it is loaded. The methods
declared by this interface are summarized below.

15 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

The ServletContext Interface


The ServletContext interface enables servlets to obtain information about their environment. Several of its
methods are summarized below.

The ServletRequest Interface


The ServletRequest interface enables a servlet to get information about a client request. Several of its methods
are summarized below.

16 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

The ServletResponse Interface


- The ServletResponse interface enables a servlet to formulate a response for a client. Several of its methods are
summarized below.

Classes
The following table summarizes the core classes that are provided in javax.servlet package.

17 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

The servlet example can be created by three ways:

 By implementing Servlet interface,


 By inheriting GenericServlet class, (or)
 By inheriting HttpServlet class
The mostly used approach is by extending HttpServlet because it provides http request specific method such as
doGet(), doPost().

Using The GenericServlet class


The GenericServlet class provides the framework for developing basic servlets. If you are creating a protocol-
independent servlet, you probably want to subclass this class rather than implement the Servlet interface
directly. Note that the service() method is declared as abstract; this is the only method you have to override to
implement a generic servlet. GenericServlet includes basic implementations of the init() and destroy() methods.

import java.io.*;

import javax.servlet.*;

public class First extends GenericServlet

public void service(ServletRequest req,ServletResponse res)

throws IOException,ServletException{

res.setContentType("text/html");

PrintWriter out=res.getWriter();

out.print("<html><body>");

out.print("<b>hello generic servlet</b>");

out.print("</body></html>");

} }

18 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

By inheriting HttpServlet class writing the servlets program

Reading servlet parameters


The ServletRequest interface includes methods that allow you to read the names and values of parameters that are
included in a client request.

Servlets parse the form(client) data automatically using the following methods depending on the situation −

getParameter() − You call request.getParameter() method to get the value of a form parameter.

getParameterValues() − Call this method if the parameter appears more than once and returns multiple values,
for example checkbox.

If a client send the data to the servlet, that data will be available in the object of
HttpServletRequest interface. In case of getParameter() method we have to pass input
parameter name and it will give the value.

request.getParameter("name")

If you are not aware of input parameter name? or if you have more input values its really
tedious to use getParameter() method so we use getParameterNames(). This method
returns an Enumeration that contains the parameter names in an unspecified order. Once
we have an Enumeration, we can loop down the Enumeration in standard way by, using
hasMoreElements() method to determine when to stop and using nextElement() method to
get each parameter name.

Enumeration en=request.getParameterNames();
while(en.hasMoreElements())
{
String param_name = (String) en.nextElement();
String value=request.getParameter(param_name);
.......
}

19 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

20 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

Web.xml

<web-app>
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>LoginDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>

javax.servlet.http Package
• Contains number of classes and interfaces that are commonly used by servlet developers
• Its functionality makes it easy to build servlets that work with HTTP requests and response . i.e. The
javax.servlet.http package supports the development of servlets that use the HTTP protocol

The following table summarizes the core inerfaces that are provided in this package.

The HttpServletRequest Interface


The HttpServletRequest interface enables a servlet to obtain information about a client request. Several of its
methods are shown below.

21 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

The HttpServletResponse Interface


The HttpServletResponse interface enables a servlet to formulate an HTTP response to a client. Several of its
methods are shown below.

The HttpSession Interface


Provides a way to identify a user across more than one page request or visit to a Web site and to store
information about that user.
• The servlet container uses this interface to create a session between an HTTP client and an HTTP server.
• The session persists for a specified time period, across more than one connection or page request from the
user.
• A session usually corresponds to one user, who may visit a site many times. The server can maintain a session
in many ways such as using cookies or rewriting URLs.

22 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

Classes
The following table summarizes the core classes that are provided in this package.

23 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

Handling HTTP Requests and Responses


• HttpServlet class provides various methods that handle the various types of HTTP requests
• A servlet developer typically overrides one of these methods
• These methods are doGet(), doPost() etc

Handling HTTP GET requests


Here we will develop a servlet that handles an HTTP GET request. The servlet is invoked when
a form on a web page is submitted. The example contains two files.
• ColorGet.html
• ColorGetservlet.java

ColorGet.html: It defines a form that contains a select element and a submit button. Notice that
the action attribute of the form tag specifies a URL. The URL identifies a servlet to process the
HTTP request.

24 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

<HTML>

<HEAD>

<TITLE>Handling HTTP GET request</TITLE>

</HEAD>

<BODY BGCOLOR="#FDF5E6">

<FORM ACTION="http://localhost:8080/servlets-examples/servlet/ColorGetServlet"

METHOD=“GET">

<B>Color:

<select name=“color” >

<option value=“Red” >Red </option>

<option value=“Green” >Green </option>

<option value=“Blue” >Blue </option>

</select><BR>

<INPUT TYPE="SUBMIT" VALUE="Submit">

</FORM>

</BODY>

</HTML>

25 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

26 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

Handling HTTP POST requests


Same as that of handling HTTP GET request, Note the following changes:
• Replace method=”get” in HTML form to method=”post”
• In servlet, override doPost(), instead of doGet()

27 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

Reading Initialization Parameters in Servlet


Both ServletContext and ServletConfig are basically the configuration objects which are used by the servlet
container to initialize the various parameter of a web application. But, the difference lies in the fact that
information shared by ServletConfig is for a specific servlet, while information shared by ServletContext is
available for all servlets in the web application.

How to Retrieve Data from ServletConfig Interface Object


In order to retrieve the data of the ServletConfig we have two methods, which are present in ServletConfig
interface.
public String getInitParameter(“param name”); Returns the parameter value for the specified parameter
name.
public Enumeration getInitParameterNames();Returns an enumeration of all the initialization parameter
names.
public String getServletName(): Returns the name of the servlet

Example
Files Required

28 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

• index.html
• OnServletConfig.java
• web.xml
index.html
<font face="verdana" size="2px">

<form action="onSCG" method="post">

Example on ServletConfig<br>

<input type="submit" value=“Click Here">

</form>

</font>

29 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

Web.xml

30 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

Generic VS HTTP Servlet

31 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

Cookie class
• Cookies are short pieces of data sent by web servers to the client browser. The cookies are
saved to the hard disk of the client in the form of small text file. Cookies help the web
servers to identify web users and tracking them in the process.

• A cookie consists of one or more name-value pairs containing bits of information such as
user preferences, shopping cart contents, the identifier for a server-based session, or other
data used by websites.

How cookie works

32 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

• By default, each request is considered as a new request. In cookies technique, we add


cookie with response from the servlet. So cookie is stored in the cache of the browser.
After that if request is sent by the user, cookie is added with request by default. Thus, we
recognize the user as the old user.
For example, when you sign in to a website, it's like the process of entering an amusement park.
First you pay for a ticket, then when you enter the park, the staff checks your ticket and gives you
a wristband.

• This is like how you sign in – the server checks your username and password, creates and
stores a session, generates a unique session id, and sends back a cookie with the session id.

• While you're in the amusement park, you can go on any ride by showing your wristband.

• Similarly, when you make requests to the website you're signed in to, your browser sends
your cookie with your session id back to the server. The server checks for your session
using your session id, then returns data for your request.

• Finally, once you leave the amusement park, your wristband no longer works – you can't
use it to get back into the park or go on more rides.

• This is like signing out of a website. Your browser sends your sign out request to the server
with your cookie, the server removes your session, and lets your browser know to remove
your session id cookie.

• If you want to get back into the amusement park, you'd have to buy another ticket and get
another wristband. In other words, if you want to continue using the website, you'd have to
sign back in.

Types of Cookie
There are 2 types of cookies in servlets.

• Non-persistent cookie
• Persistent cookie

Non-persistent cookie

33 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

It is valid for single session only. It is removed each time when user closes the browser.

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.

Disadvantage of Cookies

• It will not work if cookie is disabled from the browser.

• Only textual information can be set in Cookie object.

In servlet, cookies are object of the class javax.servlet.http.Cookie. this class is used to create
cookie, a small amount of information sent by the servlet to a web browser, saved by web browser
and later sent back to the server. The value of cookie can uniquely identify a client, so cookies are
commonly used for session tracking.

A cookie is composed of two pieces. These are cookie name and cookie value. The cookie name
is used to identify a particular cookie from among other cookies stored at client. The cookie value
is data associated with the cookie.

Cookies van be constructed using the following code.

Cookie(String CookieName, String CookieValue)

The first argument is the String object that contains the name of the cookie. The other argument
is a String object that contains the value of the cookie

E.g

Cookie cookie = new Cookie("ID", "123");

34 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

In this example, a cookie called ‘ID’ is being created and assigned the value 123.

A servlet can send a cookie to the client by passing a Cookie object to the addCookie() method
of HttpServletResponse.

void addCookie(Cookie cookie)

A servlet can read a cookie by calling the getCookies() method of the HttpServletRequest
object. It returns an array of cookie objects.

How to delete Cookie?


It is mainly used to logout or signout the user.

Cookie ck=new Cookie("user","");//deleting value of cookie

ck.setMaxAge(0);//changing the maximum age to 0 seconds

response.addCookie(ck);//adding cookie in the response

Cookie objects have the following methods

Methods

35 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

Let us develop a servlet that illustrates how to use cookies.


Example: Program to create and display cookie
The program contains three files as summarized below:
AddCookie.html : Allows a user to specify a name & value for the cookie
AddCookieServlet.java : Processes the submission of AddCookie.html
GetCookieServlet.java : Displays cookie name & values.

36 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

GetCookieServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class GetCookieServlet extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException

37 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

{
// Get cookies from header of HTTP request
Cookie[] cookies=req.getCookies();
//Display these cookies
resp.setContentType("text/html");
PrintWriter pw=resp.getWriter();
pw.println("<b>");
for (int i=0;i<cookies.length;i++)
{
String name=cookies[i].getName();
String value=cookies[i].getValue();
pw.println("Name="+name + "Value= " + value +"<br><br>");
}
pw.close();
}
}

38 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

Session Tracking
Cookies are stored on client side where as sessions are server variables. Sessions grew up from cookies as a way
of storing data on the server side, because the inherent problem of storing anything sensitive on clients'
machines is that they are able to tamper with it if they wish.

Why use Session Tracking?

• To recognize the user It is used to recognize the particular user.

• The time interval in which two systems(i.e. the client and the server) communicate with each other can
be termed as a session.

39 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

• A session indicates a period of time that a single user visits a website. A session starts when the user
requests for the first page. And during a session, the user can view as many pages as he wants.

• The session ends if the user hasn’t requested any pages for a given amount of time (timeout). The
session timeout varies, depend on server configuration – typically from 15 to 30 minutes.

HTTP is a stateless protocol, each request is independent of the previous one. However in some applications, it
is necessary to save state information so that information can be collected from several interactions between a
browser and a server. Sessions provide such a mechanism.

Session tracking in servlets can be implemented by a number of methods, cookies being


one of them.

They have disadvantages:

 Only textual information can be kept by them.


 If cookies are disabled by a user, the web application is unable to make use of them.
 Not more than 4kb of data can be contained by a single cookie.

Session Tracking Techniques


There are four techniques used in Session tracking:
• Cookies
• HttpSession
• Hidden Form Field
• URL Rewriting
HttpSession
A java servlet is capable of tracking sessions by using HttpSession interface. An object that implements this
interface can hold information for one user session between requests. A session can be created via getSession()
method of HttpServletRequest. An HttpSession object is returned.

Because the HTTP protocol is stateless so we need to maintain state using session tracking techniques., the
server can track session via cookies, URL rewriting or hidden form fields – to identify a single user across
different requests. Session tracking using cookies is the primary mechanism.

40 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

In case the user’s web browser doesn’t support cookies, then URL rewriting or hidden form fields can be used.
Each time user requests to the server, server treats the request as the new request. So we need to maintain the
state of an user to recognize to particular user.

Hidden Form Field


• The hidden form field are sent back to the server when the form is submitted. In hidden form fields the
html entry will be like this : <input type ="hidden" name = "name" value="">.

• This means that when you submit the form, the specified name and value will be get included in get or
post method. In this session ID information would be embedded within the form as a hidden field and
submitted with the Http POST command.

URLRewriting
• URLRewriting can be used in place where we don't want to use cookies. It is used to maintain the
session.

• In session tracking firstly a session object is created when the first request goes to the server. Then
server creates a token which will be used to maintain the session. The token is transmitted to the client
by the response object and gets stored on the client machine. By default the server creates a cookie and
the cookie get stored on the client machine.

HttpSession interface
In such case, container creates a session id for each user. The container uses this id to identify the particular
user.

41 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

An object of HttpSession can be used to perform two tasks:

 Bind objects
 view and manipulate information about a session, such as the session identifier, creation
time, and last accessed time.

The HttpServletRequest interface provides two methods to get the object of HttpSession:
• public HttpSession getSession():Returns the current session associated with this request,
or if the request does not have a session, creates one.
• public HttpSession getSession(boolean create):Returns the current HttpSession
associated with this request or, if there is no current session and create is true, returns a
new session.

Commonly used methods of HttpSession interface


• public String getId():Returns a string containing the unique identifier value.
• public long getCreationTime():Returns the time when this session was created,
measured in milliseconds since midnight January 1, 1970 GMT.
• public long getLastAccessedTime():Returns the last time the client sent a request
associated with this session.
• public void invalidate():Invalidates this session then unbinds any objects bound to it.

Getting or Creating a Session

42 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

To obtain the HttpSession object representing the user’s session, invoke


the getSession() method of the HttpServletRequest interface in doGet() or doPost() method
of a Java Servlet.
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();

// work with the session...


}
This method takes a boolean argument. true means a new session shall be started if none exist, while false only
returns an existing session. The HttpSession object is unique for one user session.
You can add data to an HttpSession object with the setAttribute() method. The method requires two arguments.
The first argument is the String object that contains the name of the attribute. The other argument is an object
binded with value.

To get a session without creating a new one if not exist, you can use
invoke getSession(false) on the HttpServletRequest
HttpSession session = request.getSession(false);
if (session != null) {
// a session exists

} else {
// no session
}
Binding Data to a Session
• To store a value in a session, use the method setAttribute(key, value) of
the HttpSession object. For example, the following statement stores username of the
user:

43 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

• session.setAttribute("username", "Daniel Tran");


• Here, the key is username and value is Daniel Tran. Data stored in a session is managed
by the server and will be deleted when the session ends.

Serialization and Deserialization in Java


Serialization is a mechanism of converting the state of an object into a byte stream.
Deserialization is the reverse process where the byte stream is used to recreate the actual Java
object in memory. This mechanism is used to persist the object.

What is serialVersionUID
• Sender and receiver are not the same people that is the persons may be different,
machine or system may be different and location must be different then
SerialVersionUID comes into the picture.
• In serialization, both sender and receiver should have .class file at the time of beginning
only.
The following Java Servlet prints the session ID, creation time and last accessed time of the
current session:

44 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

getAttribute() and setAttribute()


The servlet setAttribute and getAttribute methods are used to pass information from one servlet to another (or to
JSP). It is just like passing object from one class to another so that we can reuse the same object again and again.
These two method are particularly useful when you want forward your request to another Servlet/JSP rather than
simply returning the response.

Forwarding the request to another resource is done by RequestDispatcher class.

Attribute specific methods of ServletRequest, HttpSession and


ServletContext interface
There are following 4 attribute specific methods. They are as follows:
public void setAttribute(String name,Object object):sets the given object in the application scope.
public Object getAttribute(String name):Returns the attribute for the specified name.
public Enumeration getInitParameterNames():Returns the names of the context's initialization parameters as
an Enumeration of String objects.
public void removeAttribute(String name):Removes the attribute with the given name from the servlet
context.

Example 1:

45 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

Program to demonstrate getAttribute() and setAttribute()


Example: Program to create a session and display session information such as current date
and time and the date and time the page was last accessed.
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DateServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException
{
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
//Get the HTTP Session object
HttpSession hs = req.getSession(true);
// Display the date/time of last access
Date date = (Date)hs.getAttribute(“date”);

if(date != null)
{
out.println(“Last access: " + date + "<br>");
}
// Display current date/time:
date = new Date();

46 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

hs.setAttribute(“date”,date);
out.println(“Current date :" + date);
}
}
Output: When the web page is accessed first time. A session is created shown below.

Below output shown when you run it second time.

47 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

Example 2 :Program to demonstrate getAttribute() and setAttribute()


index2.html
<html>
<body>
<form action="servlet1">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
</body>
</html>

Servlet1
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response){

48 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
HttpSession session=request.getSession();
session.setAttribute("uname",n);
out.print("<a href='servlet2'>visit</a>");
out.close();
}catch(Exception e){System.out.println(e);}
}
}

Servlet2
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response){


try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();

HttpSession session=request.getSession(false);
String n=(String)session.getAttribute("uname");
out.print("Hello "+n);
out.close();

49 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

}catch(Exception e){System.out.println(e);}
}

}
web.xml file for this program:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<servlet>
<servlet-name>servlet1</servlet-name>
<servlet-class> FirstServlet </servlet-class>
</servlet>
<servlet-mapping>
<servlet-name> servlet1</servlet-name>
<url-pattern>/ FirstServlet </url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>servlet2</servlet-name>
<servlet-class> SecondServlet </servlet-class>
</servlet>
<servlet-mapping>
<servlet-name> servlet2</servlet-name>
<url-pattern>/ SecondServlet </url-pattern>
</servlet-mapping>
</web-app>

50 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

To Determine whether the Session is New or Old


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class CheckingTheSession extends HttpServlet{
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("Checking whether the session is new or old<br>");
HttpSession session = request.getSession();
if(session.isNew()){
pw.println("You have created a new session");
}
else{

51 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

pw.println("Session already exists");


}
}
}
web.xml file for this program:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd"> -->
<web-app>
<servlet>
<servlet-name>Hello</servlet-name>
<servlet-class>CheckingTheSession</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Hello</servlet-name>
<url-pattern>/CheckingTheSession</url-pattern>
</servlet-mapping>
</web-app>

52 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

• Create a HTML form with three input fields firstname, lastname and email.
Pass these values to a servlet. In the servlet verify all input fields are not
null and display them back to client.

53 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

54 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

Advantages of Http Sessions in Servlet


• Any kind of object can be stored into a session, be it a text, database, dataset etc.
• Usage of sessions is not dependent on the client’s browser.
• Sessions are secure and transparent
Disadvantages of Http session
• Performance overhead due to session object being stored on server
• Overhead due to serialization and de-serialization of data
Program to demonstrate

55 D.M.S Mandal’s College of Computer Applications, Belgaum


JSP
• JSP: Java Server Pages (JSP) is a technology which is used to develop
web pages by inserting Java code into the HTML pages by making
special JSP tags. The JSP tags which allow java code to be included
into it are <% ----java code----%>.
• It can consist of either HTML or XML (combination of both is also
possible) with JSP actions and commands.
• It can be used as HTML page, which can be used in forms and
registration pages with the dynamic content into it.
• In this, Java code can be inserted in HTML/ XML pages or both.
• JSP is first converted into servlet by JSP container before processing
the client’s request.
• HTML tags and JSP tags are present in Java Server Pages.
Declaration Tag :-It is used to declare variables.
Syntax:-
<%! Dec var %>
Example:-
<%! int var=10; %>
Java Scriplets :- It allows us to add any number of JAVA code, variables
and expressions.
Syntax:-
<% java code %>
JSP Expression :- It evaluates and convert the expression to a string.
Syntax:-
<%= expression %>
Example:-
<% num1 = num1+num2 %>
demo.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-
1">
<title>Hello World - JSP tutorial</title>
</head>
<body>
<%= "Hello World!" %>
</body>
</html>
Example of JSP where we are using the scriptlet tag to put Java code in the
JSP page.

<html>
<body>
<% out.print(2*5); %>
</body>
</html>

It will print 10 on the browser.


How to run a simple JSP Page?

• Start the server


• Put the JSP file in a folder and deploy on the server
• Visit the browser by the URL
http://localhost:portno/contextRoot/jspfile,
• for example, http://localhost:8888/myapplication/index.jsp
Difference between jsp and servlets
Servlets JSP
Servlets are java programs which are used for creating JSP is a webpage scripting language used to create the
dynamic content dynamic web content

Servlet is a java based code Jsp is a html-java based code

It should be use when there is more data processing Jsp is used when there is no involvement of much data
involved processing
Servlets run faster than jsp Jsp runs slower than servlet as it takes time to compile the
program and convert into servlets.

It is hard to write code in servlet It is easier to code in jsp compared to servlets

It can accept all protocol requests, including Http It can only accept Http requests

Modification is servlets file is a time consuming due to Jsp modification is fast as you just need to refresh it.
reloading, recompiling, restarting the server.
You can override the service() method In jsp, you cant override the service() method
Advantages of JSP over Html
• User need not write HTML and java code
Separately.
• JSP can be used for both front end and for
Writing business logic or middle tier.
• Jsp is very easy to write when compared
To servlets
Running servlet program
• Write the servlet source code. You need to import the javax.servlet package
and the javax.servlet.http package in your source file.
• Compile your source code.
• Create a deployment descriptor.
• Run Tomcat.
• Call your servlet from a web browser.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

public class TestingServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException


{

PrintWriter out = response.getWriter();


out.println("<HTML>");
out.println("<HEAD>");
out.println("<TITLE>Servlet Testing</TITLE>");
out.println("</HEAD>");
out.println("<BODY>");
out.println("Welcome to the Servlet Programming");
out.println("</BODY>");
out.println("</HTML>");
}
}
compile
• D:\webapps\chaya\WEB-INF\classes>javac TestingServlet.java
Create the Deployment Descriptor (set in web.xml)
<web-app
<servlet>
<servlet-name>TestingServlet</servlet-name>
<servlet-class>TestingServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TestingServlet</servlet-name>
<url-pattern>/TestingServlet</url-pattern>
</servlet-mapping>

</web-app>
• Run Tomcat
• Call Your Servlet from a Web Browser
http://localhost:8080/chaya/TestingServlet

Or

http://localhost:8080/chaya/servlet/TestingServlet
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class JavaTester extends HttpServlet {
private String message;
public void init() throws ServletException {
// Do required initialization
message = "Hello World";
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println(message);
}
}
Example
• Program to add two numbers
• Create html/jsp file
• Run it with browser (to check interface)
• Create java file
• Compile it
• Write servlet code in web.xml and save it
• Run the tomcat server
• compile java servlet program
• Go to browser run html/jsp file on browser with localhost
Create index.html or index.jsp
<html>
<body>

<form action="http://localhost:8080/chaya/Add" method="get">


<b> Enter first number : <input type="text" name="t1">
<b> Enter second number : <input type="text" name="t2">

<br>
<input type=submit value="Add">

</form>
</body>
</html>

Save it in folder : D:\webapps\chaya


Create Add.java (servlet file)
• import java.io.*;
• import javax.servlet.*;
• import javax.servlet.http.*;
• //import javax.servlet.annotation.WebServlet;

• //@WebServlet(urlPatterns = {"/Add"})
• public class Add extends HttpServlet
• {
• public void service(HttpServletRequest request,HttpServletResponse response)throws
• ServletException,IOException
• {
• response.setContentType("text/html");
• int i = Integer.parseInt(request.getParameter("t1"));
• int j = Integer.parseInt(request.getParameter("t2"));

• int k= i+j;
• PrintWriter out = response.getWriter();
• out.println(k);
• }
• }
Save it in folder : D:\webapps\chaya\WEB-INF\classes
Write servlet code in web.xml (D:\webapps\chaya\WEB-INF)
• <servlet>
• <servlet-name>Add</servlet-name>
• <servlet-class>Add</servlet-class>
• </servlet>
• <servlet-mapping>
• <servlet-name>Add</servlet-name>
• <url-pattern>/Add</url-pattern>
• </servlet-mapping>
Create user login servlet program
• Create login.html or login.jsp
<html>
<body>
<form method=“get” action=“http://localhost:8080/test/login”>
Username : <input type=“text” name=“u”> <br/>
Password : <input type=“password” name=“p”> <br/>

<input type=“submit” value=“login”>


</form>
</body>
</html>
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class verifyservlet extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String user = req.getParameter("U");
String password = req.getParameter("P");

if(user.equals("admin") && password.equals("admin"))


out.println("<h2> successful login </h2>");
else
out.println("<h2> eror </h2>");

}
}
Web.xml
• <servlet>
• <servlet-name>Demo</servlet-name>
• <servlet-class>verifyServlet</servlet-class>
• </servlet>
• <servlet-mapping>
• <servlet-name>Demo</servlet-name>
• <url-pattern>/login/verify</url-pattern>
• </servlet-mapping>

Run login.html in browser through localhost


In command prompt compile verifyservlet.java
Request Implicit Object Example
• In the below example we are receiving the input from user in
index.html page and displaying the same information in userinfo.jsp
page using request implicit object.
index.html
<html>
<head><title>Enter UserName and Password</title>
</head>
<body>
<form action="userinfo.jsp">
Enter User Name: <input type="text" name="uname" /><br><br>
Enter Password: <input type="text" name="pass" /><br><br>
<input type="submit" value="Submit Details"/>
</form></body>
</html>
• userinfo.jsp
• <%@ page import = " java.util.* " %>
• <html>
• <body>
• <%
• String username=request.getParameter("uname");
• String password=request.getParameter("pass");
• out.print("Name: "+username+" Password: "+password);
• %>
• </body>
• </html>
A JSP page consists of the following components:
• JSP comments
• JSP directives
• JSP declarations
• JSP scriptlets
• JSP expressions
• JSP actions
• JSP implicit objects
JSP comments:are used to explain the JSP code written in a JSP page.are not
included in the HTTP response.can be added in a JSP page by using any of the
following code snippets:
• <%-- comments --%>
• <% /** this is a comment ... **/ %>
• <!-- comments ... -->
JSP declarations:provide a mechanism to define variables and methods in
a JSP page. are placed within the <%! and %> symbols and end with
asemicolon.
<%!
int i=5;
int add()
{
i=i+5;
return i;
}
%>
JSP expressions are: used to directly insert values into the response
output.evaluated when a user makes an HTTP request.added in a JSP
page using the following code snippet:
• <%= expression%>
• The following code snippet uses JSP expressions toevaluate the value
of an expression:
• <h1>The product of 5 and 2 is: <%= (2 * 5) %></h1>
JSP scriptlets:consist of Java code snippets that are enclosed within the <%
and %> symbols.
are executed at the request time.
<% int i=10;
if(i>0)
{
out.println("i is a positive number");
}
else
{
out.println("i is a negative number");
}
%>
JSP actions: are the tags that are used to perform tasks, such as
inserting files and forwarding a user to another page. are added in a JSP
page using the following code snippet:
<jsp:actionname attribute="">
JSP directives: provide global information about a particular
JSP page.are of the following types:
• page directive
• taglib directive
• include directive
Jsp programs
To find factorial of a given number
<html>
<body>
<%! int n=5,fact=1; %>
<%for(int i=1;i<=n;i++)
{
fact=fact*i;
}
%>
<h1>Factorial of number = <%=fact %></h1>
</body>
</html>
• input.html

• <html>
• <body>
• <form action="Factorial.jsp">
• Enter a value for n: <input type="text" name="val">
• <input type="submit" value="Submit">
• </form>
• </body>
• </html>
<html>
<body>
<%!
long n, result;
String str;

long fact(long n) {
if(n==0)
return 1;
else
return n*fact(n-1);
}
%>
<%
str = request.getParameter("val");
n = Long.parseLong(str);
result = fact(n);
%>
<b>Factorial value: </b> <%= result %>
</body>
</html>
<html>
<head><title>First JSP</title></head>
<body>
<%
double num = Math.random();
if (num > 0.95) {
%>
<h2>You'll have a luck day!</h2><p>(<%= num %>)</p>
<%
} else {
%>
<h2>Well, life goes on ... </h2><p>(<%= num %>)</p>
<%
}
%>
<a href="<%= request.getRequestURI() %>"><h3>Try Again</h3></a>
</body>
</html>
The method request.getRequestURI() is used to retrieve the URL of the current page. This is used in the
anchor tag <a> for refreshing the page to obtain another random number.
BCA V SEM Advanced Java C.A. SATERI

Unit – 5 Java Networking


• The term network programming or networking associates with writing programs that can be executed
over various computer devices, in which all the devices are connected to each other to share resources
using a network.
• With networks, a single program can regain information stored in millions of computers positioned
anywhere in the world. Java is the leading programming language composed from scratch with
networking in mind. Java Networking is a notion of combining two or more computing devices
together to share resources.

Java Networking Terminology :


In Java Networking, many terminologies are used frequently. These widely used Java Networking
Terminologies are given as follows:
1. IP Address – An IP address is a unique address that distinguishes a device on the internet or a local
network. IP stands for “Internet Protocol.” It comprises a set of rules governing the format of data sent via the
internet or local network. IP Address is referred to as a logical address that can be modified. The range of IP
address varies from 0 to 255.Range of the IP Address – 0.0.0.0 to 255.255.255.255
• For Example – 192.168.0.1
2. Port Number –A port number is a method to recognize a particular process connecting internet or other
network information when it reaches a server. The port number is used to identify different applications
uniquely. The port number behaves as a communication endpoint among applications. The port number is
correlated with the IP address for transmission and communication among two applications. There are 65,535
port numbers.

3. Protocol – A network protocol is an organized set of commands that define how data is transmitted between
different devices in the same network. Network protocols are the reason through which a user can easily
communicate with people all over the world and thus play a critical role in modern digital communications.
For Example – TCP, FTP, POP, etc.

1 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

4. MAC Address – MAC address stands for Media Access Control address. MAC address is a unique number
that is used to track a device in a network. It is a identifier that is allocated to a NIC (Network Interface
Controller/ Card). It contains a 48 bit or 64-bit address, which is combined with the network

The java.net package also provides support for the two well-known network protocols.
Transmission Control Protocol (TCP) – TCP or Transmission Control Protocol allows secure
communication between different applications.
• TCP is a connection-oriented protocol which means that once a connection is established, data can be
transmitted in two directions.
• This protocol is typically used over the Internet Protocol. Therefore, TCP is also referred to as TCP/IP.
• TCP has built-in methods to examine for errors and ensure the delivery of data in the order it was sent,
making it a complete protocol for transporting information like still images, data files, and web pages.
User Datagram Protocol (UDP) – UDP or User Datagram Protocol is a connection-less protocol that allows
data packets to be transmitted between different applications.
• UDP is a simpler Internet protocol in which error-checking and recovery services are not required.
• In UDP, there is no overhead for opening a connection, maintaining a connection, or terminating a
connection.
• In UDP, the data is continuously sent to the recipient, whether they receive it or not.

2 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

TCP/IP Sockets

Socket – A socket is one endpoint of a two-way communication connection between the two applications
running on the network.
A socket is tied to a port number so that the TCP layer can recognize the application to which the data is
intended to be sent.

3 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

4 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

TCP/IP sockets are used to implement reliable, bidirectional, persistent, point-to-point, stream-based
connections between hosts on the Internet. A socket can be used to connect Java’s I/O system to other
programs that may reside either on the local machine or on any other machine on the Internet.
There are two kinds of TCP sockets in Java. One is for servers, and the other is for clients. The
ServerSocket class is designed to be a “listener,” which waits for clients to connect before doing
anything. Thus, ServerSocket is for servers. The Socket class is for clients. It is designed to connect to
server sockets and initiate protocol exchanges. The creation of a Socket object implicitly establishes a
connection between the client and server. There are no methods or constructors that explicitly expose the
details of establishing that connection. Here are two constructors used to create client sockets:

Socket defines several instance methods. For example, a Socket can be examined at any

5 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

time for the address and port information associated with it, by use of the following methods:

You can gain access to the input and output streams associated with a Socket by use of the
getInputStream( ) and getOuptutStream( ) methods, as shown here. Each can throw an
IOException if the socket has been invalidated by a loss of connection.

Several other methods are available, including connect( ), which allows you to specify a new
connection; isConnected( ), which returns true if the socket is connected to a server; isBound( ), which
returns true if the socket is bound to an address; and isClosed( ), which returns true if the socket is closed.

Creating TCP Clients


To create a TCP client, do the following:
1. Create a Socket object attached to a remote host, port.
Socket client = new Socket(host, port);
When the constructor returns, you have a connection.
2. Get input and output streams associated with the socket.
out = new PrintWriter(client.getOutputStream());
reader = new InputStreamReader(client.getInputStream());
in = new BufferedReader(reader);
Now you can read and write to the socket, thus, communicating with the server.
out.println("Watson!" + "Come here...I need you!");
String data = in.readLine();

6 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

The following program provides a simple Socket example. It opens a connection to a “whois” port (port 43)
on the InterNIC server, sends the command-line argument down the socket, and then prints the data that is
returned. InterNIC will try to look up the argument as a registered Internet domain name, and then send back
the IP address and contact information for that site.

TCP/IP Server Sockets


The ServerSocket class is used to create servers that listen for either local or remote client programs to
connect to them on published ports. ServerSockets are quite different from normal Sockets. When you create
a ServerSocket, it will register itself with the system as having an interest in client connections. The
constructors for ServerSocket reflect the port number that you want to accept connections on and, optionally,
how long you want the queue for said port to be. The queue length tells the system how many client
connections it can leave pending before it should simply refuse connections. The default is 50. The
constructors might throw an IOException under adverse conditions. Here are three of its constructors:

ServerSocket has a method called accept( ), which is a blocking call that will wait for a client to initiate
communications and then return with a normal Socket that is then used for
communication with the client.

Creating TCP Servers

To create a TCP server, do the following:


1. Create a ServerSocket attached to a port number.
ServerSocket server = new ServerSocket(port);
2. Wait for connections from clients requesting connections to that port.
// Block on accept()

7 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

Socket channel = server.accept();


You'll get a Socket object as a result of the connection.
3. Get input and output streams associated with the socket.
out = new PrintWriter(channel.getOutputStream());
reader = new InputStreamReader(channel.getInputStream());
in = new BufferedReader (reader);
Now you can read and write to the socket, thus, communicating with the client.
String data = in.readLine();
out.println("Hey! I heard you over this socket!");

When a server invokes the accept() method of the ServerSocket instance, the main server thread blocks until a
client connects to the server; it is then prevented from accepting further client connections until the server has
processed the client's request. This is known as an iterative server, since the main server method handles
each client request in its entirety before moving on to the next request. Iterative servers are good when the
requests take a known, short period of time. For example, requesting the current day and time from a time-of-
day server.

The classes contained in the java.net package are

8 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

Let's see a simple of Java socket programming where client sends a text and server receives and
prints it.

File: MyServer.java

import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args){
try{
ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept();//establishes connection
DataInputStream dis=new DataInputStream(s.getInputStream());
String str=(String)dis.readUTF();
System.out.println("message= "+str);
ss.close();
}catch(Exception e){System.out.println(e);}
}
}
File: MyClient.java
import java.io.*;
import java.net.*;
public class MyClient {
public static void main(String[] args) {
try{
Socket s=new Socket("localhost",6666);
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
dout.writeUTF("Hello Server");
dout.flush();
dout.close();
s.close();
}catch(Exception e){System.out.println(e);}
}
}

9 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

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.

Example of Java Socket Programming (Read-Write both side)


In this example, client will write first to the server then server will receive and print the text. Then server will
write to the client and client will receive and print the text. The step goes on.

File: MyServer.java
import java.net.*;
import java.io.*;
class MyServer{
public static void main(String args[])throws Exception{
ServerSocket ss=new ServerSocket(3333);
Socket s=ss.accept();
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

String str="",str2="";
while(!str.equals("stop")){

10 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

str=din.readUTF();
System.out.println("client says: "+str);
str2=br.readLine();
dout.writeUTF(str2);
dout.flush();
}
din.close();
s.close();
ss.close();
}}
File: MyClient.java
import java.net.*;
import java.io.*;
class MyClient{
public static void main(String args[])throws Exception{
Socket s=new Socket("localhost",3333);
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str="",str2="";
while(!str.equals("stop")){
str=br.readLine();
dout.writeUTF(str);
dout.flush();
str2=din.readUTF();
System.out.println("Server says: "+str2);
}
dout.close();
s.close();
}}

InetAddress
• The InetAddress class is used to encapsulate both the numerical IP address and the domain

11 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

• name for that address. You interact with this class by using the name of an IP host, which is more
convenient and understandable than its IP address. The InetAddress class hides the number inside.
InetAddress can handle both IPv4 and IPv6 addresses.

The InetAddress class has several other methods, which can be used on the objects returned
by the methods just discussed. Here are some of the more commonly used methods:

Internet addresses are looked up in a series of hierarchically cached servers. That means that your local
computer might know a particular name-to-IP-address mapping automatically, such as for itself and nearby
servers. For other names, it may ask a local DNS server for IP address information. If that server doesn’t have
a particular address, it can go to a remote site and ask for it. This can continue all the way up to the root server.
This process might take a long time, so it is wise to structure your code so that you cache IP address
information locally rather than look it up repeatedly.

12 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

Inet4Address and Inet6Address


Beginning with version 1.4, Java has included support for IPv6 addresses. Because of this, two subclasses of
InetAddress were created: Inet4Address and Inet6Address. Inet4Address represents a traditional-style IPv4
address. Inet6Address encapsulates a new-style IPv6 address. Because they are subclasses of InetAddress, an
InetAddress reference can refer to either. This is one way that Java was able to add IPv6 functionality without
breaking existing code or adding many more classes. For the most part, you can simply use
InetAddress when working with IP addresses because it can accommodate both styles.

Factory Methods
The InetAddress class has no visible constructors. To create an InetAddress object, you have to use one of the
available factory methods. Factory methods are merely a convention whereby static methods in a class return
an instance of that class. This is done in lieu of overloading a constructor with various parameter lists when
having unique method names makes the results much clearer. Three commonly used InetAddress factory
methods are shown here:

• static InetAddress getLocalHost( )throws UnknownHostException

• static InetAddress getByName(String hostName)throws UnknownHostException


• static InetAddress[ ] getAllByName(String hostName)throws UnknownHostException

 The getLocalHost( ) method simply returns the InetAddress object that represents the local host. The
getByName( ) method returns an InetAddress for a host name passed to it. If these methods are unable
to resolve the host name, they throw an UnknownHostException.
 On the Internet, it is common for a single name to be used to represent several machines. In the world
of web servers, this is one way to provide some degree of scaling.
 The getAllByName( ) factory method returns an array of InetAddresses that represent all of the
addresses that a particular name resolves to.
 It will also throw an UnknownHostException if it can’t resolve the name to at least one address.
 InetAddress also includes the factory method getByAddress( ), which takes an IP address and returns
an InetAddress object. Either an IPv4 or an IPv6 address can be used.
The following example prints the addresses and names of the local machine and two well-known Internet web sites:

13 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

OUTPUT
• Host Name: www.javatpoint.com
• IP Address: 172.67.196.82

14 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

Datagrams
TCP/IP-style networking is appropriate for most networking needs. It provides a serialized, predictable, reliable
stream of packet data. This is not without its cost, however. TCP includes many complicated algorithms for
dealing with congestion control on crowded networks, as well as pessimistic expectations about packet loss. This
leads to a somewhat inefficient way to transport data. Datagrams provide an alternative. Datagrams are bundles
of information passed between machines. They are somewhat like a hard throw from a well-trained but
blindfolded catcher to the third baseman. Once the datagram has been released to its intended target, there is no
assurance that it will arrive or even that someone will be there to catch it. Likewise, when the datagram is
received, there is no assurance that it hasn’t been damaged in transit or that whoever sent it is still there to receive
a response. Java implements datagrams on top of the UDP protocol by using two classes:
theDatagramPacket object is the data container, while the DatagramSocket is the mechanism used to send
or receive the DatagramPackets.

DatagramSocket

DatagramSocket defines four public constructors. They are shown here:


DatagramSocket( ) throws SocketException

15 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

DatagramSocket(int port) throws SocketException


DatagramSocket(int port, InetAddress ipAddress) throws SocketException
DatagramSocket(SocketAddress address) throws SocketException
The first creates a DatagramSocket bound to any unused port on the local computer. The second creates
a DatagramSocket bound to the port specified by port. The third constructs a DatagramSocket bound to
the specified port and InetAddress. The fourth constructs a DatagramSocket bound to the specified
SocketAddress. SocketAddress is an abstract class that is implemented by the concrete class
InetSocketAddress. InetSocketAddress encapsulates an IP address with a port number. All can throw a
SocketException if an error occurs while creating the socket.
DatagramSocket defines many methods. Two of the most important are send( ) and receive( ), which are
shown here:
void send(DatagramPacket packet) throws IOException
void receive(DatagramPacket packet) throws IOException
The send( ) method sends packet to the port specified by packet. The receive method waits for a packet to
be received from the port specified by packet and returns the result.
Other methods give you access to various attributes associated with a DatagramSocket.

Here is a sampling:

DatagramPacket
DatagramPacket defines several constructors. Four are shown here:
DatagramPacket(byte data[ ], int size)
DatagramPacket(byte data[ ], int offset, int size)

16 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

DatagramPacket(byte data[ ], int size, InetAddress ipAddress, int port)


DatagramPacket(byte data[ ], int offset, int size, InetAddress ipAddress, int port)
The first constructor specifies a buffer that will receive data and the size of a packet. It is used for receiving data
over a DatagramSocket. The second form allows you to specify an offset into the buffer at which data will be
stored. The third form specifies a target address and port, which are used by a DatagramSocket to determine
where the data in the packet will be sent. The fourth form transmits packets beginning at the specified offset into
the data. Think of the first two forms as building an “in box,” and the second two forms as stuffing and addressing
an envelope.
DatagramPacket defines several methods, including those shown here, that give access to the address and port
number of a packet, as well as the raw data and its length. In general, the get methods are used on packets that are
received and the set methods are used on packets that will be sent.

A Datagram Example

Example of Sending DatagramPacket by DatagramSocket

17 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

//DSender.java
import java.net.*;
public class DSender{
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket();
String str = "Welcome java";
InetAddress ip = InetAddress.getByName("127.0.0.1");

DatagramPacket dp = new DatagramPacket(str.getBytes(), str.length(), ip, 3000);


ds.send(dp);
ds.close();
}
}

Example of Receiving DatagramPacket by DatagramSocket


/DReceiver.java
import java.net.*;
public class DReceiver{
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket(3000);

18 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

byte[] buf = new byte[1024];


DatagramPacket dp = new DatagramPacket(buf, 1024);
ds.receive(dp);
String str = new String(dp.getData(), 0, dp.getLength());
System.out.println(str);
ds.close();
}
}

Write a program using DatagramPacket and DatagramSocket to create chat application


ServerSideData.java:
import java.net.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ServerSideData


{
public static void main(String[] args) throws IOException {
DatagramSocket ds = new DatagramSocket(2019);

byte[] receiveData = new byte[512];


byte[] sendData = new byte[512];

BufferedReader br = new BufferedReader( new InputStreamReader(System.in));

System.out.println(" UDP Server Socket is created, waiting for client ");

19 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

do
{
DatagramPacket receiveDP = new
DatagramPacket(receiveData,receiveData.length);
ds.receive(receiveDP);

String clientMessage = new


String(receiveDP.getData(),0,receiveDP.getLength());
System.out.println("Client Message:"+clientMessage);

InetAddress ip = receiveDP.getAddress();

System.out.print("\n\nEnter Server Message:");


String serverMessage = br.readLine();
sendData = serverMessage.getBytes();
DatagramPacket sendDP = new DatagramPacket(sendData, sendData.length, ip,
receiveDP.getPort());
ds.send(sendDP);

receiveData = new byte[512];


}while(true);

}
}
ClientSideData.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;

public class ClientSideData


{
public static void main(String[] args) throws IOException {
DatagramSocket ds = new DatagramSocket();

byte[] receiveData = new byte[512];


byte[] sendData = new byte[512];

BufferedReader br = new BufferedReader(


new InputStreamReader(System.in)
);

System.out.println(" UDP Client Socket is created, waiting for server ");

InetAddress ip = InetAddress.getLocalHost();

do
{
System.out.print("\nEnter Client Message:");
String clientMessage = br.readLine();
sendData = clientMessage.getBytes();

20 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

DatagramPacket sendDP = new DatagramPacket(sendData, sendData.length, ip,


2019);

ds.send(sendDP);

DatagramPacket receiveDP = new


DatagramPacket(receiveData,receiveData.length);
ds.receive(receiveDP);

String serverMessage = new


String(receiveDP.getData(),0,receiveDP.getLength());

System.out.println("\n\nServer Message:"+serverMessage);
}while(true);

}
}

URL
• URL is an abbreviation for Uniform Resource Locator. An URL is a form of string that helps to
find a resource on the World Wide Web (WWW).
• URL known as Uniform Resource Locator is simply a string of text that identifies all the resources
on the Internet on the World Wide Web (WWW). telling us the address of the resource, how to
communicate with it, and retrieve something from it.

The URL provides a reasonably intelligible form to uniquely identify or address information on the
Internet. URLs are ubiquitous; every browser uses them to identify information on the Web. Within Java’s
network class library, the URL class provides a simple, concise API to access information across the
Internet using URLs. All URLs share the same basic format, although some variation is allowed.

Java URLConnection Class


The Java URLConnection class represents a communication link between the URL and the application. It can
be used to read and write data to the specified resource referred by the URL.

21 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

Features of URLConnection class

1. URLConnection is an abstract class. The two subclasses HttpURLConnection and JarURLConnection


makes the connetion between the client Java program and URL resource on the internet.
2. With the help of URLConnection class, a user can read and write to and from any resource referenced
by an URL object.
3. Once a connection is established and the Java program has an URLConnection object, we can use it to
read or write or get further information like content length, etc.

How to get the object of URLConnection Class


The openConnection() method of the URL class returns the object of URLConnection class.

Syntax:

public URLConnection openConnection()throws IOException{}

Example of Java URLConnection Class

import java.io.*;
import java.net.*;
public class URLConnectionExample {
public static void main(String[] args){
try{
URL url=new URL("http://www.javatpoint.com/java-tutorial");
URLConnection urlcon=url.openConnection();
InputStream stream=urlcon.getInputStream();
int i;
while((i=stream.read())!=-1){
System.out.print((char)i);
}
}catch(Exception e){System.out.println(e);}
}
}
Write a program using URL class to retrieve the host, protocol, port and file of URL http://www.msbte.org.in
import java.net.URL;

22 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

import java.net.MalformedURLException;
public class URLRetrive
{
public static void main(String[] args) throws MalformedURLException {
URL url = new URL("https://msbte.org.in/");
System.out.println("Authority: "+ url.getAuthority());
System.out.println("Default Port: "+ url.getDefaultPort());
System.out.println("File: "+ url.getFile());
System.out.println("Path: "+ url.getPath());
System.out.println("Protocol: "+ url.getProtocol());
System.out.println("Reference: "+ url.getRef());
}
}

Write a program using URL and URLConnection class to retrieve the date, content type, content length information of
any entered URL.
import java.net.URL;
import java.net.URLConnection;
import java.util.Scanner;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Date;

public class URLInfo


{
public static void main(String[] args) throws IOException , MalformedURLException
{
Scanner sc = new Scanner(System.in);

System.out.print("Enter any Url: ");


String ad = sc.nextLine();

URL url = new URL(ad);


URLConnection uc = url.openConnection();

System.out.println("Date:"+ new Date(uc.getDate()) );


System.out.println("Content Type: "+ uc.getContentType());
System.out.println("Content Length: "+ uc.getContentLength());

}
}

23 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

Some of the important methods are helpful in using to read or write or to get some info after the connection is

established. They are:

1. URLConnection openConnection(): This method helps in opening the connection to the specific or

specified URL.

2. Object getContent(): It will retrieve some content of URLConnection.

3. Map<String, List > getHeaderFields(): It will take the map which contains some values of various header

fields in the specific HTTP folder.

4. getContentEncoding(): It will return some value of the content-encoding header’s field.

5. getContentLength(): It will return the content header field’s length.

6. getDate(): It will return header field’s date value

7. getHeaderField (int-i): It will return the header’s i-th index value

8. getHeaderField (String-Field): It will return the field named value “field” in some header which is to get a

list of all the header fields.

9. OutputStream getOutputStream(): It will return one of the connection’s output stream.

10. InputStream getInputStream(): It will return one input stream to the open connection.

11. setAllowUserInteraction(boolean): It will set the setting as a TRUE value which means users can interact

with the page. By default, the value of it is TRUE.

24 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

12. setDefaultUseCaches(boolean): It will set useCache field’s default as the provided value.

13. setDoInput(boolean): It will set only if the user is allowed to take a specific input or not

14. setDoInput(boolean): It will set only if the user now allows writing on the specific page. By default, its

value is FALSE since, most of all, the URL doesn’t even allow writing.

HttpURLConnection
The Java HttpURLConnection class is http specific URLConnection. It works for HTTP protocol only.

By the help of HttpURLConnection class, you can retrieve information of any HTTP URL such as header
information, status code, response code etc.

The java.net.HttpURLConnection is subclass of URLConnection class.

HttpURLConnection Class Constructor


Constructor Description

protected HttpURLConnection(URL u) It constructs the instance of


HttpURLConnection class.

25 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

The openConnection() method of URL class returns the object of URLConnection class.

Syntax

public URLConnection openConnection()throws IOException{}

You can typecast it to HttpURLConnection type as given below.

1. URL url=new URL("http://www.google.com");


2. HttpURLConnection huc=(HttpURLConnection)url.openConnection();

26 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

import java.io.*;
import java.net.*;
public class HttpURLConnectionDemo{
public static void main(String[] args){
try{
URL url=new URL("http://www.javatpoint.com/java-tutorial");
HttpURLConnection huc=(HttpURLConnection)url.openConnection();
for(int i=1;i<=8;i++){
System.out.println(huc.getHeaderFieldKey(i)+" = "+huc.getHeaderField(i));
}
huc.disconnect();
}catch(Exception e){System.out.println(e);}
}
}
Output:

27 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

28 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

The HttpURLConnection is an important class in the java.net package which allows you to send an HTTP
request from a Java program. By using this class you can send any kind of HTTP request like
GET, POST, PUT DELETE, HEAD, etc to the server and call REST APIs.

1. How to Send a simple GET request


You can send an HTTP request by just creating a URL object with the actual URL and then creating an
HttpURLConnection from that. Btw, the actual request is not sent until you perform some operation like
reading a response code or reading data from InputStream.

2. How to Send a POST request from Java Program


• The HttpConnection class also allows you to send a POST request, and not just POST by any HTTP
method e.g. PUT, DELETE, or PATCH. All you need to do is call the setRequestMethod("POST")
from HttpURLConnection with the appropriate method name e.g. POST to send a POST request.

Here is the code:


URL url = new URL("https://api.github.com/users/google");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");

29 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

3. How to Check the Response Code in Java


Checking the response code is very easy while using HttpURLConnection, you can just call the
getResponseCode() method and it will return the error or response code as int. It will also send the request to
the server if it does not send it already.
Here is the code to retrieve response code in Java:
int code = con.getResponseCode();

4. Dealing with Headers


You can add headers into HTTP request by calling the setRequestProperty() method of HttpURLConnection
as shown below:
con.setRequestProperty("Content-Type", "application/json");
In this case, we are setting the "Content-Type" header to "application/json" to indicate that the request is in
JSON format. Similarly, you can also retrieve header values from HTTP response using the
getRequestProperty() method, which accepts header name and returns a value like
String header = con.getRequestProperty("Content-Type");

What is EJB
 EJB is an acronym for enterprise java bean. It is a specification provided by Sun Microsystems
to develop secured, robust and scalable distributed applications.
 An EJB is a component of the J2EE architecture that primarily provides business logic to a J2EE
application and interacts with other server-side J2EE components.
 The nature of the business logic and the interactions with other| server-side J2EE components are
dependent on the J2EE application.
 An EJB is written in the Java programming language.

To run EJB application, you need an application server (EJB Container) such as Jboss, Glassfish, Weblogic,
Websphere etc. It performs:

a. life cycle management,


b. security,
c. transaction management, and
d. object pooling.

30 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

EJB application is deployed on the server, so it is called server side component also.

The EJB Container


1. An EJB container is a vendor-provided entity located on the EBJ server that manages system-level services for
EJB.
2. The EJB container is one of several containers, each of which handles a J2EE component such as a Java servlets
or JSP.

3. An EJB container provides a reusable pool of distributed components. Each EJB must be installed in an EJB
container

When use Enterprise Java Bean?


1. Application needs Remote Access. In other words, it is distributed.
2. Application needs to be scalable. EJB applications supports load balancing, clustering and fail-over.
3. Application needs encapsulated business logic. EJB application is separated from presentation and
persistent layer.

EJB Classes

Types of EBJ

1. Entity JavaBean class (entity bean) : used to represent business data.


2. Session JavaBean class (session bean) : used to model a business process.
3. Message-Driven JavaBean class ( message-driven bean) : used to receive messages from a JMS (Java
Message Service) resource
EJB Interface

1. The session and entity beans must have two interfaces.


2. These are Home interface and the Remote interface.
3. Both interfaces are declared by the developer of the EJB and are implemented by the EJB container.
4. The Home interface must extend the EJBHome interface.
There are three types of EJB:
1. Session Bean: Session bean contains business logic that can be invoked by local, remote or webservice
client. There are two types of session beans: (i) Stateful session bean and (ii) Stateless session bean.
 (i) Stateful Session bean :
Stateful session bean performs business task with the help of a state. Stateful session bean can be used to
access various method calls by storing the information in an instance variable. Some of the applications

31 D.M.S Mandal’s College of Computer Applications, Belgaum


BCA V SEM Advanced Java C.A. SATERI

require information to be stored across separate method calls. In a shopping site, the items chosen by a
customer must be stored as data is an example of stateful session bean.
 (ii) Stateless Session bean :
Stateless session bean implement business logic without having a persistent storage mechanism, such as
a state or database and can used shared data. Stateless session bean can be used in situations where
information is not required to used across call methods.
2. Message Driven Bean: Like Session Bean, it contains the business logic but it is invoked by passing
message.
3. Entity Bean: It summarizes the state that can be remained in the database. It is deprecated. Now, it is
replaced with JPA (Java Persistent API). There are two types of entity bean:
 (i) Bean Managed Persistence :
In a bean managed persistence type of entity bean, the programmer has to write the code for database
calls. It persists across multiple sessions and multiple clients.

 (ii) Container Managed Persistence :


Container managed persistence are enterprise bean that persists across database. In container managed
persistence the container take care of database calls.

Advantages of Enterprise Java Beans


1. EJB repository yields system-level services to enterprise beans, the bean developer can focus on solving
business problems. Rather than the bean developer, the EJB repository is responsible for system-level
services such as transaction management and security authorization.
2. The beans rather than the clients contain the application’s business logic, the client developer can focus
on the presentation of the client. The client developer does not have to code the pattern that execute business
rules or access databases. Due to this the clients are thinner which is a benefit that is particularly important
for clients that run on small devices.
3. Enterprise Java Beans are portable elements, the application assembler can build new applications from
the beans that already exists.

Disadvantages of Enterprise Java Beans


1. Requires application server
2. Requires only java client. For other language client, you need to go for webservice.
3. Complex to understand and develop EJB applications.

32 D.M.S Mandal’s College of Computer Applications, Belgaum

You might also like