Advanced Java ( PDFDrive )
Advanced Java ( PDFDrive )
Part-1
www.educlash.com
3
INTRODUCTION TO SWING
Unit Structure:
1. Objectives
2. Introduction to JFC and Swing
3. Swing Features and Concepts
4. Heavy Weight Containers
5. Top-Level Containers
6. Intermediate Swing Containers
7. Internal Frames
8. Summary
9. Unit end exercise
10. Further Reading
1. OBJECTIVES
www.educlash.com
4
www.educlash.com
5
Swing lets you specify which look and feel your program's
GUI uses. By contrast, AWT components always have the look and
feel of the native platform.
}//constructor
//Step 6 – Event Handling. (Event handling code will come
//here)
www.educlash.com
6
Most Swing programs also need to import the two main AWT
packages:
import java.awt.*;
import java.awt.event.*;
www.educlash.com
7
www.educlash.com
8
1.3.1 JFrames
www.educlash.com
9
Constructors:
Methods:
www.educlash.com
10
8 void setTitle(String title) - Sets the title for this frame to the
specified string.
1.3.2 JDialog
Constructors :
Methods:
www.educlash.com
11
1.3.3 JApplet
Constructors :
JApplet() - Creates a swing applet instance.
Methods:
1 Container getContentPane() - Returns the contentPane object
for this applet.
2 void setJMenuBar(JMenuBar menuBar) - Sets the menubar for
this applet.
3 void setLayout(LayoutManager manager) - By default the
layout of this component may not be set, the layout of its
contentPane should be set instead.
4 void update(Graphics g) - Just calls paint(g).
www.educlash.com
12
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import java.applet.JApplet;
/* <applet code="FreeHand.class" width=500 height=500 >
</applet> */
public class FreeHand extends JApplet
{
int lastx,lasty,newx,newy;
JButton b1=new JButton("Color Chooser");
JColorChooser c1= new JColorChooser();
Graphics g;
Color ss; public
void init()
{
FreeHandListener fhl=new FreeHandListener(this);
g=getGraphics();
JPanel jp=(JPanel)getContentPane();
jp.setLayout(new FlowLayout());
b1.addActionListener(fhl);
jp.add(b1);
addMouseListener(fhl);
addMouseMotionListener(fhl);
addKeyListener(fhl);
}
}// Class FH
class FreeHandListener implements
ActionListener,MouseMotionListener,MouseListener,KeyListener
{
FreeHand fh;
public FreeHandListener(FreeHand fh)
{
this.fh=fh;
}
public void actionPerformed(ActionEvent e)
{
JDialog jd=JColorChooser.createDialog(fh,"Choose
Color",true,fh.c1,new SetColor(fh),null);
jd.setVisible(true);
}
public class SetColor implements ActionListener
www.educlash.com
13
{
FreeHand fh;
public SetColor(FreeHand fh)
{
this.fh=fh;
}
public void actionPerformed(ActionEvent e)
{
fh.ss=fh.c1.getColor();
}
}// inner class
public void mousePressed(MouseEvent e)
{
fh.lastx=e.getX();
fh.lasty=e.getY();
}
public void mouseDragged(MouseEvent e)
{
fh.g.setColor(fh.ss);
fh.newx=e.getX();
fh.newy=e.getY();
fh.g.drawLine(fh.lastx,fh.lasty,fh.newx,fh.newy);
fh.lastx=fh.newx;
fh.lasty=fh.newy;
}
public void keyPressed(KeyEvent e)
{
if(e.getKeyCode()==KeyEvent.VK_C)
fh.repaint();
}
public void keyTyped(KeyEvent e){}
public void keyReleased(KeyEvent e){}
public void mouseReleased(MouseEvent e){}
public void mouseExited(MouseEvent e) {}
public void mouseClicked(MouseEvent e) {}
public void mouseMoved(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
}//class fhl
www.educlash.com
14
Container con=getContentPane();
con.setLayout(new GridBagLayout());
gbc.gridx=2;
gbc.gridy=2;
con.add(cc,gbc);
}
}
www.educlash.com
15
1.3.4 JWindow
Constructors:
Methods :
www.educlash.com
16
www.educlash.com
17
JRootPane's layeredPane
JRootPane's glassPane
1.5.1 JPanel
www.educlash.com
18
Constructors :
Constructor Purpose
JPanel() Create a panel. The LayoutManager
JPanel(LayoutManager) parameter provides a layout manager for
the new panel. By default, a panel uses a
FlowLayout to lay out its components.
Methods :
Method Purpose
void add(Component) void Add the specified component to the
add(Component, int) void panel. When present, the int parameter
add(Component, Object) is the index of the component within
void add(Component, the container. By default, the first
Object, int) component added is at index 0, the
second is at index 1, and so on. The
Object parameter is layout manager
dependent and typically provides
information to the layout manager
regarding positioning and other layout
constraints for the added component.
www.educlash.com
19
1.5.2 JSrollPane
JScrollPane provides a scrollable view of a component. A
JScrollPane manages a viewport, optional vertical and horizontal
scroll bars, and optional row and column heading viewports.
Constructors :
Constructor Purpose
JScrollPane() Create a scroll pane. The Component
JScrollPane(Component) parameter, when present, sets the scroll
JScrollPane(int, int) pane's client. The two int parameters,
JScrollPane(Component, when present, set the vertical and
int, int) horizontal scroll bar policies
(respectively).
www.educlash.com
20
Methods:
Method Purpose
void setVerticalScrollBarPolicy(int) Set or get the vertical scroll
int getVerticalScrollBarPolicy() policy. ScrollPaneConstants
SAME FOR HORIZONTAL defines three values for
specifying this policy:
VERTICAL_SCROLLBAR_AS_
NEEDED (the default),
VERTICAL_SCROLLBAR_AL
WAYS, and
VERTICAL_SCROLLBAR_NEV
ER.
void setViewportBorder(Border) Set or get the border around
Border getViewportBorder() the viewport.
void t the column or row
setColumnHeaderView(Componen ader for the scroll
t) ne.
void
setRowHeaderView(Component)
void setCorner(Component, int) Set or get the corner specified.
Component getCorner(int) The int parameter specifies
which corner and must be one
of the following constants
defined in ScrollPaneConstants:
UPPER_LEFT_CORNER,
UPPER_RIGHT_CORNER,
LOWER_LEFT_CORNER, and
LOWER_RIGHT_CORNER.
www.educlash.com
21
Constructors:
Constructor Purpose
JTabbedPane() JTabbedPane(int Creates a tabbed pane. The
tabPlacement) JTabbedPane(int first optional argument specifies
tabPlacement, int where the tabs should appear.
tabLayoutPolicy) By default, the tabs appear at
the top of the tabbed pane.You
can specify these positions
TOP, BOTTOM, LEFT, RIGHT.
The second optional argument
specifies the tab layout policy.
Methods:
Method Purpose
JTabbedPane() Create a tabbed pane. The optional
JTabbedPane(int) argument specifies where the tabs should
appear. By default, the tabs appear at the top
of the tabbed pane. You can specify these
positions (defined in the SwingConstants
interface, which JTabbedPane implements):
TOP, BOTTOM, LEFT, RIGHT.
addTab(String, Icon, Add a new tab to the tabbed pane. The first
Component, String) argument specifies the text on the tab. The
addTab(String, Icon, optional icon argument specifies the tab's
Component) icon. The component argument specifies the
addTab(String, component that the tabbed pane should
Component) show when the tab is selected. The fourth
argument, if present, specifies the tool tip text
for the tab.
insertTab(String, Insert a tab at the specified index, where the
Icon, Component, first tab is at index 0. The arguments are the
String, int) same as for addTab.
void set Select the tab that has the specified
SelectedIndex (int) component or index. Selecting a tab has the
void set Selected effect of displaying its associated component.
Component
(Component)
void set EnabledAt Set or get the enabled state of the tab at the
(int, boolean) specified index.
boolean is
EnabledAt (int)
www.educlash.com
22
public CitiesPanel() {
add(new JButton("Mumbai"));
add(new JButton("Delhi"));
add(new JButton("Banglore"));
add(new JButton("Chennai"));
}
}
class ColorPanel extends JPanel {
public ColorPanel() {
add(new JCheckBox("Red"));
add(new JCheckBox("Yellow"));
add(new JCheckBox("Green"));
add(new JCheckBox("Blue"));
}
}
class FlavourPanel extends JPanel {
public FlavourPanel() {
String item[]={"Vanila","Stroberry","Chocolet"};
JComboBox jcb=new JComboBox(item);
add(jcb);
}
}
www.educlash.com
23
Constructors:
Constructor Summary
Methods:
Method Purpose
void Make the internal frame visible (if true) or
setVisible(boolean) invisible (if false). You should invoke
setVisible(true) on each JInternalFrame
before adding it to its container. (Inherited
from Component).
www.educlash.com
24
www.educlash.com
25
{
public ColorPanel()
{
super("Select Colors",true,true);
JPanel jp=new JPanel();
jp.add(new JButton("Red"));
jp.add(new JButton("Blue"));
jp.add(new JButton("Green"));
getContentPane().add(jp);
setPreferredSize(new Dimension(300,300));
setDefaultCloseOperation(HIDE_ON_CLOSE);
}
}
//Third internal frame
import javax.swing.*; import
java.awt.Dimension;
public class FlavourPanel extends JInternalFrame
{
public FlavourPanel()
{
super("Select Flavours",true,true);
JPanel jp=new JPanel();
jp.add(new JButton("Vanilla"));
jp.add(new JButton("Chocolate"));
jp.add(new JButton("Strawberry"));
getContentPane().add(jp);
setPreferredSize(new Dimension(300,300));
setDefaultCloseOperation(HIDE_ON_CLOSE);
}
}
//Main Frame
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class IFrameDemo extends JFrame implements
ActionListener
{
CitiesPanel c1=new CitiesPanel();
ColorPanel c2=new ColorPanel();
FlavourPanel c3=new FlavourPanel();
public IFrameDemo()
www.educlash.com
26
{
JMenuBar mb=new JMenuBar(); JMenu
select=new JMenu("Select"); JMenuItem
city=new JMenuItem("City");
JMenuItem color=new JMenuItem("Color");
JMenuItem flavour=new JMenuItem("Flavour");
select.add(city);
select.add(color);
select.add(flavour);
mb.add(select);
setJMenuBar(mb);
city.addActionListener(this);
color.addActionListener(this);
flavour.addActionListener(this);
JDesktopPane dp=new JDesktopPane();
dp.setLayout(new FlowLayout());
dp.add(c1);
dp.add(c2);
dp.add(c3);
getContentPane().add(dp,BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent e)
{
String args=e.getActionCommand();
if(args.equals("City"))
{
c1.setVisible(true);
c2.setVisible(false);
c3.setVisible(false);
}
else if(args.equals("Color"))
{
c1.setVisible(false);
c2.setVisible(true);
c3.setVisible(false);
}
else if(args.equals("Flavour"))
{
c1.setVisible(false);
c2.setVisible(false);
www.educlash.com
27
c3.setVisible(true);
}
}
public static void main(String args[])
{
IFrameDemo f1=new IFrameDemo();
f1.setVisible(true);
f1.setSize(500,500);
f1.setTitle("Internal Frame Demo");
f1.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
7. SUMMARY
www.educlash.com
28
www.educlash.com
29
Unit Structure:
1. Objectives
2. The JComponent Class & Swing Components
3. Interface Action
4. Printing with 2D API
5. Java Print Service API
6. Summary
7. Unit end exercise
8. Further Reading
1. OBJECTIVES
JComponent Features
The JComponent class provides the following functionality to its
descendants:
www.educlash.com
30
2.1.2 JLabel
www.educlash.com
31
www.educlash.com
32
2.1.3 JTextField
2.1.4 JButton
www.educlash.com
33
www.educlash.com
34
2.1.5 JCheckBox
www.educlash.com
35
2.1.6 JRadioButton
Constructor Purpose
JRadioButton(String) Create a JRadioButton instance. The
JRadioButton(String, string argument specifies the text, if
boolean) any, that the radio button should
JRadioButton(Icon) display. Similarly, the Icon argument
JRadioButton(Icon, specifies the image that should be
boolean) used instead of the look and feel's
JRadioButton(String, Icon) default radio button image. Specifying
JRadioButton(String, Icon, the boolean argument as true
boolean) initializes the radio button to be
JRadioButton() selected, subject to the approval of the
ButtonGroup object. If the boolean
argument is absent or false, then the
radio button is initially unselected.
www.educlash.com
36
JLabel lbllang,lblstream;
JCheckBox cbeng,cbhin,cbmar;
JRadioButton rbart,rbcomm,rbsci;
ButtonGroup bg;
public StudentBioData02()
{
//Step 4- Create objects for the declared instances
lbllang=new JLabel("Languages Known");
lblstream=new JLabel("Stream");
cbeng=new JCheckBox("English",true);
cbhin=new JCheckBox("Hindi");
cbmar=new JCheckBox("Marathi");
rbart=new JRadioButton("Arts");
rbcomm=new JRadioButton("Commerce");
rbsci=new JRadioButton("Science");
bg=new ButtonGroup();
bg.add(rbart); bg.add(rbcomm); bg.add(rbsci);
//Step 5 – Add all the objects in the Content Pane with Layout
Container con=getContentPane();
con.setLayout(new FlowLayout());
con.add(lbllang);
con.add(cbeng); con.add(cbhin); con.add(cbmar);
con.add(lblstream);
con.add(rbart); con.add(rbcomm);con.add(rbsci);
}//constructor
//Step 6 – Event Handling. (Event handling code will come here)
public static void main(String args[])
{
//Step 7 – Create object of class in main method
StudentBioData02 sbd=new StudentBioData02();
sbd.setSize(150,200);
sbd.setVisible(true);
}//main
}//class
www.educlash.com
37
2.1.7 JComboBox
www.educlash.com
38
2.1.8 JList
www.educlash.com
39
www.educlash.com
40
con.add(lblyear);
con.add(jcb);
}//constructor
//Step 6 – Event Handling. (Event handling code will come here)
public static void main(String args[])
{
//Step 7 – Create object of class in main method
StudentBioData03 sbd=new StudentBioData03();
sbd.setSize(150,200);
sbd.setVisible(true);
}//main
}//class
2.1.9 Menus
JMenuBar
An implementation of a menu bar. You add JMenu objects to
the menu bar to construct a menu. When the user selects a JMenu
object, its associated JPopupMenu is displayed, allowing the user
to select one of the JMenuItems on it.
JMenu
An implementation of a menu -- a popup window containing
JMenuItems that is displayed when the user selects an item on the
JMenuBar. In addition to JMenuItems, a JMenu can also contain
JSeparators.
JMenuItem
An implementation of an item in a menu. A menu item is
essentially a button sitting in a list. When the user selects the
"button", the action associated with the menu item is performed. A
JMenuItem contained in a JPopupMenu performs exactly that
function.
www.educlash.com
41
the menu.
JMenuItem() Creates an ordinary menu item.
JMenuItem(String) The icon argument, if present,
JMenuItem(Icon) specifies the icon that the menu
JMenuItem(String, Icon) item should display. Similarly,
JMenuItem(String, int) the string argument specifies the
text that the menu item should
display. The integer argument
specifies the keyboard
mnemonic to use. You can
specify any of the relevant VK
constants defined in the
KeyEvent class. For example, to
specify the A key, use
KeyEvent.VK_A.
www.educlash.com
42
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class LineAnimation extends JFrame implements
ActionListener
{
Timer t;
JLabel lblText;
JMenuBar mb;
JMenu m1,m2;
JMenuItem mi1,mi2,mi3,mi4;
double theta=0.0;
int x,y,incr=-1;
//Graphics g;
Container con;
public LineAnimation()
{
super("Line Animation"); lblText=new
JLabel("Line Animation"); mb=new
JMenuBar();
m1=new JMenu("Motion");
m2=new JMenu("Direction");
mi1=new JMenuItem("Start");
mi2=new JMenuItem("Stop");
mi3=new JMenuItem("Clock-wise");
mi4=new JMenuItem("Anti-Clock-wise");
t=new Timer(100,this);
mi1.addActionListener(this);
mi2.addActionListener(this);
mi3.addActionListener(this);
mi4.addActionListener(this);
con=getContentPane();
con.setLayout(new FlowLayout());
con.add(lblText);
www.educlash.com
43
m1.add(mi1); m1.add(mi2);
m2.add(mi3); m2.add(mi4);
mb.add(m1); mb.add(m2);
setJMenuBar(mb);
//g=getGraphics();
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==t)
repaint();
if(ae.getSource()==mi1)
t.start();
if(ae.getSource()==mi2)
t.stop();
if(ae.getSource()==mi3)
incr=1;
if(ae.getSource()==mi4)
incr=-1;
}
public void paint(Graphics g)
{
g.clearRect(0,0,300,300);
x=(int)(100*Math.cos(theta*Math.PI/180));
y=(int)(100*Math.sin(theta*Math.PI/180));
g.drawLine(150+x,150+y,150-x,150-y);
theta+=incr;
}
public static void main(String args[])
{
LineAnimation la=new LineAnimation();
la.setVisible(true); la.setSize(300,300);
}//main
}//class
www.educlash.com
44
2.1.10 JTable
Methods
www.educlash.com
45
www.educlash.com
46
Object rowdata[][]={
{"2005","SSC","First"},
{"2007","HSC","Second"},
{"2011","BSc","Distinction"}
};
tbldata=new JTable(rowdata,header);
jsp=new JScrollPane(tbldata);
//Step 5 – Add all the objects in the Content Pane with Layout
Container con=getContentPane();
con.setLayout(new FlowLayout());
con.add(lbldata);
con.add(jsp);
}//constructor
//Step 6 – Event Handling. (Event handling code will come here)
public static void main(String args[])
{
//Step 7 – Create object of class in main method
StudentBioData04 sbd=new StudentBioData04();
sbd.setSize(150,200);
sbd.setVisible(true);
}//main
}//class
Note: If you combine all the four student bio-data program, you would end
up with the final program with all the components included. Just remove
the common code from all the files.
2.1.11 JTree
www.educlash.com
47
Methods of MutuableTreeNode
Methods of DefaultMutableTreeNode
www.educlash.com
48
Create the object of the tree with the top most node as an
argument.
Use the add method to create the heirarchy.
Create an object of JScrollpane and add the JTree to it. Add the
scroll pane to the content pane.
Event Handling
The JTree generates a TreeExpansionEvent which is in the
package javax.swing.event. The getPath() of this class returns a
Tree Path object that describes the path to the changed node. The
addTreeExpansionListener and removeTreeExpansionListener
methods allows listeners to register and unregister for the
notifications. The TreeExpansionListener interface provides two
methods:
DefaultMutableTreeNode top=new
DefaultMutableTreeNode("Option");
DefaultMutableTreeNode stream=new
DefaultMutableTreeNode("Stream");
www.educlash.com
49
DefaultMutableTreeNode arts=new
DefaultMutableTreeNode("Arts");
DefaultMutableTreeNode science=new
DefaultMutableTreeNode("Science");
DefaultMutableTreeNode comm=new
DefaultMutableTreeNode("Commerce");
DefaultMutableTreeNode year=new
DefaultMutableTreeNode("Year");
DefaultMutableTreeNode fy=new
DefaultMutableTreeNode("FY");
DefaultMutableTreeNode sy=new
DefaultMutableTreeNode("SY");
DefaultMutableTreeNode ty=new
DefaultMutableTreeNode("TY");
top.add(stream);
stream.add(arts); stream.add(comm); stream.add(science);
top.add(year);
year.add(fy); year.add(sy); year.add(ty);
tree=new JTree(top);
JScrollPane jsp=new JScrollPane(
tree,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
con.add(jsp,BorderLayout.CENTER);
txt1=new JTextField("",20);
con.add(txt1,BorderLayout.SOUTH);
tree.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent me)
{
doMouseClicked(me);
}
});
www.educlash.com
50
}// init()
2.1.12 JToolBar
By default, the user can drag the tool bar to another edge of
its container or out into a window of its own. The next figure shows
how the application looks after the user has dragged the tool bar to
the right edge of its container.
www.educlash.com
Thank You
www.educlash.com
Advanced Java
Part-2
www.educlash.com
51
For the drag behavior to work correctly, the tool bar must be
in a container that uses the BorderLayout layout manager. The
component that the tool bar affects is generally in the center of the
container. The tool bar must be the only other component in the
container, and it must not be in the center.
Method or Purpose
Constructor
JToolBar() Creates a tool bar. The optional int
JToolBar(int) parameter lets you specify the orientation;
JToolBar(String) the default is HORIZONTAL. The optional
JToolBar(String, int) String parameter allows you to specify the
title of the tool bar's window if it is dragged
outside of its container.
www.educlash.com
52
public ToolBarDemo()
{
super("Tool bar Demo");
toolBar = new JToolBar("Still draggable");
toolBar.add(cmdPrev);
toolBar.add(cmdUp);
toolBar.add(cmdNext);
cmdPrev.addActionListener(this);
cmdUp.addActionListener(this);
cmdNext.addActionListener(this);
Container con=getContentPane();
con.setLayout(new BorderLayout());
con.add(toolBar, BorderLayout.NORTH);
con.add(scrollPane, BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
www.educlash.com
53
2.1.13 JColorChooser
www.educlash.com
54
Method Purpose
void setColor(Color) void Set or get the currently selected color.
setColor(int, int, int) void The three integer version of the setColor
setColor(int) method interprets the three integers
Color getColor() together as an RGB color. The single
integer version of the setColor method
divides the integer into four 8-bit bytes
and interprets the integer as an RGB
color as follows:
www.educlash.com
55
2.1.14 JFileChooser
Method Purpose
void setSelectedFile(File) Sets or obtains the currently
File getSelectedFile() selected file or (if directory
selection has been enabled)
directory.
www.educlash.com
56
Swing text components display text and optionally allow the user to
edit the text. Programs need text components for tasks ranging
from the straightforward (enter a word and press Enter) to the
complex (display and edit styled text with embedded images in an
Asian language).
The following table tells you more about what you can do with each
kind of text component.
www.educlash.com
57
Text Also known simply as text fields, text JTextField and its
Controls controls can display only one line of sub classes
editable text. Like buttons, they JPassword Field
generate action events. Use them to and
get a small amount of textual JFormattedTextFi
information from the user and perform eld
an action after the text entry is
complete.
www.educlash.com
58
www.educlash.com
59
Method Summary
boolean isEnabled()
Returns the enabled state of the Action.
void removePropertyChangeListener(PropertyChangeListener
listener)
Removes a PropertyChange listener.
void setEnabled(boolean b)
Sets the enabled state of the Action.
www.educlash.com
60
Many of the features that are new in the Java Print Service,
such as printer discovery and specification of printing attributes, are
also very important to users of the Java 2D printing API. To make
these features available to users of Java 2D printing, the
java.awt.print package has been updated for version 1.4 of the
JavaTM 2 SE to allow access to the JavaTM Print Service from the
Java 2D printing API.
The Java Print Service (JPS) is a new Java Print API that is
designed to support printing on all Java platforms, including
platforms requiring a small footprint, but also supports the current
Java 2 Print API. This unified Java Print API includes extensible
print attributes based on the standard attributes specified in the
Internet Printing Protocol (IPP) 1.1 from the IETF Specification,
RFC 2911. With the attributes, client and server applications can
discover and select printers that have the capabilities specified by
the attributes. In addition to the included StreamPrintService, which
allows applications to transcode print data to different formats, a
third party can dynamically install their own print services through
the Service Provider Interface.
www.educlash.com
61
2.5 SUMMARY
www.educlash.com
62
www.educlash.com
63
www.educlash.com
64
Unit Structure:
1. Objectives
2. Introduction
3. Load the JDBC Driver
4. Define the Connection URL
5. Establish the Connection
6. Create a Statement Object
7. Execute a Query or Update
8. Process the Results
9. Close the Connection
10. Summary
11. Unit end exercise
12. Further Reading
1. OBJECTIVES
2. INTRODUCTION
www.educlash.com
65
JDBC lets you change database hosts, ports, and even database
vendors with minimal changes to your code.
www.educlash.com
66
www.educlash.com
67
Once you have loaded the JDBC driver, you must specify
the location of the database server. URLs referring to databases
use the jdbc: protocol and embed the server host, port, and
database name (or reference) within the URL. The exact format is
defined in the documentation that comes with the particular driver,
but here are a few representative examples.
String host = "dbhost.yourcompany.com";
String dbName = "someName";
int port = 1234;
String oracleURL = "jdbc:oracle:thin:@" + host +":" + port + ":" +
dbName;
String sybaseURL = "jdbc:sybase:Tds:" + host +":" + port + ":" +
"?SERVICENAME=" + dbName;
String msAccessURL = "jdbc:odbc:" + dbName;
www.educlash.com
68
www.educlash.com
69
Here is an example that prints the values of the first two columns
and the first name and last name, for all rows of a ResultSet.
while(resultSet.next())
{
System.out.println( resultSet.getString(1) + " " +
www.educlash.com
70
www.educlash.com
71
import java.sql.*;
www.educlash.com
72
{
public static void main(String args[])
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}
catch(Exception e){
System.out.println("Error"+e.getMessage());}
try
{
Connection con =
DriverManager.getConnection("jdbc:odbc:myDSN");
Statement st = con.createStatement();
st.executeUpdate(str);
System.out.println("Table Created");
System.out.println("Values Inserted");
}
catch(Exception
e){System.out.println("Error"+e.getMessage());}
}
}
www.educlash.com
73
Note: To run the program we need to create a DSN. Here are the
steps to create.
1) Click on Start Settings Control Panel Administrative
Tools
2) Click on Data Sources (ODBC) which opens a dialog box.
Click Add button.
3) Select the driver for your database and click on Finish
button.
4) Give name myDSN and select your database which was
already created.
import java.sql.*;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con =
DriverManager.getConnection("jdbc:odb
c: myDSN ");
Statement st = con.createStatement();
www.educlash.com
74
}
}
}
import java.sql.*;
class FetchData
{
public static void main(String args[])
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection
("jdbc:odbc: myDSN");
System.out.println("Connecting to database....");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery
("select * from dept order by deptno asc");
ResultSetMetaData rsmd = rs.getMetaData();
System.out.println("Displaying Values....");
for(int i=1;i<=rsmd.getColumnCount();i++)
System.out.print(rsmd.getColumnName(i)+"\t");
System.out.println("\n");
con.commit();
while(rs.next()) {
System.out.println(rs.getInt(1)+
"\t"+rs.getString(2)+"\t"+rs.getString(3));
}
st.close();
}
catch(Exception a){
System.out.println("ERROR"+a.getMessage());
}
}
}
www.educlash.com
75
3.9 SUMMARY
Load the JDBC driver - To load a driver, you specify the class
name of the database driver
Define the connection URL - In JDBC, a connection URL
specifies the server host, port, and database name with which to
establish a connection.
Establish the connection - With the connection URL, username,
and password, a network connection to the database can be
established.
Create a Statement object - Creating a Statement object
enables you to send queries and commands to the database.
Execute a query or update - Given a Statement object, you can
send SQL statements to the database
Process the results - When a database query is executed, a
ResultSet is returned.
Close the connection - When you are finished performing
queries and processing results, you should close the
connection, releasing resources to the database.
www.educlash.com
76
www.educlash.com
77
ADVANCE JDBC
Unit Structure:
1. Objectives
2. The JDBC Exception classes
3. Prepared Statements
4. Joins
5. Transactions
6. Stored Procedures
7. Summary
8. Unit end exercise
9. Further Reading
1. OBJECTIVES
class java.lang.Throwable
o class java.lang.Exception
class java.sql.SQLException
class java.sql.BatchUpdateException
class java.sql.SQLWarning
o class java.sql.DataTruncation
1. SQLException
www.educlash.com
78
2. BatchUpdateException
3. SQLWarning
www.educlash.com
79
4.1.4 DataTruncation
www.educlash.com
80
question mark is a Java String, you call the method setString, and
so on. In general, there is a setXXX method for each primitive type
declared in the Java programming language.
updateEmp.setInt(1, 7500);
updateEmp.setInt(2,1030);
updateEmp.executeUpdate():
4.3 JOINS
The following code selects the whole table and lets us see what the
table SUPPLIERS looks like:
ResultSet rs = stmt.executeQuery("select * from SUPPLIERS");
The result set will look similar to this:
SUP_ID SUP_NAME STREET CITY STATE ZIP
101 Reliance 99 Market Street New Delhi Delhi 95199
49 Tata 1 Party Place Mumbai Mah 95460
150 Sahara 100 Coffee Lane Kolkata WB 93966
www.educlash.com
81
ResultSet rs = stmt.executeQuery(query);
System.out.println("Coffees bought from Reliance.: ");
while (rs.next()) {
String coffeeName = rs.getString("COF_NAME");
System.out.println(" " + coffeeName);
}
4.4 TRANSACTIONS
There are times when you do not want one statement to take
effect unless another one completes. For example, when the
proprietor of The Coffee Break updates the amount of coffee sold
each week, he will also want to update the total amount sold to
date. However, he will not want to update one without updating the
other; otherwise, the data will be inconsistent. The way to be sure
that either both actions occur or neither action occurs is to use a
transaction. A transaction is a set of one or more statements that
are executed together as a unit, so either all of the statements are
executed, or none of the statements is executed.
www.educlash.com
82
Committing a Transaction
Once auto-commit mode is disabled, no SQL statements are
committed until you call the method commit explicitly. All
statements executed after the previous call to the
method commit are included in the current transaction and
committed together as a unit.
www.educlash.com
83
www.educlash.com
84
1. TYPE_FORWARD_ONLY
● The result set is nonscrollable; its cursor moves forward
only, from top to bottom.
● The view of the data in the result set depends on whether
the DBMS materializes results incrementally.
2. TYPE_SCROLL_INSENSITIVE
● The result set is scrollable: Its cursor can move forward or
backward and can be moved to a particular row or to a row
whose position is relative to its current position.
● The result set generally does not show changes to the
underlying database that are made while it is open. The
membership, order, and column values of rows are typically
fixed when the result set is created.
3. TYPE_SCROLL_SENSITIVE
● The result set is scrollable; its cursor can move forward or
backward and can be moved to a particular row or to a row
whose position is relative to its current position.
● The result set is sensitive to changes made while it is open.
If the underlying column values are modified, the new values
are visible, thus providing a dynamic view of the underlying
data. The membership and ordering of rows in the result set
may be fixed or not, depending on the implementation.
Concurrency Types
A result set may have different update capabilities. As with
scrollability, making a ResultSet object updatable increases
overhead and should be done only when necessary. That said, it is
often more convenient to make updates programmatically, and that
can only be done if a result set is made updatable. The JDBC 2.0
core API offers two update capabilities, specified by the following
constants in the ResultSet interface:
1. CONCUR_READ_ONLY
www.educlash.com
85
2. CONCUR_UPDATABLE
● Indicates a result set that can be updated programmatically
● Reduces the level on concurrency. Updatable results sets
may use write-only locks so that only one user at a time has
access to a data item. This eliminates the possibility that two
or more users might change the same data, thus ensuring
database consistency. However, the price for this
consistency is a reduced level of concurrency.
www.educlash.com
86
Releasing a Savepoint
The method Connection.rollback() release Savepoint takes
a Savepoint object as a parameter and removes it from the current
transaction. Once a savepoint has been released, attempting to
www.educlash.com
87
www.educlash.com
88
The following code puts the SQL statement into a string and
assigns it to the variable createProcedure, which we will use later:
String createProcedure = "create procedure SHOW_SUPPLIERS "
+ "as " + "select SUPPLIERS.SUP_NAME, COFFEES.COF_NAME
" + "from SUPPLIERS, COFFEES " + "where SUPPLIERS.SUP_ID
= COFFEES.SUP_ID " + "order by SUP_NAME";
CallableStatement cs = con.prepareCall
("{call SHOW_SUPPLIERS}");
ResultSet rs = cs.executeQuery();
The ResultSet rs will be similar to the following:
SUP_NAME COF_NAME
---------------- -----------------------
Reliance Colombian
Reliance Colombian_Decaf
Tata French_Roast
Tata French_Roast_Decaf
Sahara Espresso
www.educlash.com
89
Update would have been the one to use. It is sometimes the case,
however, that a stored procedure contains more than one SQL
statement, in which case it will produce more than one result set,
more than one update count, or some combination of result sets
and update counts. In this case, where there are multiple results,
the method execute should be used to execute the Callable
Statement.
Statement st=con.createStatement();
BufferedReader br=new BufferedReader((
new InputStreamReader(System.in)));
System.out.println("Enter The Query");
str=br.readLine();
ResultSet rs=st.executeQuery(str);
ResultSetMetaData md=rs.getMetaData();
int num=md.getColumnCount();
www.educlash.com
90
System.out.print("\n");
for(i=1;i<=num;i++)
System.out.print(md.getColumnName(i)+"\t\t");
System.out.println("");
while(rs.next())
{
for(i=1;i<=num;i++)
System.out.print(rs.getString(i)+"\t\t");
System.out.print("\n");
}
}
catch(Exception e)
{
System.out.println("Error1:"+e.getMessage());
}
}
}
public FriendDatabase()
{
lblHead=new JLabel("Information");
lblName=new JLabel("Friend Name");
www.educlash.com
91
lblDob=new JLabel("DOB");
lblDetails=new JLabel("Address");
lblPhno=new JLabel("Phno");
txtName=new JTextField("");
txtDob=new JTextField("");
txtDetails=new JTextArea(2,2);
int v=ScrollPaneConstants.
VERTICAL_SCROLLBAR_AS_NEEDED;
int h=ScrollPaneConstants.
HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane jsp=new JScrollPane(txtDetails,v,h);
txtPhno=new JTextField("");
cmdAdd=new JButton("Add");
cmdAdd.addActionListener(this);
cmdShowAll=new JButton("Show All");
cmdShowAll.addActionListener(this);
cmdExit=new JButton("Exit");
cmdExit.addActionListener(this);
con.setLayout(new GridBagLayout());
gbc.fill=GridBagConstraints.BOTH;
gbc.weightx=1.0;
gbc.insets=new Insets(20,20,20,20);
gbc.gridx=1;gbc.gridy=0;
con.add(lblHead,gbc);
gbc.gridx=0;gbc.gridy=1;
con.add(lblName,gbc);
gbc.gridx=1;gbc.gridy=1;
con.add(txtName,gbc);
gbc.gridx=0;gbc.gridy=2;
con.add(lblDob,gbc);
gbc.gridx=1;gbc.gridy=2;
con.add(txtDob,gbc);
www.educlash.com
92
gbc.gridx=0;gbc.gridy=3;
con.add(lblDetails,gbc);
gbc.gridx=1;gbc.gridy=3;
con.add(jsp,gbc);
gbc.gridx=0;gbc.gridy=4;
con.add(lblPhno,gbc);
gbc.gridx=1;gbc.gridy=4;
con.add(txtPhno,gbc);
gbc.fill=GridBagConstraints.NONE;
gbc.gridx=0;gbc.gridy=5;
con.add(cmdAdd,gbc);
gbc.gridx=1;gbc.gridy=5;
con.add(cmdShowAll,gbc);
gbc.gridx=2;gbc.gridy=5;
con.add(cmdExit,gbc);
}
public void actionPerformed(ActionEvent ae)
{
Object obj=ae.getSource();
if(obj==cmdAdd)
{
Connection con;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=
DriverManager.getConnection("jdbc:odbc:sidd");
String query="insert into
FriendDatabase values(?,?,?,?)";
PreparedStatement ps;
ps=con.prepareStatement(query);
ps.setString(1,txtName.getText());
ps.setDate(2,Date.valueOf(txtDob.getText()));
ps.setString(3,txtDetails.getText());
String str=txtPhno.getText();
www.educlash.com
93
int m=Integer.parseInt(str);
ps.setInt(4,m);
ps.executeUpdate();
JOptionPane.showMessageDialog(this,
"Record Entered", "FriendsDatabase",
JOptionPane.ERROR_MESSAGE);
txtName.setText("");
txtDob.setText("");
txtDetails.setText("");
txtPhno.setText("");
ps.close();
con.close();
}
catch(Exception e)
{
System.out.println("Error:"+e.getMessage());
}
}
if(obj==cmdExit)
{
System.exit(0);
}
if(obj==cmdShowAll)
{
ShowAll as=new ShowAll(this,true);
}
}
www.educlash.com
94
int i,j;
JScrollPane p;
JTable t;
Connection con;
public ShowAll(JFrame f,boolean m)
{
super(f,m);
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.
getConnection("jdbc:odbc:sidd");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery
("Select * from FriendDatabase");
i=0;
while(rs.next())
{
for(j=0;j<=3;j++)
{
Object obj=rs.getObject(j+1);
rows[i][j]=obj.toString();
System.out.print(""+obj.toString()+"\t");
}
i++;
}
t=new JTable(rows,cols);
int v1=ScrollPaneConstants.
VERTICAL_SCROLLBAR_ALWAYS;
int h1=ScrollPaneConstants.
HORIZONTAL_SCROLLBAR_ALWAYS;
p=new JScrollPane(t,v1,h1);
Container con1=getContentPane();
con1.add(p,BorderLayout.CENTER);
setSize(300,300);
setVisible(true);
}
catch(Exception e)
{
www.educlash.com
95
System.out.println("Error2:"+e.getMessage());
}
}
}
4.6 SUMMARY
www.educlash.com
96
Unit Structure:
1. Objectives
2. Introduction
3. Life Cycle of a Thread
4. Thread Priorities
5. Creating a Thread
6. Using Multithreading
7. Thread Deadlock
8. Summary
9. Unit end exercise
10. Further Reading
5.0 OBJECTIVES
5.1. INTRODUCTION
www.educlash.com
97
New: A new thread begins its life cycle in the new state. It
remains in this state until the program starts the thread. It is also
referred to as a born thread.
Runnable: After a newly born thread is started, the thread
becomes runnable. A thread in this state is considered to be
executing its task.
Waiting: Sometimes a thread transitions to the waiting state
while the thread waits for another thread to perform a task.A
thread transitions back to the runnable state only when another
thread signals the waiting thread to continue executing.
Timed waiting: A runnable thread can enter the timed waiting
state for a specified interval of time. A thread in this state
transition back to the runnable state when that time interval
expires or when the event it is waiting for occurs.
Terminated: A runnable thread enters the terminated state
when it completes its task or otherwise terminates.
www.educlash.com
98
2. THREAD PRIORITIES:
3. CREATING A THREAD:
You will define the code that constitutes the new thread
inside run() method. It is important to understand that run() can call
other methods, use other classes, and declare variables, just like
the main thread can.
void start( );
www.educlash.com
99
Example:
public class RunnableThread implements Runnable
{
private int countDown = 5;
public String toString()
{
return "#" + Thread.currentThread().getName()
+": " + countDown;
}
public void run()
{
while(true)
{
System.out.println(this);
if(--countDown == 0) return;
}
}
public static void main(String[] args)
{
for(int i = 1; i <= 5; i++)
new Thread(new RunnableThread(), "" +
i).start();
}
}
5.3.2 Create Thread by Extending Thread:
Example:
Here is the preceding program rewritten to extend Thread:
public class SimpleThread extends Thread
{
private int countDown = 5;
private static int threadCount = 0;
public SimpleThread()
{
www.educlash.com
100
SN Methods
www.educlash.com
Thank You
www.educlash.com
Advanced Java
Part-3
www.educlash.com
101
SN Methods
www.educlash.com
102
4. USING MULTITHREADING:
1. Thread Synchronization
synchronized(object) {
// statements to be synchronized
}
2. Interthread Communication
www.educlash.com
103
Example:
class A
{
synchronized void foo(B b)
{
String name = Thread.currentThread().getName();
www.educlash.com
104
www.educlash.com
105
{
Thread.currentThread().setName("MainThread");
Thread t = new Thread(this, "RacingThread");
t.start();
a.foo(b); // get lock on a in this thread.
System.out.println("Back in main thread");
}
public void run()
{
b.bar(a); // get lock on b in other thread.
System.out.println("Back in other thread");
}
public static void main(String args[])
{
new Deadlock();
}
}
Ordering Locks:
5.7 SUMMARY
www.educlash.com
106
www.educlash.com
107
NETWORKING BASICS
Unit Structure:
1. Objectives
2. Introduction to Networking
3. Working with URL’s
4. URLConnection
5. TCP/IP Sockets
6. UDP Sockets
7. Summary
8. Unit end exercise
9. Further Reading
www.educlash.com
108
Constructor Summary
URL(String spec)
Creates a URL object from the String representation.
URL(String protocol, String host, int port, String file)
Creates a URL object from the specified protocol, host, port
number, and file.
URL(String protocol, String host, String file)
Creates a URL from the specified protocol name, host name,
and file name.
Method Summary
www.educlash.com
109
6.3 URLCONNECTION:
Constructor Summary
URLConnection(URL url)
Constructs a URL connection to the specified URL.
Method Summary
www.educlash.com
110
import java.net.URL;
import java.net.URLConnection;
import java.net.HttpURLConnection;
import java.util.Date;
class URLDemo
{
long d;
public static void main(String args[])throws Exception
{
URL u=new URL("http://localhost:8080/index.html");
URLConnection uc=u.openConnection();
HttpURLConnection huc=(HttpURLConnection)uc;
www.educlash.com
111
www.educlash.com
112
class Download
{
public static void main(String args[])throws Exception
{
int b;
char c;
if(args.length==0)
throw new Exception("Invalid Number of argument");
URL u=new URL(args[0]);
InputStream is=u.openStream();
OutputStream os;
if(args.length==1)
{
while ((b=is.read())!=-1)
System.out.print((char)b);
}
else
{ File f2=new File(args[1]);
os=new FileOutputStream(f2);
if(f2.exists()==true)
{
System.out.println("This file exists");
System.exit(0);
}
else
{
while ((b=is.read())!=-1)
os.write(b);
}
www.educlash.com
113
}
}//main
}//class
4. TCP/IP SOCKETS:
Advantages:
Easy to use.
Used for 2 way communication.
No parts of the transmission are lost.
Disadvantages:
It requires setup time and shutdown time.
Delivery is slower than datagram sockets.
There are two types of TCP/IP sockets. One is used for Servers
and other is used for clients.
Socket Class:
Constructor Summary
www.educlash.com
114
Method Summary
ServerSocket Class:
www.educlash.com
115
Constructor Summary
ServerSocket(int port)
Creates a server socket, bound to the specified port.
Method Summary
Example: Write a simple server that reports the current time (in
textual form) to any client that connects. This server should
simply output the current time and close the connection,
without reading anything from the client. You need to choose a
port number that your service listens on.
import java.net.*;
import java.io.*;
import java.util.*;
class TimeServer
{
public static void main(String args[])throws Exception
{
ServerSocket s=new ServerSocket(1234);
Socket c=s.accept();
Calendar calendar = new GregorianCalendar();
www.educlash.com
116
import java.net.*;
import java.io.*;
class TimeClient
{
public static void main(String args[])throws Exception
{
Socket c=new Socket(InetAddress.getLocalHost(),1234);
BufferedReader br=new BufferedReader(new
InputStreamReader(c.getInputStream()));
String userInput;
while((userInput=br.readLine())!=null)
{
System.out.println(userInput);
}
c.close();
}
}
5. UDP SOCKETS:
Advantages:
Does not require setup time and shutdown time.
Delivery is faster than TCP/IP sockets.
www.educlash.com
117
Disadvantages:
Datagram sockets cannot be used for two way
communication.
Parts of the transmission are lost.
Constructor Summary
DatagramSocket()
Constructs a datagram socket and binds it to any available port on
the local host machine.
DatagramSocket(int port)
Constructs a datagram socket and binds it to the specified port on
the local host machine.
Method Summary
www.educlash.com
118
DatagramPacket:
DatagramPackets are use to implement a connection less
packet delivery service. Each message is routed from one machine
to another based on the information contained within that packet.
Constructor Summary
Method Summary
www.educlash.com
119
www.educlash.com
120
ds.send(new DatagramPacket
(buffer,str.length(),ia,cp));
if(str.length()==0)
{
ds.close();
break;
}
}
}//main
}//class
import java.net.*;
import java.io.*;
class DataGramClient
{
public static DatagramSocket ds;
public static byte buffer[]=new byte[1024];
public static int cp=1510,sp=1511;
public static void main(String args[])throws Exception
{
ds=new DatagramSocket(cp);
System.out.print("Client is waiting for
server to send data....");
while(true)
{
DatagramPacket dp=new
DatagramPacket(buffer,buffer.length);
ds.receive(dp);
String str=new
String(dp.getData(),0,dp.getLength());
if(dp.getLength()==0)
break;
System.out.println(str);
}
}//main
}//class
www.educlash.com
121
6.6 SUMMARY
www.educlash.com
122
www.educlash.com
123
7
ADVANCE NETWORKING
Unit Structure:
1. Objectives
2. Programmatic Access to Network Parameters
3. What Is a Network Interface?
4. Retrieving Network Interfaces
5. Listing Network Interface Addresses
6. Network Interface Parameters
7. Summary
8. Unit end exercise
9. Further Reading
7.0 OBJECTIVES
www.educlash.com
124
www.educlash.com
125
available so that you can retrieve the interface details from the
system: getByInetAddress(), getByName(), and get
NetworkInterfaces(). The first two methods are used when you
already know the IP address or the name of the particular interface.
The third method, getNetworkInterfaces() returns the complete list
of interfaces on the machine.
import java.io.*;
import java.net.*;
import java.util.*;
import static java.lang.System.out;
www.educlash.com
126
www.educlash.com
127
Loopback? true
PointToPoint? false
Supports multicast? false
Virtual? false
Hardware address: null
MTU: 8232
7.6 SUMMARY
8. FURTHER READING
Ivan Bayross, Web Enabled Commercial Applications
Development Using Java 2, BPB Publications, Revised Edition,
2006
Joe Wigglesworth and Paula McMillan, Java Programming:
Advanced Topics, Thomson Course Technology (SPD), Third
Edition, 2004
Cay S. Horstmann, Gary Cornell, Core Java™ 2: Volume II–
Advanced Features Prentice Hall PTR, 2001
www.educlash.com
128
1. OBJECTIVES
www.educlash.com
129
1.Goals
A primary goal for the RMI designers was to allow
programmers to develop distributed Java programs with the same
syntax and semantics used for non-distributed programs. To do
this, they had to carefully map how Java classes and objects work
in a single Java Virtual Machine (JVM) to a new model of how
classes and objects would work in a distributed (multiple JVM)
computing environment.
www.educlash.com
130
www.educlash.com
131
www.educlash.com
132
server. The second class acts as a proxy for the remote service
and it runs on the client. This is shown in the following diagram.
www.educlash.com
133
In RMI's use of the Proxy pattern, the stub class plays the
role of the proxy, and the remote service implementation class
plays the role of the RealSubject.
www.educlash.com
134
3. Transport Layer
The Transport Layer makes the connection between JVMs.
All connections are stream-based network connections that use
TCP/IP.
www.educlash.com
135
www.educlash.com
136
rmi://<host_name>
[:<name_service_port>]
/<service_name>
where the host_name is a name recognized on the local area
network (LAN) or a DNS name on the Internet.
The name_service_port only needs to be specified only if the
naming service is running on a different port to the default 1099.
5. USING RMI
www.educlash.com
137
server to provide the class files. Assuming that the RMI system is
already designed, you take the following steps to build a system:
Write and compile Java code for interfaces
Write and compile Java code for implementation classes
Generate Stub and Skeleton class files from the
implementation classes
Write Java code for a remote service host program
Develop Java code for RMI client program
Install and run RMI system
Interfaces
The first step is to write and compile the Java code for the
service interface. The Calculator interface defines all of the remote
features offered by the service:
Implementation
Next, you write the implementation for the remote service. This is
the CalculatorImpl class:
www.educlash.com
138
}
public long sub(long a, long b) throws java.rmi.RemoteException {
return a - b;
}
public long mul(long a, long b) throws java.rmi.RemoteException {
return a * b;
}
public long div(long a, long b) throws java.rmi.RemoteException {
return a / b;
}
}
Again, copy this code into your directory and compile it. The
implementation class uses UnicastRemoteObject to link into the
RMI system. In the example the implementation class directly
extends UnicastRemoteObject. This is not a requirement. A class
that does not extend UnicastRemoteObject may use
its exportObject() method to be linked into RMI.
Try this in your directory. After you run rmic you should find the
file Calculator_Stub.class and, if you are running the Java 2
SDK, Calculator_Skel.class.
Options for the JDK 1.1 version of the RMI compiler, rmic, are:
Host Server
Remote RMI services must be hosted in a server process.
The class CalculatorServer is a very simple server that provides the
bare essentials for hosting.
import java.rmi.Naming;
public class CalculatorServer
{
public CalculatorServer() {
try {
www.educlash.com
139
Client
The source code for the client follows:
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.net.MalformedURLException;
import java.rmi.NotBoundException;
public class CalculatorClient
{
public static void main(String[] args)
{
try {
Calculator c = (Calculator)
Naming.lookup("rmi://localhost/CalculatorService");
System.out.println( c.sub(4, 3) );
System.out.println( c.add(4, 5) );
System.out.println( c.mul(3, 6) );
System.out.println( c.div(9, 3) );
}
catch (Exception e) {
System.out.println("Trouble: " + e);
}
}//main
}//class
www.educlash.com
140
directory that contains the classes you have written. From there,
enter the following:
rmiregistry
If all goes well, the registry will start running and you can switch to
the next console.
In the second console start the server hosting
the CalculatorService, and enter the following:
>java CalculatorServer
It will start, load the implementation into memory and wait for a
client connection.
In the last console, start the client program.
>java CalculatorClient
If all goes well you will see the following output:
1
9
18
3
8.6 SUMMARY
www.educlash.com
141
www.educlash.com
142
SERVLET BASICS
Unit Structure:
1. Objectives
2. Introduction to Servlet.
3. The Servlet Life Cycle
4. Reading Form Data from Servlets
5. Response Headers
6. Request Headers
7. Summary
8. Unit end exercise
9. Further Reading
1. OBJECTIVES
2. INTRODUCTION TO SERVLET
Read the explicit data sent by the client - The end user
normally enters the data in an HTML form on a Web page.
www.educlash.com
143
www.educlash.com
144
Efficient
With traditional CGI, a new process is started for each HTTP
request. If the CGI program itself is relatively short, the overhead of
starting the process can dominate the execution time. With servlets,
the Java virtual machine stays running and handles each request
with a lightweight Java thread, not a heavyweight operating system
process. Similarly, in traditional CGI, if there are N requests to the
same CGI program, the code for the CGI program is loaded into
memory N times. With servlets, however, there would be N threads,
but only a single copy of the servlet class would be loaded. This
approach reduces server memory requirements and saves time by
instantiating fewer objects. Finally, when a CGI program finishes
handling a request, the program terminates. This approach makes
www.educlash.com
145
Convenient
Servlets have an extensive infrastructure for automatically
parsing and decoding HTML form data, reading and setting HTTP
headers, handling cookies, tracking sessions, and many other such
high-level utilities. In CGI, you have to do much of this yourself.
Besides, if you already know the Java programming language, why
learn Perl too? You’re already convinced that Java technology
makes for more reliable and reusable code than does Visual Basic,
VBScript, or C++. Why go back to those languages for server-side
programming?
Powerful
Servlets support several capabilities that are difficult or
impossible to accomplish with regular CGI. Servlets can talk directly
to the Web server, whereas regular CGI programs cannot, at least
not without using a server-specific API. Communicating with the
Web server makes it easier to translate relative URLs into concrete
path names, for instance. Multiple servlets can also share data,
making it easy to implement database connection pooling and
similar resource-sharing optimizations. Servlets can also maintain
information from request to request, simplifying techniques like
session tracking and caching of previous computations.
Portable
Servlets are written in the Java programming language and
follow a standard API. Servlets are supported directly or by a plugin
on virtually every major Web server. Consequently, servlets written
for, say, Macromedia JRun can run virtually unchanged on Apache
Tomcat, Microsoft Internet Information Server (with a separate
plugin), IBM WebSphere, iPlanet Enterprise Server, Oracle9i AS,
or StarNine WebStar. They are part of the Java 2 Platform,
Enterprise Edition (J2EE), so industry support for servlets is
becoming even more pervasive.
Inexpensive
A number of free or very inexpensive Web servers are good
for development use or deployment of low- or medium-volume Web
sites. Thus, with servlets and JSP you can start with a free or
inexpensive server and migrate to more expensive servers with
high-performance capabilities or advanced administration utilities
only after your project meets initial success. This is in contrast to
many of the other CGI alternatives, which require a significant initial
investment for the purchase of a proprietary package. Price and
portability are somewhat connected.
www.educlash.com
146
Secure
www.educlash.com
147
www.educlash.com
148
lists of cookie values that indicate special access, you should also
proactively write the data to disk periodically.
www.educlash.com
149
www.educlash.com
150
//Student.java file
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Student extends HttpServlet
{
public void doGet(HttpServletRequest req,
HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");
String name=(String)req.getParameter("txtName");
String age=(String)req.getParameter("txtAge");
PrintWriter out=res.getWriter();
out.println(“Name = ”+name);
out.println(“Age= ”+age);
}
}//class
www.educlash.com
Thank You
www.educlash.com
Advanced Java
Part-4
www.educlash.com
151
www.educlash.com
152
throws IOException,ServletException
{
try
{
res.setContentType("text/html");
Enumeration e=req.getParameterNames();
PrintWriter out=res.getWriter();
while(e.hasMoreElements())
{
String name=(String)e.nextElement();
out.println(name);
String[] value=req.getParameterValues(name);
for(int i=0;i<value.length;i++)
{
out.print(value[i]+"\t");
}
}
}//try
catch(Exception e)
{
System.out.println("ERROR "+e.getMessage());
}
}
}
www.educlash.com
153
{
try
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.println("<Html><Head><Title>Department Info
</Title></Head>");
out.println("<Form name=frm method="+"POST"+"
action=DeptEntry.class>");
out.println("DepartmentNo: <input type=text
name=txtNo><br>");
out.println("DepartmentName: <input type=text
name=txtName><br>");
out.println("Location: <input type=text
name=txtLoc><br>");
out.println("<input type=submit name=Submit>");
out.println("<input type=reset name=Reset>");
out.println("</Form></Html>");
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
}
//Part II
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class DeptEntry extends HttpServlet
{
public void doPost(HttpServletRequest req,
HttpServletResponse res)
throws IOException,ServletException
{
String a,b,c,d,e,f;
int i;
Connection con;
www.educlash.com
154
try
{
res.setContentType("text/html");
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:odbc:First”);
String Query="insert into dept Values(?,?,?)";
Statement st=con.createStatement();
PreparedStatement ps;
ps=con.prepareStatement(Query);
a=(String)req.getParameter("txtNo");
b=(String)req.getParameter("txtName");
c=(String)req.getParameter("txtLoc");
ps.setString(1,a);
ps.setString(2,b);
ps.setString(3,c);
ps.executeUpdate();
PrintWriter out=res.getWriter();
ResultSet rs=st.executeQuery("select * from dept");
ResultSetMetaData md=rs.getMetaData();
int num=md.getColumnCount();
out.println("<html><body><table border=1><tr>");
for(i=1;i<=num;i++)
{
out.print("<th>"+md.getColumnName(i)+"</th>");
}
out.println("</tr>");
while(rs.next())
{ d=rs.getString(1);
e=rs.getString(2);
f=rs.getString(3);
out.println("<tr><td>"); out.println(d);
out.println("</td><td>"); out.println(e);
out.println("</td><td>"); out.println(f);
out.println("</td></tr>");
}
out.println("</table>");
con.commit();
out.println("<a href=DeptForm.class>BACK</a>");
out.println("</body></html>");
www.educlash.com
155
}
catch (Exception ae)
{
System.out.println(ae.getMessage());
}
}
}
www.educlash.com
156
www.educlash.com
157
www.educlash.com
158
Following is a summary.
getCookies - The getCookies method returns the contents of the
Cookie header, parsed and stored in an array of Cookie objects.
getAuthType and getRemoteUser - The getAuthType and
getRemoteUser methods break the Authorization header into its
component pieces.
getContentLength - The getContentLength method returns the
value of the Content-Length header (as an int).
getContentType - The getContentType method returns the value
of the Content-Type header (as a String).
getDateHeader and getIntHeader - The getDateHeader and
getIntHeader methods read the specified headers and then
convert them to Date and int values, respectively.
getHeaderNames - Rather than looking up one particular
header, you can use the getHeaderNames method to get an
Enumeration of all header names received on this particular
request.
getHeaders - In most cases, each header name appears only
once in the request. Occasionally, however, a header can
appear multiple times, with each occurrence listing a separate
value. Accept-Language is one such example. You can use
getHeaders to obtain an Enumeration of the values of all
occurrences of the header.
www.educlash.com
159
www.educlash.com
160
request.getRequestURI() + "<BR>\n");
out.println("<B>Request Protocol: </B>" +
request.getProtocol() + "<BR>\n");
out.println("<TABLE BORDER=1 ALIGN=\"CENTER\">\n");
out.println("<TR BGCOLOR=\"#FFAD00\">\n");
out.println("<TH>Header Name<TH>Header Value");
9.6 SUMMARY
www.educlash.com
161
www.educlash.com
162
10
ADVANCE SERVLETS
Unit Structure:
10.0 Objectives
10.1 Status Codes
10.2 Filtering Requests and Responses
10.3 Cookies
10.4 HttpSession
10.5 Summary
10.6 Unit end exercise
10.7 Further Reading
1. OBJECTIVES
2. STATUS CODES
www.educlash.com
163
the PrintWriter or carefully check that the buffer hasn’t been flushed
and content actually sent to the browser.
www.educlash.com
164
300–399: Values in the 300s are used for files that have moved and
usually include a Location header indicating the new address.
import javax.servlet.*;
import javax.servlet.http.*;
public class WrongDestination extends HttpServlet
{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
String userAgent = request.getHeader("User-Agent");
if ((userAgent != null) &&(userAgent.indexOf("MSIE") != -1))
response.sendRedirect("http://home.netscape.com");
else
response.sendRedirect("http://www.microsoft.com");
}
}
www.educlash.com
165
Programming Filters
The filtering API is defined by the Filter, FilterChain, and
FilterConfig interfaces in the javax.servlet package. You define a
filter by implementing the Filter interface. The most important
method in this interface is doFilter, which is passed request,
response, and filter chain objects. This method can perform the
following actions:
Examine the request headers.
Customize the request object if the filter wishes to modify
request headers or data.
Customize the response object if the filter wishes to modify
response headers or data.
Invoke the next entity in the filter chain. If the current filter is the
last filter in the chain that ends with the target web component
or static resource, the next entity is the resource at the end of
the chain; otherwise, it is the next filter that was configured in
the WAR. The filter invokes the next entity by calling the doFilter
method on the chain object (passing in the request and
response it was called with, or the wrapped versions it may
have created). Alternatively, it can choose to block the request
by not making the call to invoke the next entity. In the latter
case, the filter is responsible for filling out the response.
Examine response headers after it has invoked the next filter in
the chain.
Throw an exception to indicate an error in processing.
www.educlash.com
166
10.3 COOKIES
Benefits of Cookies
There are four typical ways in which cookies can add value
to your site. We summarize these benefits below:
Identifying a user during an e-commerce session - This type of
short-term tracking is so important that another API is layered
on top of cookies for this purpose.
Remembering usernames and passwords - Cookies let a user
log in to a site automatically, providing a significant convenience
for users of unshared computers.
Customizing sites - Sites can use cookies to remember user
preferences.
Focusing advertising - Cookies let the site remember which
topics interest certain users and show advertisements relevant
to those interests.
To read the cookies that come back from the client, you should
perform the following two tasks, which are summarized below:
Call request.getCookies. This yields an array of Cookie objects.
www.educlash.com
167
Loop down the array, calling getName on each one until you
find the cookie of interest. You then typically call getValue and
use the value in some application-specific way.
//Part I
<html><body><center>
<form name=form1 method=get action=”AddCookieServlet”>
<B>Enter a Value</B>
<input type=text name=data>
<input type=submit>
</form></center></body></html>
www.educlash.com
168
//Part II
import javax.servlet.*;
import javax.servlet.http.*;
public class AddCookieServlet extends HttpServlet
{
public void doGet(
HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException
{
String data = req.getParametar();
Cookie c = new Cookie("My Cookie",data);
res.addCookie(c);
res.setCountentType("text/html");
PrintWriter out = res.getWriter();
out.println("My Cookie has been set to");
out.println(data);
}
}
//Part III
import javax.servlet.*;
import javax.servlet.http.*;
public class GetCookie extends HttpServlet
{
public void doGet(
HttpServletRequest req,HttpServletResponse res)
throws IOException, ServletException
{
Cookie c[] = req.getCookies();
res.setContentType("text/html");
PrintWriter out = res.getWriter();
for(int i = 0; i < c.length; i++)
{
String name = c[i].getName();
String value = c[i].getValue();
out.println(name +"\t"+ value);
}
}
}
www.educlash.com
169
Method Summary
www.educlash.com
170
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class SessionServlet extends HttpServlet
{
public void service(
HttpServletResponse res,HttpServletRequest req)
throws IOException,ServletException
{
try {
res.setContentType("Text/Html");
Integer hitCount;
PrintWriter out=res.getWriter();
HttpSession s=req.getSession(true);
if(s.isNew()){
out.println("<Html>");
out.println("<Form method="+"GET"+" action
=http://localhost:8080/servlet/SessionServlet>");
out.println("<b>Please select bgcolor</b>");
out.println("<input type=radio name=optColor
value=red>Red");
out.println("<input type=radio name=optColor
value=green>Green");
out.println("<input type=radio name=optColor
value=blue>Blue");
out.println("<input type=text name=txtName>");
out.println("<br><br>");
out.println("<input type=submit value=Submit>");
www.educlash.com
171
out.println("</form></Html>");
}//if
else{
String name=(String)req.getParameter("txtName");
String color=(String)req.getParameter("optColor");
if(name!=null && color!=null){
out.println("Name: "+name);
hitCount=new Integer(1);
out.println("<a
href=SessionServlet>SessionServlet");
s.setAttribute("txtName",name);
s.setAttribute("optColor",color);
s.setAttribute("Hit",hitCount);
}else{
hitCount=(Integer)s.getValue("Hit");
hitCount=new Integer(hitCount.intValue()+1);
s.putValue("Hit",hitCount);
out.println("<Html><body text=cyan bgcolor="
+s.getAttribute("optColor")+">");
out.println("You Have Been Selected"
+s.getAttribute("optColor")+"Color");
out.println("<br><br>Your Name Is"
+s.getAttribute("txtName"));
out.println("<br><br>Number Of Visits==>"
+hitCount);
out.println("<br><br>");
out.println("<a
href=SessionServlet>SessionServlet</a>");
out.println("</body></html>");
}
}
}//try
catch(Exception e){}
} }//class
www.educlash.com
172
10.5 SUMMARY
www.educlash.com
173
11
INTRODUCTION TO JSP
Unit Structure:
11.0 Objectives
11.1 Introduction to JSP
11.2 The Life Cycle of a JSP Page
11.3 JSP Syntax Basics
11.4 Unified Expression Language
11.5 Summary
11.6 Unit end exercise
11.7 Further Reading
1. OBJECTIVES
2. INTRODUCTION TO JSP
JSP Advantages
Separation of static from dynamic content: With servlets, the
logic for generation of the dynamic content is an intrinsic part of
the servlet itself, and is closely tied to the static presentation
templates responsible for the user interface. Thus, even minor
changes made to the UI typically result in the recompilation of
the servlet. This tight coupling of presentation and content
results in brittle, inflexible applications. However, with JSP, the
www.educlash.com
174
www.educlash.com
175
www.educlash.com
176
Once this class file is loaded within the servlet container, the
_jspService() method is responsible for replying to a client's
request. By default, the _jspService() method is dispatched on a
separate thread by the servlet container in processing concurrent
client requests, as shown below:
www.educlash.com
177
www.educlash.com
178
www.educlash.com
179
Register.jsp
<Html>
<Head>
<Title>Register</Title>
</Head>
<form method=get action="http://localhost:8080/StudentInfo.jsp">
<table border=1>
<tr><td>Name:</td><td> <input type=text name=txtName></td>
<tr><td>Age: </td><td><input type=text name=txtAge></td>
<tr><td>Tel Nos: </td><td><input type=text name=txtTelNo></td>
<tr><td><input type=submit></td><td> <input type=reset></td>
</table>
</form>
</html>
StudentInfo.jsp
<html>
<head>
<Title>Student Info</Title>
</Head>
<Body>
<table border=1>
<tr><td>Name</td><td><%=request.getParameter("txtName")
%></td></tr>
<tr><td>Age</td><td><%=request.getParameter("txtAge")
%></td></tr>
<tr><td>Tel No</td><td><%=request.getParameter("txtTelNo")
%></td></tr>
</table>
</body>
</html>
www.educlash.com
180
DeptForm.jsp
<html>
<Head><title>Department Form</title>
</head>
<body>
<form method=GET action="http://localhost:8080/Register1.jsp">
<table>
<tr><td>DepartmentNo: </td><td> <input type=text
name=txtNo></td></tr>
<tr><td>DepartmentName: </td><td><input type=text
name=txtName></td></tr>
<tr><td>Location:</td><td> <input type=text
name=txtLoc></td></tr>
</table>
<input type=submit name=Submit>
<input type=reset name=Reset>
</Form>
</body>
</Html>
Register1.jsp
<%@ page import="java.sql.*" %>
<%! String a,b,c,d,e,f,Query; %>
<%! Connection con;
Statement st;
PreparedStatement ps; %>
<%! int i,num; %>
<%!
public void jspInit()
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:ty289");
st=con.createStatement();
Query="insert into Dept values(?,?,?)";
www.educlash.com
181
ps=con.prepareStatement(Query);
}
catch(Exception e){System.out.println("Error: "+e.getMessage());}
}
%>
<%
a=(String)request.getParameter("txtNo");
b=(String)request.getParameter("txtName");
c=(String)request.getParameter("txtLoc");
ps.setInt(1,Integer.parseInt(a));
ps.setString(2,b);
ps.setString(3,c);
ps.executeUpdate();
con.commit();
ResultSet rs=st.executeQuery("select * from Dept");
%>
<html><body>
<table border=1>
<tr><th>Dept No </th><th>Dept Name</th><th>Location</th></tr>
<%
while(rs.next())
{
%>
<tr>
<% for(int j=0;j<=2;j++)
{
Object obj=rs.getObject(j+1);
%>
<td><%=obj.toString()%></td>
<%
}
}
%>
</tr>
</table>
<%!
public void jspDestroy()
{ try
{
ps.close();
www.educlash.com
182
st.close();
}
catch(Exception e){System.out.println("Error:
"+e.getMessage());}
}%>
</body>
</html>
Directives
JSP directives are messages for the JSP engine. They do
not directly produce any visible output, but tell the engine what to
do with the rest of the JSP page. JSP directives are always
enclosed within the <%@ ... %> tag. The two primary directives are
page and include.
Page Directive
Typically, the page directive is found at the top of almost all
of your JSP pages. There can be any number of page directives
within a JSP page, although the attribute/value pair must be unique.
Unrecognized attributes or values result in a translation error. For
example,
www.educlash.com
183
www.educlash.com
184
The web.xml file lets you specify application-wide error pages that
apply whenever certain exceptions or certain HTTP status codes
result.
• The errorPage attribute is for page-specific error pages
Declarations
JSP declarations let you define page-level variables to save
information or define supporting methods that the rest of a JSP
page may need. While it is easy to get led away and have a lot of
code within your JSP page, this move will eventually turn out to be
a maintenance nightmare. For that reason, and to improve
reusability, it is best that logic-intensive processing is encapsulated
as JavaBean components.
Declarations are found within the <%! ... %> tag. Always end
variable declarations with a semicolon, as any content must be
valid Java statements:
<%! int i=0; %>
www.educlash.com
185
Expressions
With expressions in JSP, the results of evaluating the
expression are converted to a string and directly included within the
output page. Typically expressions are used to display simple
values of variables or return values by invoking a bean's getter
methods. JSP expressions begin within <%= ... %> tags and do not
include semicolons:
<%= fooVariable %>
<%= fooBean.getName() %>
Scriptlets
JSP code fragments or scriptlets are embedded within <% ...
%> tags. This Java code is run when the request is serviced by the
JSP page. You can have just about any valid Java code within a
scriptlet, and is not limited to one line of source code. For example,
the following displays the string "Hello" within H1, H2, H3, and H4
tags, combining the use of expressions and scriptlets:
<% for (int i=1; i<=4; i++) { %>
<H<%=i%>>Hello</H<%=i%>>
<% } %>
Comments
Although you can always include HTML comments in JSP
pages, users can view these if they view the page's source. If you
don't want users to be able to see your comments, embed them
within the <%-- ... --%> tag:
<%-- comment for server side only --%>
A most useful feature of JSP comments is that they can be
used to selectively block out scriptlets or tags from compilation.
Thus, they can play a significant role during the debugging and
testing process.
Object Scopes
It is important to understand the scope or visibility of Java
objects within JSP pages that are processing a request. Objects
may be created implicitly using JSP directives, explicitly through
actions, or, in rare cases, directly using scripting code. The
instantiated objects can be associated with a scope attribute
defining where there is a reference to the object and when that
reference is removed. The following diagram indicates the various
scopes that can be associated with a newly created object:
www.educlash.com
186
Note that these implicit objects are only visible within the system
generated _jspService() method. They are not visible within
methods you define yourself in declarations.
www.educlash.com
187
11.5 SUMMARY
www.educlash.com
188
www.educlash.com
189
12
ADVANCE JSP
Unit Structure:
12.0 Objectives
12.1 Reusing Content in JSP Pages
12.2 Using JavaBeans Components
12.3 Using Custom tags
12.4 Transferring Control to another Web Component
12.5 Summary
12.6 Unit end exercise
12.7 Further Reading
12.0 OBJECTIVES
www.educlash.com
190
Include.jsp
<html>
<body bgcolor="white">
<br>
<H1 align="center">JavaServer Pages 1.0</H1>
<H2 align="center">Include Example</H2>
<P> </P>
<P> </P>
<font color="red">
<%@ page buffer="5" autoFlush="false" %>
<p>In place evaluation of another JSP which gives you the current
time:
</html>
www.educlash.com
191
foo.jsp
<body bgcolor="white">
<font color="red">
<%= System.currentTimeMillis() %>
www.educlash.com
192
www.educlash.com
193
www.educlash.com
194
BeanTime.jsp
<html>
<body>
<jsp:useBean class="myclass.CalendarBean" id="cal" />
<pre>
Time: <jsp:getProperty name="cal" property="Time" /><br>
Hour: <jsp:getProperty name="cal" property="Hour" /><br>
Minute:<jsp:getProperty name="cal" property="Minute"
/><br>
Seconds:<jsp:getProperty name="cal" property="Second"
/><br>
</pre>
</body>
</html>
www.educlash.com
195
Note that if any data has already been returned to a client, the
jsp:forward element will fail with an IllegalStateException.
jsp:param Element
When an include or forward element is invoked, the original
request object is provided to the target page. If you wish to provide
additional data to that page, you can append parameters to the
request object by using the jsp:param element:
<jsp:include page="..." >
<jsp:param name="param1" value="value1"/>
</jsp:include>
12.5 SUMMARY
www.educlash.com
196
www.educlash.com
197
13
INTRODUCTION TO EJB
Unit Structure:
13.0 Objectives
13.1 Introduction to EJB
13.2 Benefits of EJB
13.3 Difference between JavaBeans and Enterprise JavaBeans
13.4 JEE Architecture overview
13.5 JEE Application components
13.6 Java EE Clients
13.7 Summary
Unit end exercise
13.8
Further Reading
13.9
1. OBJECTIVES
2. INTRODUCTION TO EJB
www.educlash.com
198
www.educlash.com
199
www.educlash.com
200
6. JAVA EE CLIENTS:
1. Web Clients:
A web client consists of two parts:
i. dynamic web pages that contain various types of markup
languages (HTML, XML, and so on), which are generated by
web components running in the web tier, and
ii. a web browser, which renders the pages received from the
server.
www.educlash.com
201
2. Applets:
A web page received from the web tier can include an
“embedded applet”. An applet is a small client application written in
the Java programming language that executes in the Java Virtual
Machine installed in the web browser. However, client systems will
likely need the Java Plug-in, and possibly a security policy file, for
the applet to successfully execute in the web browser.
3. Application Clients:
An application client runs on a client machine. The
application client provides a better method for users to handle
tasks, which require a richer user interface than can be provided by
a markup language. The application client typically has a graphical
user interface (GUI) created from the Swing or the Abstract Window
Toolkit (AWT) API. However, a command-line interface is certainly
possible.
13.7 SUMMARY
www.educlash.com
202
www.educlash.com
Thank You
www.educlash.com
Advanced Java
Part-5
www.educlash.com
203
14
TYPES OF EJB’S
Unit Structure:
14.0 Objectives
14.1 Types of Enterprise JavaBeans
14.2 Session Beans
14.3 Message-driven Bean
14.4 Deciding on Remote or Local Access
14.5 Method Parameters and Access
14.6 Summary
14.7 Unit end exercise
14.8 Further Reading
14.0 OBJECTIVES
• Session Beans:
A Session Bean represents a transient conversation with a
client. When the Client completes its execution, the Session Bean
and it’s data are gone.
• Message-driven Beans:
A Message-driven Bean combines features of a session
bean and a message listener, allowing a business component to
asynchronously receive messages. Commonly, these are known as
Java Message Service (JMS) messages. In Java EE 5, the Entity
Beans have been replaced by Java Persistence API entities. An
Entity represents persistent data stored in one row of a database
www.educlash.com
204
www.educlash.com
205
1.Does Not Exist to Ready: The client initiates the life cycle by
obtaining a reference to a Stateless Session Bean. The container
performs any dependency injection, and then invokes the method
annotated @PostConstruct, if any. The client can now invoke the
business methods of the bean.
2.Ready to Does Not Exist: At the end of the session bean life
cycle, the EJB container calls the method annotated @PreDestroy,
if any. The Bean instance is then ready for garbage collection.
Callback Methods:
@PostConstruct: The container invokes this method on newly
constructed Bean instances after all dependency injections are
completed, and before the first business method is invoked on
the Enterprise Bean.
@PreDestroy: These methods are invoked after any method
annotated @Remove is completed, and before the container
removes the Enterprise Bean instance.
www.educlash.com
206
1. Does Not Exist to Ready: The Client initiates the life cycle by
obtaining a reference to a Stateful Session Bean. Dependency
injection is performed by container, and then invokes the
method annotated @PostConstruct, if any. The client can now
invoke the business methods of the bean.
2. Ready to Passive: In the Ready state, the EJB container may
decide to passivate the Bean by moving it from the memory to
the secondary storage.
3. Passive to Ready: If there is any @PrePassivate annotated
method, container invokes it immediately before passivating the
Bean. If a Client invokes a business method on the Bean while it
is in the Passive state, the EJB container activates the Bean.
The container then calls the method annotated with
@PostActivate and moves it to the Ready state.
4. Ready to Does Not Exist: At the end, the client calls a method
annotated with @Remove, and the EJB container calls the
method annotated with @PreDestroy. The Bean’s instance is
then ready for garbage collection. Only the method annotated
with @Remove can be controlled with your code.
Callback methods:
Given below are the annotations with the help of which you can
declare Bean Class methods as Life Cycle Callback methods:
• javax.annotation.PostConstruct
• javax.annotation.PreDestroy
• javax.ejb.PostActivate
• javax.ejb.PrePassivate
www.educlash.com
207
www.educlash.com
208
www.educlash.com
209
JMS Concept:
• What is Message?
Message is a unit of information or data which can be sent from
one processing computer/application to other/same
computer/applications.
• What is Messaging?
Messaging is a method of communication between software
components or applications.
• What is JMS?
The Java Message service is a client-side API for accessing
messaging systems.
www.educlash.com
210
www.educlash.com
211
www.educlash.com
212
Isolation
The parameters of remote calls are more isolated than those
of local calls. With remote calls, the client and the bean operate on
different copies of a parameter object. If the client changes the
value of the object, the value of the copy in the bean does not
change. This layer of isolation can help protect the bean if the client
accidentally modifies the data.
In a local call, both the client and the bean can modify the
same parameter object. In general, you should not rely on this side
www.educlash.com
213
www.educlash.com
214
ConverterBeanRemote.java
package server;
import java.math.BigDecimal;
import javax.ejb.Remote;
@Remote
public interface ConverterBeanRemote
{
public BigDecimal dollarToYen(BigDecimal dollars);
public BigDecimal yenToEuro(BigDecimal yen);
}
ConverterBean.java
package server;
import javax.ejb.Stateless;
import java.math.BigDecimal;
@Stateless
public class ConverterBean
{
private BigDecimal euroRate = new BigDecimal("0.0070");
private BigDecimal yenRate = new BigDecimal("112.58");
public BigDecimal dollarToYen(BigDecimal dollars)
{
BigDecimal result = dollars.multiply(yenRate);
www.educlash.com
215
ConverterServlet.java
package server;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.W ebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name="ConverterServlet",
urlPatterns={"/ConverterServlet"})
public class ConverterServlet extends HttpServlet {
String str=request.getParameter("txtnum");
int number=Integer.parseInt(str);
BigDecimal num=new BigDecimal(number);
www.educlash.com
216
CartBeanRemote.java
package server;
import java.util.Collection;
import javax.ejb.Remote;
@Remote
public interface CartBeanRemote{
public void addItem(String item);
public void removeItem(String item);
public Collection getItems();
}
CartBean.java
package server;
import java.util.ArrayList;
import java.util.Collection;
import javax.annotation.PostConstruct;
import javax.ejb.Stateful;
@Stateful
public class CartBean implements CartBeanRemote
{
private ArrayList items;
@PostConstruct
public void initialize() {
items = new ArrayList();
}
@Override
public void addItem(String item) {
items.add(item);
}
@Override
public void removeItem(String item) {
items.remove(item);
}
@Override
public Collection getItems() {
return items;
www.educlash.com
217
}
}
protected void processRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException
{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try
{
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet CartServlet</title>");
out.println("</head>");
out.println("<body>");
final Context context= new InitialContext();
CartBeanRemote cart = (CartBeanRemote)context.lookup
("java:global/CartStatefulEJB/CartBean");
out.println("<br>Adding items to cart<br>");
cart.addItem("Pizza");
cart.addItem("Pasta");
cart.addItem("Noodles");
cart.addItem("Bread");
cart.addItem("Butter");
out.println("<br>Listing cart contents<br>");
Collection items = cart.getItems();
for (Iterator i = items.iterator(); i.hasNext();)
{
String item = (String) i.next();
out.println("<br>" + item);
}
}catch (Exception ex){
out.println("ERROR -->" + ex.getMessage());
}
out.println("</body>");
out.println("</html>");
out.close();
}
www.educlash.com
218
14.6 SUMMARY
www.educlash.com
219
15
WEB SERVICES
Unit Structure:
15.0 Objectives
15.1 Introduction to Web Services
15.2 Building Web Services with JAX-WS
15.3 Creating a Simple Web Service and Client with JAX-WS.
15.4 Summary
15.5 Unit end exercise
15.6 Further Reading
1. OBJECTIVES
www.educlash.com
220
JAX-WS stands for Java API for XML Web Services. JAX-
WS is a technology for building web services and clients that
communicate using XML. JAX-WS allows developers to write
message-oriented as well as RPC-oriented web services.
www.educlash.com
221
package hello;
public class CircleFunctions {
public double getArea(double radius) {
return java.lang.Math.PI * (r * r);
}
public double getCircumference(double radius) {
return 2 * java.lang.Math.PI * r;
}
}
import javax.jws.WebService;
@WebService
public class CircleFunctions {
public double getArea(double r) {
return java.lang.Math.PI * (r * r);
}
public double getCircumference(double r) {
return 2 * java.lang.Math.PI * r;
}
}
www.educlash.com
222
new CircleFunctions());
}
Now, compile the source code normally using javac. However, you
must perform one more step: Call the Wsgen tool, as follows.
> wsgen –cp . hello.CircleFunctions
http://localhost:8080/WebServiceExample/circlefunctions?WSDL
15.4 SUMMARY
www.educlash.com
223
www.educlash.com
Thank You
www.educlash.com