Java Full Notes
Java Full Notes
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
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.
SECTION - A
P.T.O.
41423/D230 2
SECTION - B
Answer any four of the following : 5x4=20
2. Explain swing features.
SECTION - C
Answer any four of the following : 10x4=40
7. Write a JSP program to find factorial of given number.
10. Explain Session Java bean and Message Driver Java bean.
-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.
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
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
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.
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.
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.
• 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.
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)
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.
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.
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.
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.
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:
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:
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
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.
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.
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:
int getClickCount( )
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.
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( )
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 ();
}
}
• Registered the button component with respective event. i.e. ActionEvent by addActionListener().
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);
}
});
}
}
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
Example:
Example of FlowLayout class: Using FlowLayout(int align, int hgap, int vgap) constructor
import java.awt.*;
import javax.swing.*;
frameObj.setSize(300, 300);
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
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);
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
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();
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.
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.
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.
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
ActionListener and ItemListener do not have corresponding adapter class as they contain only one abstract
method.
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);
}
}
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.
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
• 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:
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)
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.
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.
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.
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
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
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.
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.
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.
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.
JComponent:
The class JComponent is the base class for all Swing components except top-level
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.
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)
}
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.
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)
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.
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:
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.
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.
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
Example :
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();
}
}
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);
}
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.
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);
Examples
SetBounds Method
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
import javax.swing.*;
public class SwingApp {
SwingApp()
{
JFrame f = new JFrame();
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);
}
{
JFrame frame = new JFrame();
JOptionPane.showMessageDialog(frame, "This is a JOptionPane message window.");
}
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();
}
}
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();
}
}
class MessageDialogs1 {
// Driver code
public static void main(String args[])
{
// Creating Object of demo class.
Demo f = new Demo();
}
}
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 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.
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.
• 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.
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.
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.
• 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
• 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.
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.
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
To delete/drop table
drop table employees;
To update data
UPDATE Students
SET DepartmentId = 3
WHERE StudentId = 6;
Retrieving data
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()
• 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.
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));
}
Executing Statements Once a Statement object is created, we can use it to execute a SQL statement with one of its
three execute methods.
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.
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.
}
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));
}
}
}
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.
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.
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.
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.absolute(3);
result.deleteRow(0);
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.
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.
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
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.
import java.sql.*;
class InsertPrepared{
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");
int i=stmt.executeUpdate();
System.out.println(i+" records inserted");
con.close();
}
}
Example of PreparedStatement interface that updates the record
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.
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.
fast performance It makes the performance fast because database is hit at the time of commit.
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.
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();
}}
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();
}
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
con.setAutoCommit(false);
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");
String ans=br.readLine();
if(ans.equals("n")){
break;
}
}
con.commit();
System.out.println("record successfully saved");
}}
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");
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();
• 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();
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();
con.close();
}catch(Exception e){ System.out.println(e);}
}
}
Output :
• 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.
• 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:
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.
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.
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.
The doGet() and doPost() are most frequently used methods with in each service request.
Here is the signature of these two methods.
• Create a Servlet
<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.
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>");
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>
What is web.xml
They constitute the Servlet API. These packages are not part of the java core packages. Instead, they are
standard extensions provided by Tomcat.
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.
Classes
The following table summarizes the core classes that are provided in javax.servlet package.
import java.io.*;
import javax.servlet.*;
throws IOException,ServletException{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.print("<html><body>");
out.print("</body></html>");
} }
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);
.......
}
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.
Classes
The following table summarizes the core classes that are provided in this package.
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.
<HTML>
<HEAD>
</HEAD>
<BODY BGCOLOR="#FDF5E6">
<FORM ACTION="http://localhost:8080/servlets-examples/servlet/ColorGetServlet"
METHOD=“GET">
<B>Color:
</select><BR>
</FORM>
</BODY>
</HTML>
Example
Files Required
• index.html
• OnServletConfig.java
• web.xml
index.html
<font face="verdana" size="2px">
Example on ServletConfig<br>
</form>
</font>
Web.xml
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.
• 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
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
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.
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
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.
A servlet can read a cookie by calling the getCookies() method of the HttpServletRequest
object. It returns an array of cookie objects.
Methods
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
{
// 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();
}
}
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.
• The time interval in which two systems(i.e. the client and the server) communicate with each other can
be termed as a session.
• 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.
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.
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.
• 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.
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.
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:
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:
Example 1:
if(date != null)
{
out.println(“Last access: " + date + "<br>");
}
// Display current date/time:
date = new Date();
hs.setAttribute(“date”,date);
out.println(“Current date :" + date);
}
}
Output: When the web page is accessed first time. A session is created shown below.
Servlet1
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response){
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 {
HttpSession session=request.getSession(false);
String n=(String)session.getAttribute("uname");
out.print("Hello "+n);
out.close();
}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>
• 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.
<html>
<body>
<% out.print(2*5); %>
</body>
</html>
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 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.*;
</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>
<br>
<input type=submit value="Add">
</form>
</body>
</html>
• //@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/>
}
}
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>
• <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
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.
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.
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.
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
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.
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.
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.
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.
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);}
}
}
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.
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")){
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
• 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.
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:
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:
OUTPUT
• Host Name: www.javatpoint.com
• IP Address: 172.67.196.82
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
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)
A Datagram Example
//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");
do
{
DatagramPacket receiveDP = new
DatagramPacket(receiveData,receiveData.length);
ds.receive(receiveDP);
InetAddress ip = receiveDP.getAddress();
}
}
ClientSideData.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;
InetAddress ip = InetAddress.getLocalHost();
do
{
System.out.print("\nEnter Client Message:");
String clientMessage = br.readLine();
sendData = clientMessage.getBytes();
ds.send(sendDP);
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.
Syntax:
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;
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;
}
}
Some of the important methods are helpful in using to read or write or to get some info after the connection is
1. URLConnection openConnection(): This method helps in opening the connection to the specific or
specified URL.
3. Map<String, List > getHeaderFields(): It will take the map which contains some values of various header
8. getHeaderField (String-Field): It will return the field named value “field” in some header which is to get a
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
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 openConnection() method of URL class returns the object of URLConnection class.
Syntax
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:
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.
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:
EJB application is deployed on the server, so it is called server side component also.
3. An EJB container provides a reusable pool of distributed components. Each EJB must be installed in an EJB
container
EJB Classes
Types of EBJ
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.