0% found this document useful (0 votes)
502 views

BCA 6th Sem Advanced Java

The document discusses various classes in Java for drawing shapes and text, including: - Graphics2D for drawing basic shapes like rectangles - Rectangle2D for drawing rectangles with float or double coordinates - Point2D for representing x,y coordinate points - Ellipse2D for drawing ellipses defined by a bounding rectangle - RoundRectangle2D for drawing rectangles with rounded corners - Arc2D for drawing arcs defined by a bounding box, start angle, sweep angle and closure type - Font for specifying font face, style, and size - JLabel for displaying read-only text or an image These classes provide methods for common tasks like drawing shapes, text, and images to the screen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
502 views

BCA 6th Sem Advanced Java

The document discusses various classes in Java for drawing shapes and text, including: - Graphics2D for drawing basic shapes like rectangles - Rectangle2D for drawing rectangles with float or double coordinates - Point2D for representing x,y coordinate points - Ellipse2D for drawing ellipses defined by a bounding rectangle - RoundRectangle2D for drawing rectangles with rounded corners - Arc2D for drawing arcs defined by a bounding box, start angle, sweep angle and closure type - Font for specifying font face, style, and size - JLabel for displaying read-only text or an image These classes provide methods for common tasks like drawing shapes, text, and images to the screen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

} image, heightis the desired height of image, and

Swing } observer is the object to notify of the progress


The basic AWT library deals with user interface To draw rectangles, we use drawRect(x1, y1, w, h) of the rendering process (may be null). For example,
elements by delegating their creation and behavior to method and to draw string we use class SimplePanel extends JPanel
the native GUI toolkit on each target platform drawString(▫String▫, x1, y1) and so on. The drawings {
(Windows, Solaris, Macintosh, and so on). using Graphics class methods are very limited. For public void paintComponent(Graphics g)
This peer-based approach worked well for simple example, you cannot vary the line thickness and {
applications. User interface elements such as menus, cannot rotate the shapes. Image i = new
scrollbars, and text fields can have subtle differences ImageIcon("src\\simpleframe\\comp.gif","").getImage()
in behavior on different platforms. Moreover, some program : ;
graphical environments do not have as rich a class SimplePanel extends JPanel g.drawImage(i, 10, 10,150,150, null);
collection of user interface components as does { }
Windows or the Macintosh. As a result, public void paintComponent(Graphics g) }
GUI applications built with the AWT simply did not { -----------------------
look as nice as native Windows or Macintosh Graphics2D g2d = (Graphics2D)g; Text and Fonts
applications, nor did they have the kind of functionality Rectangle2D floatRect = new Rectangle2D.Float (10, We specify a font by its font face name (or font name
that users of those platforms had come to expect. 15.5F, 52.5F, 60.0F); for short). A font face name is composed of a font
More depressingly, there were different bugs in the g2d.draw(floatRect); family name, such as ▫Helvetica,▫ and an optional
AWT user interface library on the different platforms. } suffix such as Bold.▫ For example, the font faces
} ▫Helvetica▫ and ▫Helvetica Bold▫ are both considered
Creating a Frame --------- to be part of the family named ▫Helvetica.▫ To find out
A top-level window (that is, a window that is not Rectangle2D Class which fonts are available on a particular computer,
contained inside another window) is called a frame in The Rectangle2D class an abstract class with two call the getAvailableFontFamilyNames method of the
Java. The AWT library has a class, called Frame, for concrete subclasses, which are also static inner GraphicsEnvironment class. The method returns an
this top level. The Swing version of this class is called classes: Rectangle2D.Float and Rectangle2D.Double array of strings that contains the names of all
JFrame and extends the Frame class. The JFrame is as shown in the figure belowWhen we construct a available fonts. To obtain an instance of the
one of the few Swing components that is not painted Rectangle2D.Float object, we supply the coordinates Graphics Environment class that describes the
on a canvas. Thus, the decorations (buttons, title bar, as float numbers. For a Rectangle2D.Double object, graphics environment of the user's system, use the
icons, and so on) are drawn by the user▫s windowing we supply them as double numbers. For example, static getLocalGraphicsEnvironment method. Thus,
system, not by Swing. A simple program that displays Rectangle2D.Float floatRect = new the following program gives you a printout of the
an empty fame on the screen is given below. Rectangle2D.Float (10.0F, 25.0F, 22.5F, 20.0F); names of all fonts on your system:
import javax.swing.*; Rectangle2D.Double doubleRect = new import java.awt.*;
import java.awt.*; Rectangle2D.Double (10.0, 25.0, 22.5, 20.0); public class ListFonts
public class SimpleFrame -------------- {
{ Point2D Class public static void main(String[] args)
public static void main(String[] args) There is a Point2D class with subclasses {
{ Point2D.Float and GraphicsEnvironment ge=
EventQueue.invokeLater(()-> Point2D.Double. Here is how to make a point object. GraphicsEnvironment.getLocalGraphicsEnvironment()
{ Point2D p = new Point2D.Double (10, 20); ;
JFrame f = new JFrame(); ------------- String[]
Ellipse2D Class fontNames=ge.getAvailableFontFamilyNames();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOS For drawing the elliptical shapes we need to provide for (int i = 0; i < fontNames.length; i++)
E); the coordinates of bounding rectangles. Then System.out.println(fontNames[i]);
f.setSize(300,200); Elliptical shapes are drawn by jointing the mid points }
f.setVisible(true); of the sides of the rectangle. It is similar to Graphics }
}); class. For example,Ellipse2D e = new To draw characters in a font, you must first create an
} Ellipse2D.Double (150, 200, 100, 50); object of the class Font. You specify the font name,
} -------------- the font style, and the point size. Here is an example
RoundRectangle2D Class of how you construct a Font object.
Some common methods from For drawing the round edges rectangular shapes we Font f = new Font ("Helvetica", Font.BOLD, 14);
java.awt.Component need to provide the top left corner, width and height, You specify the style (plain, bold, italic, or bold italic)
• boolean isVisible(), void setVisible(boolean b) ▫ gets and the x- and y-dimension of the corner area that by setting the second Font constructor argument to
or sets the visible property. Components are initially should be rounded. For example, one of the following values:
visible, with the exception of top-level components RoundRectangle2D r = new Font.PLAIN
such as JFrame. RoundRectangle2D.Double(150, 200, 100, 50, 20, Font.BOLD
• void setSize(int width, int height) ▫ resizes the 20); Font.ITALIC
component to the specified width and height. --------------- Font.BOLD + Font.ITALIC
• void setLocation(int x, int y) ▫ moves the component Arc2D Class -------------
to a new location. The x and y coordinates use the To construct an arc, you specify the bounding box, Labels
coordinates of the container if the component is not a followed by the start angle and the angle swept out by A label displays a single line of read-only text, an
top▫level component, or the coordinates of the screen the arc and the closure type, one of Arc2D.OPEN, image or both text and an image. Labels are defined
if the component is top level (for example, a JFrame). Arc2D.PIE, or with class JLabel. Some of its useful constructors are:
• void setBounds(int x, int y, int width, int height) ▫ Arc2D.CHORD. Its general form is: • JLabel() ▫ creates a blank label.
moves and resizes this component Arc2D a = new Arc2D.Double (x, y, width, height, • JLabel(String str) ▫ creates a label that contains the
• Dimension getSize(), void setSize(Dimension d) ▫ startAngle, arcAngle, closureType); string specified by str.
gets or sets the size property of this component. For Example • JLabel(String str, int align) ▫ creates a label that
Arc2D a = new Arc2D.Double(10, 10, 200, 200, 45, contains the string specified by str using the
Some common methods from java.awt.Window 180, Arc2D.CHORD); (CHORD OR PIE OR OPEN ) alignment specified by align. The align argument is
• void toFront() ▫ shows this window on top of any JLabel.LEFT,
other windows. ------------------------ JLabel.RIGHT, JLabel.CENTER, JLabel.LEADING, or
• void toBack() ▫ moves this window to the back of the QuadCurve2D Class JLabel.TRAILING.
stack of windows on the desktop and rearranges all The Java 2D package supplies quadratic curves. • JLabel(Icon image) ▫ creates a label that contains
other visible windows accordingly. Quadratic curves are specified by two end points and the icon specified by image.
• boolean isLocationByPlatform(), void one control point. Moving the control points changes • JLabel(Icon image, int align) ▫ creates a label that
setLocationByPlatform(boolean b) ▫ gets the shape of the curves. Its general form is: contains the icon specified by image using the
or sets the locationByPlatform property. When the QuadCurve2D q = new QuadCurve2D.Double(startX, alignment specified by align.
property is set before thiswindow is displayed, the startY, controlX, controlY, endX, endY);
platform picks a suitable location. For example, ---------------
QuadCurve2D q = new Text Fields
Some common methods from javax.awt.Frmae QuadCurve2D.Float(10,10,50,300,200,200); Text fields allow the user to enter one line text and
• boolean isResizable(), void setResizable(boolean b) ---------------------------- edit using the arrow keys, cut and paste keys, and
▫ gets or sets the resizable property. When the CubicCurve2D Class mouse selection. Text fields are defined with the class
property is set, the user can resize the frame. The Java 2D package supplies cubic curves. Cubic JTextField. Several of its constructors are shown
• String getTitle(), void setTitle(String s) ▫ gets or sets curves are specified by two end points and two here:
the title property that determines the text in the title control point. Moving the control points changes the • JTextField() ▫ constructs a new empty JTextField
bar for the frame. shape of the curves. Its general form is: with 0 column width.
• Image getIconImage(), void setIconImage(Image CubicCurve2D c = new CubicCurve2D.Double(startX, • JTextField(int cols) ▫ constructs a new empty
image) ▫ gets or sets the startY, control1X, control1Y, JTextField with the specified
iconImage property that determines the icon for the control2X, control2Y, endX, endY); number of columns.
frame. The windowing system may display the icon as For example, • JTextField(String s) ▫ constructs a new JTextField
part of the frame decoration or in other locations. CubicCurve2D q = new with an initial string.
• boolean isUndecorated(), void CubicCurve2D.Float(10,10,100,50,100,300,200,200); • JTextField(String s, int cols) ▫ constructs a new
setUndecorated(boolean b) ▫ gets or sets the ---------------------- JTextField with an initial string
undecorated property. When the property is set, the Displaying Images and the specified number of columns
frame is displayed without decorations such as a title Once images are stored in local files or someplace on ---------------
bar or close button. This method must be called the Internet, you can read them into a Java Text Area
before the frame is displayed. application and display them on Graphics objects. If you need to collect user input that is more than one
• int getExtendedState(), void setExtendedState(int There are many ways of reading images. Here, we line long, you can use the JTextArea component.
state) ▫ gets or sets the extended window state. The use the ImageIcon class that you already saw: When you place a text area component in your
state is one of Image img = new ImageIcon(filename).getImage(); program, a user can enter any number of lines of text,
Frame.NORMAL Now the variable image contains a reference to an using the Enter key to separate them. Each line
Frame.ICONIFIED object that encapsulates the image data. You can ends with a '\n'. Most commonly used constructors
Frame.MAXIMIZED_HORIZ display the image with the drawImage methods of the are given below:
Frame.MAXIMIZED_VERT Graphics class as given below. • JTextArea() ▫ constructs a new text area with null
Frame.MAXIMIZED_BOTH boolean drawImage(Image img, int x, int y, starting text string, and 0 row and column width.
ImageObserver observer) - draws an unscaled image. • JTextArea(String text) ▫ constructs a new text area
Here, img is the image to be drawn, x is the x initialized with the specified text.
Working with 2D Shapes coordinate of the top left corner, y is the y coordinate • JTextArea(int rows, int columns) ▫ constructs a new
Starting with Java 1.0, the Graphics class from of the top left corner, and observer is the object to text area with the specified
java.awt package has methods to draw strings, lines, notify of the progress of the rendering process (may rows and columns.
rectangles, ellipses, and so on. For example to draw be null) • JTextArea(String text, int rows, int columns) ▫
line, we use drawLine(x1, y1, x2, y2) method as show • boolean drawImage(Image img, int x, int y, int width, constructs a new text area with specified text, rows
below, int height, ImageObserver observer) ▫ draws a scaled and columns.
class SimplePanel extends JPanel image. The system scales the image to fit into a ------------
{ region with the given width and height. Buttons
public void paintComponent(Graphics g) Here, img is the image to be drawn, x is the x The most widely used component is the push button.
{ coordinate of the top left corner, y is the y coordinate A push button is a component that contains a label
g.drawLine(10,10,100,100); of the top left corner, width is the desired width of and generates an event when it is pressed. The
JButton class provides the functionality of a push • showMessageDialog ▫ Show a message and wait for Using No Layout Manager
buttons. It allows an icon, a string, or both to be the user to click OK We can drop a component at a fixed location
associated with the push button. Some useful • showConfirmDialog ▫ Show a message and get a (absolute positioning) without using any
constructors are: confirmation (like OK/Cancel) layout manager. To place a component at a fixed
• JButton() ▫ creates an empty button. • showOptionDialog ▫ Show a message and get a user location, we follow the following steps:
• JButton(Icon icon) ▫ creates a button that contains option from a set of options • Set the layout manager to null.
icon as a label. • showInputDialog ▫ Show a message and get one line • Add the component you want to the container.
• JButton(String text) ▫ create a button that contains of user input The icon on the left side of the dialog • Specify the position and size that you want using
text as a label. box depends on one of five message types: setBounds method. The syntax setBounds method is
• JButton(String text, Icon icon) ▫ creates a button that ERROR_MESSAGE void setBounds(int x, int y, int width, int height). This
contains text and icon as label INFORMATION_MESSAGE method moves and resizes a component. Parameters
--------------- WARNING_MESSAGE x and y are top left corner of the component and width
Check Boxes QUESTION_MESSAGE and height determine new size of the component.
A check box is a control that is used to turn an option PLAIN_MESSAGE For example,
on or off. It consists of a small box that can either class SimplePanel extends JPanel
contain a check mark or not. There is a label {
associated with each check box that describes what private final JButton b1;
option the check box represents. You can change the private final JTextField t1;
state of a check box by clicking on it. Check boxes Layout Management public SimplePanel()
can be used individually or as part of a group. A layout manager automatically arranges your {
Check boxes are objects of the JCheckBox class. components inside a container using some type of b1 = new JButton("Ok");
Some useful constructors are: algorithm. The layout manager is set by the setLayout t1 = new JTextField(8);
• JCheckBox() ▫ creates a checkbox whose label is method. If no call to setLayout is made, then the setLayout(null);
blank. The state of the check box is unchecked. default layout manager is used. The setLayout b1.setBounds(10,10,50,35);
• JCheckBox(String str) ▫ creates a checkbox whose method has the following general form:void t1.setBounds(70,20,50,35);
label is specified by str. The state of the check box is setLayout(LayoutManager m) add(b1);
unchecked. Here, m is a reference to the desired layout manager. add(t1);
• JCheckBox(String str, boolean state) ▫ creates a Java has several predefined layout manager classes. }
checkbox whose label is specified by str. If state is Some of them are described below. You can use the }
true, the check box is initially checked; otherwise it is layout manager that best fits your application ------------------
cleared. Event Handling
• JCheckBox(Icon i) ▫ creates a checkbox with an icon 1.FlowLayout Event handling is of fundamental importance to
i. The state of the check box is unchecked. FlowLayout implements a simple layout style, which is programs with a graphical user interface.Any
• JCheckBox(Icon i, boolean state) ▫ creates a similar to how words flow in a text editor. Components operating environment that supports GUIs constantly
checkbox with an icon i. If state is true, the check box are laid out from the upper left corner, left to right, and monitors events such as keystrokes or mouse clicks.
is initially checked; otherwise it is cleared. top to bottom. When no more components fit on a The operating environment reports these events to
• JCheckBox(String, str, Icon i, boolean state) ▫ line, the next one appears on the next line. A small the programs that are running. Each program then
creates a checkbox with string str and an icon i. If space is left between each component, above and decides what, if anything, to do in response to these
state is true, the check box is initially checked; below, as well as left and right. events.Java uses AWT event model for handling
otherwise it is cleared. Here are the constructors for FlowLayout: events. This approach to handling events is
--------------------- FlowLayout() based on the delegation event model, which defines
Radio Buttons FlowLayout(int how) standard and consistent mechanisms to generate and
It is possible to create a set of mutually exclusive FlowLayout(int how, int horz, int vert) process events. This concept is quite simple: an event
check boxes in which one and only one check box in source generates an event and sends it to one or
the group can be checked at any one time. These For example, more event listeners. You can designate any object to
check boxes are oftencalled radio buttons. Radio class SimplePanel extends JPanel be an event listener. The listener simply waits until it
buttons are supported by JRadioButton class. Several { receives an event. Once an event is received, the
of its constructors are shown here: private final JButton b; listener processes the event and then returns.Event
• JRadioButton() ▫ Creates an unselected radio button private final JTextField t; sources have methods that allow you to register event
with no text. public SimplePanel() listeners with them. For example, the method that
• JRadioButton(Icon i) ▫ Creates an unselected radio { registers a keyboard event listener is called
button with specified icon. b = new JButton("Ok"); addKeyListener.We can also use removeKeyListener
• JRadioButton(Icon i, boolean state) ▫ Creates an t = new JTextField(8); method to remove keyboard listener. When an
unselected radio button with specified icon and setLayout(new FlowLayout(FlowLayout.LEFT)); event happens to the source, the source sends a
selected state. add(b); notification of that event to all the listener
• JRadioButton(String text) ▫ Creates an unselected add(t); objects that were registered for that event.
radio button with specified text. }
• JRadioButton(String s, boolean state) ▫ Creates a } How event handling in the AWT works
radio button with the specified text and selected state. A listener object is an instance of a class that
---------------- 2. BorderLayout implements a special interface called a listener
Combo Boxes This layout manager has four narrow, fixed-width interface.
Combo box is a combination of a text field and a drop- components at the edges and one large area in the • An event source is an object that can register
down list. A combo box normally displays one entry. center. The four sides are referenced to as north, listener objects and send them event objects.
However, it can also display a drop-down list that south, east, and west. The middle area is called the • The event source sends out event objects to all
allows a user to select a different entry. You can also center. registered listeners when that event occurs.
type your selection into the text field. Swing provides class SimplePanel extends JPanel • The listener objects will then use the information in
a combo box through the JComboBox class. Some of { the event object to determine their reaction to the
its constructors are: private final JButton b1,b2; event.
• JComboBox() ▫ Creates a JComboBox with a default private final JTextField t; In the program below, whenever the user clicks the
data model. public SimplePanel() button, the JButton object creates an ActionEvent
• JComboBox(Object[] items) ▫ Creates a JComboBox { object and listener object is notified. The
that contains the elements in the specified array. b1 = new JButton("Ok"); actionPerformed method in the listener object is
b2 = new JButton("Cancel"); called receiving the event object as a parameter.
------------- t = new JTextField(8); import javax.swing.*;
Menu Bars setLayout(new BorderLayout()); import java.awt.*;
A menu bar at the top of a window contains the JPanel p1 = new JPanel(); import java.awt.event.*;
names of the pull-down menus. Clicking on a name JPanel p2 = new JPanel(); public class EventDemo
opens the menu containing menu items and p1.add(b1); {
submenus. When the user clicks on a menu item, all p1.add(b2); public static void main(String[] args)
menus are closed and a message is sent to the p2.add(t); {
program.Swing provides a menu bar through the add(BorderLayout.NORTH,p1); EventQueue.invokeLater(() -> {
JMenuBar class. The dropdowns within that bar add(BorderLayout.SOUTH,p2); JFrame f = new JFrame();
are JMenu objects. JMenus can be nested within a }
JMenu to provide sub-menus. Each Menu is a } f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOS
collection of the widgets JMenuItem, E);
JRadioButtonMenuItem, JCheckBoxMenuItem and 3. BoxLayout f.setSize(300,200);
JSeparator. When the user selects a menu, an action It lays out components either in a row or in a column. SimplePanel p = new SimplePanel();
event is triggered. You need to install an action The BoxLayout class has only one constructor. f.add(p);
listener for each menu item. BoxLayout(Container target, int axis) ▫ creates a box f.setVisible(true);
To add a menu bar to a top-level container, create layout with the specified container that needs to be });
a JMenuBar object, populate it with menus, and laid out and the axis to lay out components along. The }
then call setJMenuBar method. For example, value of axis can be one of the following: }
JFrame frame = new JFrame("Menu bar demo"); BoxLayout.X_AXIS ▫ Components are laid out class SimplePanel extends JPanel
JMenuBar menuBar = new JMenuBar(); horizontally from left to right. {
JMenu fileMenu = new JMenu("File"); BoxLayout.Y_AXIS ▫ Components are laid out private final JButton b;
JMenu editMenu = new JMenu("Edit"); vertically from top to bottom. private final JTextField t;
JMenuItem newItem = new JMenuItem("New"); For example, public SimplePanel()
JMenuItem openItem = new JMenuItem("Open"); setLayout(new BoxLayout(panel, {
JMenuItem saveItem = new JMenuItem("Save"); BoxLayout.X_AXIS)); b = new JButton("Ok");
JMenuItem copyItem = new JMenuItem("Copy"); t = new JTextField(8);
JMenuItem pasteItem = new JMenuItem("Paste"); 4.GridLayout MyEventListener me = new MyEventListener();
fileMenu.add(newItem); It lays out components in a two-dimensional grid. The b.addActionListener(me);
fileMenu.add(openItem); constructors supported by add(b);
fileMenu.add(saveItem); GridLayout are: add(t);
editMenu.add(copyItem); GridLayout() ▫ creates a single-column grid layout. }
editMenu.add(pasteItem); GridLayout(int numRows, int numCols) ▫ creates a private class MyEventListener implements
menuBar.add(fileMenu); grid layout with the specified number of rows and ActionListener
menuBar.add(editMenu); columns. {
frame.setJMenuBar(menuBar); GridLayout(int numRows, int numCols, int horz, int public void actionPerformed(ActionEvent e)
------------------- vert) ▫ also allows you to specify the horizontal and {
Dialog Boxes vertical space left between components in horz and t.setText("Hello World!");
You usually want separate dialog boxes to pop up to vert, respectively.Either numRows or numColumns }
give information to, or get information from, the user. can be zero. Specifying numRows as zero allows for }
Swing has a convenient JOptionPane class that lets unlimited length columns and specifying numColumns }
you put up a simple dialog without writing any special as zero allows for unlimited length rows. Components --------------------
dialog box code. The JOptionPane has four static are added from first row to last row and first column to class SimplePanel extends JPanel
methods to show these simple dialogs: last column. {
-------------------- private final JTextField t;
public SimplePanel() you execute a query, you are interested in the result. • A JdbcRowSet is a thin wrapper around a ResultSet.
{ The executeQuery object returns an object of type It adds useful methods from the RowSet interface.
t = new JTextField(8); ResultSet that you can use to walk through the result There is a standard way for obtaining a row set:
MyEventListener me = new MyEventListener(); one row at a time. For example, RowSetFactory factory =
addMouseListener(me); String sqlStmt = "SELECT * FROM student"; RowSetProvider.newFactory();
add(t); ResultSet rs=stmt.executeQuery(sqlStmt); CachedRowSet crs = factory.createCachedRowSet();
}
private class MyEventListener extends
MouseAdapter 7)Closing Result Set, Statement and Connection
{ After completing the database operations, we close Cached Row Sets
public void mouseClicked(MouseEvent e) the result set, statement and the connection as A cached row set contains all data from a result set.
{ follows. Since CachedRowSet is a subinterface of the
t.setText("Hello World!"); rs.close(); ResultSet interface, you can use a cached row set
} stmt.close(); exactly as you would use a result set. Cached row
} conn.close() sets confer an important benefit: You can close the
} connection and still use the row set. Each user
------------------------ Scrollable and Updatable Result Sets command simply opens the database connection,
JDBC: In a scrollable result set, you can move forward and issues a query, puts the result in a cached row set,
Java provides a pure Java API for SQL access along backward through a result set and even jump to any and then closes the database connection. For
with a driver manager to allow third▫party drivers to position. In an updatable result set, you can example,
connect to specific databases. Database vendors programmatically update entries so that the database Statement stmt = conn.createStatement();
provide their own drivers to plug in to the driver is automatically updated. String sqlStmt = "SELECT * FROM Student";
manager. There is a simple mechanism for registering ResultSet rs = stmt.executeQuery(sqlStmt);
third-party drivers with the driver manager. Programs Scrollable Result Sets RowSetFactory factory =
written according to the API talk to the driver By default, result sets are not scrollable or updatable. RowSetProvider.newFactory();
manager, which, in turn, uses a driver to talk to the To obtain scrollable result sets from your queries, you CachedRowSet crs = factory.createCachedRowSet();
actual database. This means the JDBC API is all that must obtain a different Statement object with the crs.populate(rs);
most programmers will ever have to deal with. methodStatement stmt = conn.createStatement(type, conn.close();
-------------------- concurrency);
JDBC Driver Types For a prepared statement, use the call It is even possible to modify the data in a cached row
The JDBC specification classifies drivers into the PreparedStatement stmt = set. Of course, the modifications are not immediately
following types: conn.prepareStatement(command, type, reflected in the database; you need to make an
• A type 1 driver translates JDBC to ODBC and relies concurrency); explicit request to accept the accumulated changes.
on an ODBC driver to communicate with the The possible values of type and concurrency are: The CachedRowSet then reconnects to the database
database. Early versions of Java included one such • ResultSet.TYPE_FORWARD_ONLY ▫ The result set and issues SQL statements to write the accumulated
driver, the JDBC/ODBC bridge. Java 8 no longer is not scrollable (default). changes. You can inspect and modify the row set with
provides the JDBC/ODBC bridge. • ResultSet.TYPE_SCROLL_INSENSITIVE ▫ The the same methods you use for result sets.
result set is scrollable but not sensitive to database
• A type 2 driver is written partly in Java and partly in changes.
native code. It communicates with the client API of a • ResultSet.TYPE_SCROLL_SENSITIVE ▫ The result
database. When using such a driver, you must install set is scrollable and sensitive to database changes. CRUD
some platform-specific code onto the client in addition import java.sql.*;
to a Java library. If the result set is scrollable, you can scroll both public class MyDatabaseApplication
forward and backward by one row using rs.next() and {
• A type 3 driver is a pure Java client library that uses rs.previous() respectively. These method returns true public static void main(String[] args)
a database-independent protocol to communicate if the cursor is positioned on an actual row and false if {
database requests to a server component, which then it is positioned after the last row or before the first try
translates the requests into a database-specific row.You can move the cursor backward or forward by {
protocol. This simplifies deployment because the a number of rows with the call rs.relative(n). Class.forName("com.mysql.jdbc.Driver");
platform-specific code is located only on the server. Connection
conn=DriverManager.getConnection("jdbc:mysql://loc
• A type 4 driver is a pure Java library that translates alhost:3306/college","root","");
JDBC requests directly to a database-specific Updatable Result Sets Statement stmt=conn.createStatement();
protocol. If you want to edit the data in the result set and have String sqlStmt = "SELECT * FROM student";
the changes automatically reflected in the database, ResultSet rs=stmt.executeQuery(sqlStmt);
-------------------- create an updatable result set. Updatable result sets while(rs.next())
Configuring JDBC and Executing SQL Statements don▫t have to be scrollable, but if you present data to System.out.println(rs.getString(1)+"
You need to gather a number of items before you can a user for editing, you usually want to allow scrolling "+rs.getString(2)+" "+rs.getInt(3));
write your first database program. as well. To obtain updatable result sets, create a rs.close();
statement as follows Statement stmt = stmt.close();
1)Database URLs conn.createStatement(ResultSet.TYPE_SCROLL_SE conn.close();
When connecting to a database, you must use NSITIVE, ResultSet.CONCUR_UPDATABLE); }
various database-specific parameters such as host The result sets returned by a call to executeQuery are catch(Exception e)
names, port numbers, and database names. JDBC then updatable. If we use, {
uses syntax similar to that of ordinary URLs to ResultSet.CONCUR_READ_ONLY, the result set System.out.println(e);
describe data sources. The JDBC URL for MySQL cannot be used to update the database (default). }
database is given below. There are rs.updateXxx() methods for all data types }
"jdbc:mysql://localhost:3306/college","root","" that correspond to SQL types, such as }
rs.updateDouble(), rs.updateString()
2)Driver JAR Files Executing other SQL Statements
You need to obtain the JAR file in which the driver for For example,
your database is located. If you use MySQL, you Statement stmt = Creating Tables
need the file mysql-connector.jar. Include the driver conn.createStatement(ResultSet.TYPE_SCROLL_SE String sqlStmt = "CREATE TABLE Student (SID
JAR file on the class path when running a program NSITIVE, VARCHAR(10), SName VARCHAR(50),
that accesses the database. ResultSet.CONCUR_UPDATABLE); Roll_no INTEGER)";
String sqlStmt = "SELECT * FROM Student"; stmt.executeUpdate(sqlStmt);
3)Starting the Database ResultSet rs = stmt.executeQuery(sqlStmt);
The database server needs to be started before you while(rs.next()) Entering Data into a Table
can connect to it. The details depend on your { String sqlStmt = "INSERT INTO Student VALUES
database. if(rs.getString(2).equals("Anuja")) ('S101', 'Nawaraj',4)";
{ stmt.executeUpdate(sqlStmt);
4)Registering the Driver Class rs.updateString("SName", "Niraj");
Many JDBC JAR files automatically register the driver rs.updateRow(); Updating Data into a Table
class. If your driver▫s JAR file doesn▫t support } String sqlStmt = "UPDATE Student SET Roll_no = 5
automatic registration, you need to find out the name } WHERE SID = 'S101'";
of the JDBC driver classes used by your vendor. rs.close(); stmt.executeUpdate(sqlStmt);
Driver name for MySQL is:com.mysql.jdbc.Driver stmt.close();
There are two ways to register the driver with the Deleting Data from a Table
DriverManager. One way is to load the driver class in ------------------------------------ String sqlStmt = "DELETE FROM Student WHERE
your Java program. For example, Roll_no = 5";
Class.forName("com.mysql.jdbc.Driver"); Row Sets stmt.executeUpdate(sqlStmt);
Scrollable result sets are powerful, but they have a
major drawback. You need to keep the database Dropping a Table
5)Connecting to the Database connection open during the entire user interaction. String sqlStmt = "DROP table Student";
To connect to the database, we use getConnection However, a user can walk away from the computer for stmt.executeUpdate(sqlStmt);
method that returns a Connection object. For example a long time, leaving the connection occupied. That is
: Connection conn = not good ▫ database connections are scarce
DriverManager.getConnection("jdbc:mysql://localhost: resources. In this situation, use a row set. -----------------------------
3306/college", "root",""); The RowSet interface extends the ResultSet Prepared Statement
After connecting to the database, you can execute interface, but row sets don▫t have to be tied to a The PreparedStatement interface, a sub-interface of
different SQL statements on it. database connection Statement interface is used to create prepared
statement. Prepared statement is used to execute
parameterized query. We can prepare a query with a
6) Executing SQL Statements Constructing Row Sets host variable and use it many times. Each host
To execute a SQL statement, you first create a The javax.sql.rowset package provides the following variable in a prepared query is indicated with a ?. If
Statement object. To create statement object, use the interfaces that extend the RowSet interface: there is more than one variable, you must keep track
Connection object that you obtained from the call to • A CachedRowSet allows disconnected operation. of the positions of the ? when setting the values.
DriverManager.getConnection. For example, • A WebRowSet is a cached row set that can be
Statement stmt = conn.createStatement(); saved to an XML file. The XML file can be moved to
The executeUpdate method returns a count of the another tier of a web application where it is opened by —---For select ------
rows that were affected by the SQL statement, or zero another WebRowSet object. String sid = "S112";
for statements that do not return a row count. The • The FilteredRowSet and JoinRowSet interfaces int roll = 15;
executeUpdate support lightweight operations on row sets that are String sqlStmt = "SELECT * FROM Student WHERE
method can execute actions such as INSERT, equivalent to SQL SELECT and JOIN operations. SID = ? AND Roll_no = ?";
UPDATE, and DELETE, as well as data These operations are carried out on the data stored in PreparedStatement stmtPrepared =
definition statements such as CREATE TABLE and row sets, without having to make a database conn.prepareStatement(sqlStmt);
DROP TABLE you need to use the executeQuery connection. stmtPrepared.setString(1, sid);
method to execute SELECT queries. When stmtPrepared.setInt(2, roll);
ResultSet rs = stmtPrepared.executeQuery(); • A Bean obtains all the benefits of Java▫s ▫write- {
while(rs.next()) once, run-anywhere▫ paradigm. g.setColor(col);
System.out.println(rs.getString(2)); • The properties, events, and methods of a Bean that g.fillRect(20, 5, 20, 30);
rs.close(); are exposed to another application can be controlled }
stmtPrepared.close(); • Auxiliary software can be provided to help configure }
a Bean. This software is only needed when the Compile the source file(s)
-Insert,update,delete---- design-time parameters for that component are being javac SimpleBean.java
set. It does not need to be included in the run-time
String sid = "S112"; environment. Create manifest file
String sname = "Nawaraj"; • The state of a Bean can be saved in persistent User must create the manifest file to provide which
int roll = 15; storage and restored at a later time. components in the JAR file are java beans. You can
String sqlStmt = "INSERT INTO student • A Bean may register to receive events from other put any number of files in the manifest file entry but if
VALUES(?,?,?)"; objects and can generate events that are sent to other you have class files acting as java beans then each
PreparedStatement objects. entry of the file must be immediately followed by the
stmt=conn.prepareStatement(sqlStmt); line Java-Bean: True. For example,
stmt.setString(1, sid); Introspection: Name: SimpleBean.class
stmt.setString(2, sname); At the core of Java Beans is introspection. Beans Java-Bean: True
stmt.setInt(3, roll); support introspection, which allows a builder tool to Name the file as SimpleBean.mf (or .tmp or of your
stmt.executeUpdate(); analyze how Beans work. This is the process of choice)
stmt.close() analyzing a Bean to determine its capabilities. This is
an essential feature of the Java Beans API because it Generate a JAR file
allows another application, such as a builder tool, to Gather all needed class files in the directory and run
obtain information about a component. Without the jar as shown below.
JavaBean API introspection, the Java Beans technology could not jar cvfm SimpleBean.jar SimpleBean.mf
The package java.beans contains a set of classes operate.There are two ways in which the developer of SimpleBean.class
and interfaces that provide many functionalities a Bean can indicate which of its properties,events, You can also add other items such as icon images for
related to creating components based on JavaBeans and methods should be exposed. With the first beans to the JAR file. After generating the JAR file,
architecture. These classes are used by beans at method, simple naming conventions are used. These we can test it by loading it to the builder tool. You can
runtime. For example, the PropertyChangeEvent allow the introspection mechanisms to infer use NetBeans IDE to test the bean using following
class is used to fire property and vetoable change information about a Bean. In the second way, an steps.
events.JavaBeans component architecture also additional class that extends the BeanInfo interface is 1. Select Tools → Palette → Swing/AWT Components
provides support for a long-term persistence provided that explicitly supplies this information.
model. This enables beans to be saved in XML from the menu.
format. The read scheme with persistence is pretty Properties: 2. Click the Add from JAR button.
straightforward and does not require any special Properties control a Bean's appearance and behavior. 3. In the file dialog box, move to the directory and
knowledge in the process. The write scheme is a bit Builder tools introspect on a Bean to discover its select the jar.
tricky at times and requires special knowledge about properties and to expose them for manipulation. As a 4. Now a dialog box pops up that lists all the beans
the bean's type. If the bean's state is exposed using a result, you can change a Bean's property at design found in the JAR file. Select the bean.
nullary constructor, properties using public getters time. 5. Finally, you are asked into which palette you want
and setters, no special knowledge is required. to place the beans. Select Beans. (There are other
Otherwise, the bean requires a custom object, called Customization: palettes for Swing components, AWT components,
a persistence delegate, to handle the process of The exposed properties of a Bean can be customized and so on.)
writing out beans of a particular type. at design time. Customization allows a user to alter 6. Have a look at the Beans palette. It now contains
The classes that inherit java.awt.Component or its the appearance and behavior of a Bean. Beans an icon representing the new bean. However, the icon
descendents, automatically own persistence support customization by using property editors or by is just a default icon. You can also add icons to the
delegates. Otherwise, we can use a using special, sophisticated Bean customizers. bean
DefaultPersistenceDelegate instance or create our
own subclass of PersistenceDelegate to support the Design Patterns
scheme.The JavaBean APIs are meant to be used by Persistence: Bean developers are not required to add any
the bean editor, which provides the environment to Beans use Java object serialization, implementing the additional support for introspection in their code. They
customize and manipulate the properties of a bean java.io.Serializable interface, to save and restore only have to structure the code for the bean itself
component. Some interfaces and classes commonly state that may have changed as a result of because JavaBeans relies on the naming and type
used are as follows. customization. State is saved,for example, when you signatures of the methods defined in the code for a
Interface || Description customize a Bean in an application builder, so that the bean to determine what properties, methods, and
AppletInitializer => Methods of this interface are changed properties can be restored at a later time. events the bean supports for public use. In other
particularly useful for initializing applet beans. words, the conventions used in the code for a bean
Events: are also used as a means to introspect the bean.The
BeanInfo => This interface is used in the process of Beans use events to communicate with other Beans. automatic approach to JavaBeans introspection relies
introspection about the events, methods, and Beans may fire events, which mean the Bean sends heavily on the naming conventions and type
properties of a Bean. an event to another Bean. When a Bean fires an signatures of a bean's methods, including methods for
event it is considered a source Bean. A Bean may registering event listeners. The approach relies on
Customizer => This interface helps in providing a GUI receive an event, in which case it is considered a design patterns, which are standardized naming
interface. This GUI interface may be used to listener Bean. A listener Bean registers its interest in conventions and type signatures that are used to
manipulate and configure beans. the event with the source Bean. Builder tools use define bean methods based on their function.There
introspection to determine those events that a Bean are a variety of different design patterns for specifying
DesignMode => Methods in this interface help in sends and those events that it receives. everything from simple properties to event sources.
finding out if the bean is operating in the design All of these design patterns rely on some type of
mode. Methods: consistent naming convention for methods and their
All JavaBean methods are identical to methods of related arguments and types
ExceptionListener => Methods of this interface are other Java classes. A bean's methods are the things it
called when an exception occurs. can do. Any public method that is not part of a Three major types of design patterns, each of
property definition is a bean method. When you use a which are discussed.
PropertyChangeListener => A method of this interface bean in the context of a builder tool like NetBeans, • Property design patterns
is invoked when a bounded property change is you can use a bean's methods as part of your • Event design patterns
triggered. application. For example, you could wire a button • Method design patterns
press to call one of your bean's methods. Property Design Patterns
Properties are private values accessed through
Class || Description accessor methods (getter and setter methods).
BeanDescriptor => A BeanDescriptor provides global Bean Writing Process Property getter and setter method names follow
information about a "bean", including its Java class, Writing a bean is not technically difficult ▫ there are specific rules, called design patterns. These methods
its displayName, and so on. only few new classes and interfaces for you to are used to identify the publicly accessible properties
Beans => This class provides some general purpose master. In particular, the simplest kind of bean is of a bean.
bean control methods. nothing more than a Java class that follows some It turns out that accessor methods are the means by
PropertyChangeEvent => A "PropertyChange" event fairly strict naming conventions for its methods. We which the JavaBeans automatic introspection facilities
gets delivered whenever a bean changes a "bound" use a number of different steps to write and test determine which properties a bean exposes.
or "constrained" property. JavaBeans as follows.
SimpleBeanInfo => This is a support class to make it 1. Create a directory for the new Bean 1. Simple Property
easier for people to provide BeanInfo classes. 2. Create the java source file(s) Simple properties consist of all single-valued
VetoableChangeSuport => This is a utility class that 3. Compile the source file(s) properties, which include all built-in Java data types
can be used by beans that support constrained 4. Create manifest file. as well as classes and interfaces. For example, int,
properties. 5. Generate a JAR file. long, float, Color, Font, and boolean are allconsidered
Introspector => The Introspector class provides a 6. Start Builder tool. simple properties
standard way for tools to learn about the properties, 7. Load the jar file. public <PropertyType> get<PropertyName>()
events, and methods supported by a target Java 8. Test the bean. public void set<PropertyName>(<PropertyType> x)
Bean. Create a directory for the new Bean
EventHandler => The EventHandler class provides For example, 2. Boolean Property
support for dynamically generating event listeners C:\Users\IBASE\Desktop\bean\simplebean Boolean Properties are technically simple properties
whose methods execute a simple statement involving Create the java source file(s) of boolean type. They have an optional design pattern
an incoming event object and a target object. import java.awt.*; for the getter method that can be used to make it
FeatureDescriptor => The FeatureDescriptor class is import java.io.*; clearerthat a property is of boolean type. This design
the common base class fo public class SimpleBean extends Canvas implements patterns are as follows:
Serializable public boolean is<PropertyName>() //preferred one
JavaBeans are reusable software components for { public boolean get<PropertyName>()
Java that can be manipulated visually in a builder tool private Color col = Color.red;
(such as NetBeans). Once you implement a bean, public SimpleBean() 3. Indexed Property
others can use it in a builder environment. Instead of { An indexed property is an array of simple properties.
having to write tedious code, they can simply drop setSize(60,40); Because indexed properties require slightly different
your bean into a GUI form and customize } accessor methods, it only makes sense that their
it.JavaBeans are the classes written in the Java public Color getColorName() design patterns differ a little from other properties.
programming language conforming to a particular { Here are the design patterns for indexed properties.
convention. Beans are dynamic in that they can be return col; Methods to access individual values
changed or customized. Through the design mode of } public <PropertyType> get<PropertyName>(int index)
a builder tool you can use the Properties window of public void setColorName(Color c) public void set<PropertyName>(int index,
the bean to customize the bean and then save { <PropertyType> value)
(persist) your beans using visual manipulation. col = c;
repaint();
Advantages of JavaBeans } ----------------------------
Some of the major benefits of JavaBeans are: public void paint(Graphics g) Event Design Patterns
When a bean's internal state changes, it often is serialization automatic. Your Bean need take no other
necessary to notify an outside party of the change. To action. Automatic serialization can also be inherited.
accomplish this, beans are capable of broadcasting Therefore, if any superclass of a Bean implements Advantages of servlet:
event notifications that inform interested parties of java.io.Serializable, then automatic serialization is 1.Efficient
some change in a bean. A bean class can fire off any obtained. 2.Portable
type of event, including custom events. When using automatic serialization, you can 3.Robust0
Beans send notifications to event listeners that have selectively prevent a field from being saved 4.Extensible
registered themselves with a bean as wanting to through the use of the transient keyword. Thus, data 5.Secure
receive event notifications. Because listeners must members of a Bean specified as transient will not be 6.Performance
register themselves with a bean, it is important that serialized. 7.Life Cycle Of servlet
beans provide appropriate methods to facilitate the
registration process. The event registration methods ----------------- The lifecycle of servlet has following stages:
come in pairs, with one method enabling listeners to Customizers 1) Servlet class is loaded
be added and the other enabling beans to be Customization provides a means for modifying the The classloader is responsible to load the servlet
removed. JavaBeans introspector uses these appearance and behavior of a bean within an class. The servlet class is loaded when the first
methods to assess the events that a bean is capable application builder so it meets your specific needs. request for the servlet is received by the web
of sending. Event registration methods must conform There are several levels of customization available for container.
to the following design patterns for the automatic a bean developer to allow other developers to get
introspection services to work properly. maximum benefit from a bean's potential functionality 2) Servlet instance is created
public void add<EventListener>(<EventListener> e) A bean's appearance and behavior can be The web container creates the instance of a servlet
public void remove<EventListener>(<EventListener> customized at design time within beans▫compliant after loading the servlet class. The servlet instance is
e)public EventListener[] get<EventListeners>() builder tools. There are two ways to customize a created only once in the servlet life cycle.
bean:
----------------------------- 1)By using a Property Editor 3) init method is invoked
Method Design Patterns Each bean property has its own property editor. The The web container calls the init method only once after cre
The last area to cover in regard to design patterns is NetBeans GUI Builder usually displays a bean's
related to public methods that aren't accessor property editors in the Properties window. The public void init(ServletConfig config) throws ServletEx
methods. These methods are completely user-defined property editor that is associated with a particular ception
in that they have no pre▫established purpose such as property type edits that property type.
getting or setting a property. Because the naming and 2)By using Customizers 4) service method is invoked
type signature for non-accessor public methods is Customizers give you complete GUI control over bean The web container calls the service method each time
totally up to the bean developer, there aren't any customization. Customizers are used where property when request for the servlet is received. If servlet is
specific design patterns governing them. JavaBeans editors are not practical or applicable. Unlike a not initialized, it follows the first three steps as
assumes all public methods are to be publicly property editor, which is associated with a property, a described above then calls the service method. If
exported for outside use. The only difference between customizer is associated with a bean. The JavaBeans servlet is initialized, it calls the service method. Notice
these public methods and public accessor methods is specification provides for user-defined customizers, that servlet is initialized only once. The syntax of the
that accessor methods notify the JavaBeans through which you can define a higher level of service method of the Servlet interface is given below:
introspector of a bean property. customization for bean properties than is available public void service(ServletRequest request, ServletRe
with property editors. sponse response)
All customizers throws ServletException, IOException
Bound Properties must:
A Bean that has a bound property generates an event • Extend 5) destroy method is invoked
when the value of the property is changed. The event java.awt.Component The web container calls the destroy method before
is of type PropertyChangeEvent and is sent to objects or one of its removing the servlet instance from the service. It
that previously registered an interest in receiving such subclasses. gives the servlet an opportunity to clean up any
notifications. A class that handles this event must • Implement the resource for example memory, thread etc. The syntax
implement the PropertyChangeListener of the destroy method of the Servlet interface is given
interface.PropertyChangeEvent and below:
PropertyChangeListener live in the java.beans public void destroy()
package.The java.beans package also includes a java.beans.Customizer interface. This means
class, PropertyChangeSupport that takes care implementing methods to register Servlet API
of most of the work of bound properties. The bean PropertyChangeListener objects, and firing property Servlet APImakes manipulating anHTTPrequest and
class includes addPropertyChangeListener() and change events at those listeners when a change to responsepair simply Using HTTPServletRequest and
removePropertyChangeListener() the target bean has occurred. HTTPServletResponse objects
methods for managing the bean's listeners. • Implement a default constructor. 1)HTTPServletRequest object
• Associate the customizer with its target class via Information about anHTTP request
BeanInfo.getBeanDescriptor. Headers
------------- Query String
It is a very useful framework, an open-source MVC
Constrained Properties Session
framework for creating modern enterprise-level Java
A constrained property is a special kind of bound Cookies
web applications that favor convention over
property. For a constrained property, the bean keeps 2)HTTPServletResponse object
configuration and reduce overall development time. It
track of a set of veto listeners. When a constrained Used for formatting an HTTP response
comes with plugins to support REST, AJAX, and
property is about to change, the listeners are Headers
JSON and can be easily integrated with other Java
consulted about the change. Any one of the listeners Statuscodes
frameworks like Spring and Hibernate.
has a chance to veto the change, in which case the Cookies
Super Flexible and beginner-friendly,
property remains unchanged. It also generates an Reliable, based on MVC design pattern.
event of type PropertyChangeEvent. It too is sent to To sendtheinformation toaclient
Integration with REST, JSON, and AJAX.
objects that previously registered an interest in Useeither getWriter()orgetOutputStream( ):returning
Creative themes and templates make development
receiving such notifications. However, those other suitable objects for
tasks faster.
objects have the ability to veto the proposed change sending either text or binary content to the client,
Extend capabilities for complex development,
by throwing a PropertyVetoException. This capability respectively
Reduced development time and Effort, makes dev
allows a Bean to operate differently according to its Onlyonefothemethods may be used witha
easier and fun.
run-time environment. A class that handles this event HTTPServletResponse object andattemptingtocallboth
must implement the VetoableChangeListener methodscauseanexceptiontobethrown
Unit 4 Servlet and JSP
interface. The java.beans package includes a Java Servlets are programs that run on aWeb or
VetoableChangeSupport class that greatly simplifies Application server
constrained properties. The bean class includes Servlets arealsocalled server-sideprogramsi.e. Thecodeof
addVetoableChangeListener() and theprogramexecutesatserver side, acting as amiddle
removeVetoableChangeListener() layer betweenrequest comingfromWeb browsers orother
methods for managing the bean's listeners. HTTPclientsanddatabases orapplications ontheHTTP
server.
--------------- Reading Servlet Parameters
BeanInfo Interface 1.Servletshandles formdata parsing automatically using
Design patterns implicitly determine what information thefollowingmethods
is available to the user of a Bean. The BeanInfo 2.depending onthesituation
interface enables you to explicitly control what 3.getParameter() − You call request.getParameter()
information is available. The BeanInfo interface method to get the value of aformparameterbytakinga
defines several methods, including these: parameterasaparametername
PropertyDescriptor[ ] getPropertyDescriptors( ) 4.getParameterValues()−Callthismethodifthe
EventSetDescriptor[ ] getEventSetDescriptors( ) parameterappears morethanonceand returns multiple
MethodDescriptor[ ] getMethodDescriptors( ) values, for example checkbox or combobox (sends
They return arrays of objects that provide information multiplevaluesforthesameparametername)
about the properties, events, and methods of a Bean. 5.getParameterNames()−Callthismethodifyouwanta
The classes PropertyDescriptor, EventSetDescriptor, completelist ofallparametersinthecurrentrequest.
and MethodDescriptor are defined within the 6.Thebrowserusestwomethodstopass thisinformation
java.beans package, and they describe the indicated towebserver.These methods are GET Method and
elements. By implementing these methods, a Servlet Packages POST Method.
developer can designate exactly what is presented to Servlets can be created using the javax.servlet and
a user, bypassing introspection based on design javax.servlet.http packages, whichareastandard part of GETMethod(doGet())
patterns. theJava's enterpriseedition, anexpanded versionofthe 1.TheGETmethodsendstheencodeduserinformation
When creating a class that implements BeanInfo, you Javaclasslibrarythatsupportslarge-scaledevelopment appended tothepagerequest.
must call that class bnameBeanInfo, where bname is projects. 2.Thepageandtheencodedinformationareseparatedby
the name of the Bean. For example, if the Bean is Theseclassesimplement theJavaServletandJSP the?(questionmark)symbol asfollows −
called MyBean, then the information class must be specifications. http://www.test.com/hello?key1 = value1&key2 =
called MyBeanBeanInfo Javaservletshavebeencreatedandcompiledjustlikeany value2
otherJavaclass.After you install the servlet packages POSTMethod
--------------- and add them to your computer's Classpath, you can 4.Agenerallymore reliable methodofpassing information
Persistance compile servlets with the JDK's Java compiler or any toabackend program is thePOSTmethod.
Persistence is the ability to save the current state of a other current compiler. 5.Thispackagestheinformationinexactlythesamewayas
Bean, including the values of a Bean▫s properties and GETmethod,butinsteadof sending it as a text string
instance variables, to nonvolatile storage and to after a ? (question mark) in the URL it sends it as a
retrieve them at a later time. The object serialization separatemessage.
capabilities provided by the Java class libraries are 6.Thismessagecomestothebackendprogramintheform
used to provide persistence for Beans.The easiest ofthestandard inputwhichyoucanparseanduseforyour
way to serialize a Bean is to have it implement the processing.
java.io.Serializable interface, which is simply a marker 7.ServlethandlesthistypeofrequestsusingdoPost()
interface. Implementing java.io.Serializable makes method.
Javax.servlet Package pw.println("Demo Cookie"); <body>
1.Provides the contract between the servlet/web pw.println("</TITLE></HEAD><BODY>"); <%!
application and the web container pw.println("<H3>"); int cube(int n){return n*n*n*;
2.Used for creating protocol independent server pw.println("The Cookie name is : "+ c.getName()); }
applications pw.println("<BR>"); %>
3.Servlet interface defines thecore of theentire package pw.println("The Value of Cookie : " + c.getValu <%= "Cube of 3 is:"+cube(3) %>
Other interfaces provide additional services to the pw.println("<BR>") </body>
developer pw.println("Life of Cookie is : " + c.getMaxAge() </html>
4.Contains 12 interfaces seconds"); pw.println("<BR>");pw.println("</H3>");
7interfacesimplementedbythepackage pw.println("</BODY></HTML>");pw.close(); Lifecycle of jsp
5interfaces implemented by theuser } Translation of JSP Page
5.7interfacesimplementedbythepackage } Compilation of JSP Page
6.5interfaces implemented by theuser Classloading (theclassloaderloads classfile)
Searching cookie Instantiation(Object of the Generated Servlet is created)
Cookies can be used tocheck whetherthe user isthefirst Initialization(thecontainerinvokesjspInit()method)
Server implemented interfaces time visitor or the users Requestprocessing(thecontainerinvokes_jspService()
ServletConfig hasalready visited
ServletContext Tosearchaspecific cookie,alltheavailable cookies
ServletRequest needtobecheckedtofindtheparticular cookieusing
ServletResponse thegetCookies()methodofHttpServletRequest
RequestDispatcher
FilterChain Deleting cookie
FilterConfig To delete cookies from local disk start Microsoft
Acookiecan also bedeleted withfollowingstep.
User implemented interfaces Setthemaximumageofcookietozero.
Servlet Assign nullvalue to cookie
ServletContextListener Cookie c = new Cookie(“JavaCookie”);
ServletContextAttributeListener c.setMaxAge(0);
SingleThreadModel response.addCookie(c);
Filter First createthecookieofsameastobedeleted and set
itsagetozeroand add ittotheresponseheaderofthe
Javax.servlet.http Package HTTPresponse.
Javax.servlet package provides interfacesandclasses to method)
service client requestsinprotocolindependent manner. Session Tracking: HTTP Session Destroy(the containerinvokes jspDestroy()method)
Javax.servlet.http packagesupports http-specific Session simply means a particular interval of time.
functions. Session Tracking is a way to maintain state (data) of
Severaloftheclassesarederivedfromthejavax.servlet an user. It is also known as session management in JSP vs Serverlet
packaage servlet.
Somemethodsfromthejavax.servlet packagearealso Http protocol is a stateless, so we need to maintain
used state using session tracking techniques. Each time
Contains user requests to the server, server treats the request
8 interfaces as the new request. So, we need to maintain the state
7classes of an user to recognize to particular user.

A simple servlet AsessioncanbecreatedviathegetSession()methodof


import javax.servlet.http.*; HttpServletRequest.
import javax.servlet.*; Thisobjectcanstoreasetofbindingsthatassociatenames
import java.io.*; withobjects.
public class DemoServlet extends HttpServlet{ ThesetAttribute(),getAttribute(),getAttributeNames(),and
public void doGet(HttpServletRequest req,HttpServlet removeAttribute()
Response res) methodsofHttpSessionmanagethesebindings.
throws ServletException,IOException
{ How do servlet track session?
res.setContentType("text/html"); There are four techniques used in Session tracking: Java WEB Frameworks
PrintWriter pw=res.getWriter(); Cookies 1) Spring
Hidden Form Field Spring is a powerful, lightweight, and most popular
pw.println("<html><body>"); URL Rewriting framework which makes Java quicker, easier, and
pw.println("Welcome to servlet"); HttpSession safer to use. This framework is very popular among
pw.println("</body></html>"); developers for its speed, simplicity, and productivity
pw.close(); Each session has a unique ID which helps to create enterprise-level web
}} ThefirsttimeasessionisbegunanIDisassigned applications with complete ease. Spring MVC and
Servlet vs java application Every subsequent connectionmustsend theID(througha Spring Boot made Java modern, reactive, and cloud-
Servlets do not have a main() cookieortheURL)HttpSession session= ready to build high-performance complex web
The main() is in the server request.getSession(); applications hence used by many tech-giants,
Entrypointtoservlet codeisviacalltoamethod(doGet()in Ifnullthenthisisanewsession including Netflix, Amazon, Google, Microsoft, etc.
theexample) ->Spring provides a lightweight container that can be
Servlet interaction with end user is indirect via Java Server Page(JSP) triggered without a web server or application server.
request/response object APIs JavaServer Pages(JSP)anextensionofservlet It provides backward compatibility and easy testability
Actual HTTP request/response processing is handled by technologythatseparates the of your project.
the server presentation fromthebusiness logic ->It supports JDBC which improves productivity and
Primary servlet output is typically HTML reduces the error as much as possible
TheclassesandinterfacesthatarespecifictoJavaServer ->It supports modularity and both XML and
Maintaining State Pagesprogrammingare annotation-based configuration
Thereare3ways tomaintain state located in packages javax.servlet.jsp and 2) Grails
Cookies javax.servlet.jsp.tagext. It is a dynamic full-stack Java framework based on
Hidden fields in forms TherearefourkeycomponentstoJSPs: the MVC design pattern. which is easy to learn and
Session level authentication Directives most suitable for beginners. Grails is an object-
Actions oriented language that enhances developer
Cookies Scriptingelements productivity. While written in Groovy it can run on the
ACookieis data (String)thattheserver passes tothe Taglibraries. Java platform and is perfectly compatible with Java
browser and thebrowser JSP Scriplet tag syntax.
stores ontheserver A scriptlet tag isusedto executejava source code in JSP ->Easy to Create tags for the View,
Setofnamevaluepairs Example: ->built-in support for RESTful APIs,
Webservers place cookies onusermachines with id to <html> ->you can mix Groovy and Java using Grails,
tracktheusers <body> ->best suitable for Rapid Development,
Cookiescanbeoneofthefollowing: <% out.print("welcome to jsp"); %> ->configuration features are dynamic, no need to
Persistent cookies: Stored on hard drive in text format </body> restart the server.
Non-persistent cookies: Stored in memory and goesaway </html>
after yourebootorturnoffthemachine JSP Expression
The code placed within JSP expression tag is writtentothe 3) Google Web Toolkit (GWT)
Types of cookies output streamofthe It is a very popular open-source Java framework used
PermanentCookies response. by a large number of developers around the world for
Permanent cookies are stored in client machine, they Soyouneednotwriteout.print()towritedata. building and optimizing complex browser-based
are not deleted when browsing session is closed. Itismainly usedtoprint thevaluesofvariable ormethod. applications. This framework is used for the
Permanent cookiescan beused to identify individual <%= statement %> productive development of high-performance complex
users.Itpersists aftertheuser restart thecomputer. web applications without being an expert in front-end
<html> technologies like JavaScript or responsive design. It
SessionCookies <body> converts Java code into JavaScript code which is a
Sessioncookiesarealsocalledtransient cookies. <%= "welcome to jsp" %> remarkable feature of GWT. Popular Google’s
These cookiesexiststill thebrowsing session continues </body> applications like AdSense and AdWords are written
and automatically getsdeletedassoonastheusercloses </html> and using this framework.
thewebbrowser.Thesecookies usually store asession ID ->Google APIs are vastly used in GWT applications.
that isnotpermanently boundto theuser,allowingtheuser ->Open-source and Developer-friendly.
tomovefrompagetopagewithoutlogineachtime. JSP declaration tag ->Easily create beautiful UIs without vast knowledge
TheJSPdeclarationtagisusedtodeclarefieldsand in front-end scripting languages.
Creating cookie methods. ->Create optimized web applications that are easy to
import java.io.*; import javax.servlet.*; Thecodewritteninsidethejspdeclaration tagisplaced debug.
import javax.servlet.http.*; outsidetheservice()method ->Compiles the Java source code into JavaScript files
public class DemoCookie extends HttpServlet{ ofautogeneratedservlet. that can run on all major browsers
public void doGet(HttpServletRequest request, Soitdoesn'tgetmemoryateachrequest.
HttpServletResponse response)throws <%! field or method declaration %> 4) Struts
ServletException, IOException{ <html> It is a very useful framework, an open-source MVC
response.setContentType("text/html"); <body> framework for creating modern enterprise-level Java web
PrintWriter pw = response.getWriter(); <%! int data=50; %> applications that favor convention over configuration and
Cookie c = new Cookie("DemoCookie","123456"); <%= "Value of the variable is:"+data %>
reduce overall development time. It comes with plugins to
c.setMaxAge(7*24*60*60); </body>
response.addCookie(c); </html> support REST, AJAX, and JSON and can be easily
pw.println("<HTML><HEAD><TITLE>"); <html>
integrated with other Java frameworks like Spring and public class AdderRemote extends UnicastRemoteOb
Hibernate. ject implements Adder{
1.Super Flexible and beginner-friendly, AdderRemote()throws RemoteException{
super();
2.Reliable, based on MVC design pattern.
}
3.Integration with REST, JSON, and AJAX. public int add(int x,int y){return x+y;}
}
5) JavaServer Faces (JSF)
It is quite similar to Struts, a free web application 3) create the stub and skeleton objects using the rmic
developed framework, maintained by Oracle technology tool.
which simplifies building user interfaces for Server-side Next step is to create stub and skeleton objects using
applications by assembling reusable UI components in a the rmi compiler. The rmic tool invokes the RMI
page. JSF is a component-based MVC framework that compiler and creates stub and skeleton objects.
encapsulates various client-side technologies and focuses rmic AdderRemote
more on the presentation layer to allow web developers to
create UI simply by just drag and drop. 4) Start the registry service by the rmiregistry tool
Rich libraries and reusable UI components, Now start the registry service by using the rmiregistry
->Easy front-end tools to use without too much coding, tool. If you don't specify the port number, it uses a
->JSF helps to improve productivity and consistency, default port number. In this example, we are using the
->Enrich the user experience by adding Ajax events for port number 5000.
validations and method invocations. rmiregistry 5000
->It provides an API to represent and manage UI
components and instead of using Java, JSF uses XML for 5) Create and run the server application
view handling. import java.rmi.*;
import java.rmi.registry.*;
UNIT 5 RMI public class MyServer{
RMI public static void main(String args[]){
The RMI (Remote Method Invocation) is an API that try{
provides a mechanism to create distributed Adder stub=new AdderRemote();
application in java. The RMI allows an object to Naming.rebind("rmi://localhost:5000/sonoo",stub);
invoke methods on an object running in another JVM. }catch(Exception e){System.out.println(e);}
The RMI provides remote communication between }
the applications using two objects stub and skeleton. }
Architecture of RMI
In an RMI application, we write two programs, 6) Create and run the client application
a server program (resides on the server) and a client import java.rmi.*;
program (resides on the client). public class MyClient{
Inside the server program, a remote object is created public static void main(String args[]){
try{
and reference of that object is made available for the Adder stub=(Adder)Naming.lookup("rmi://localhost:50
client (using the registry). 00/sonoo");
The client program requests the remote objects on System.out.println(stub.add(34,4));
the server and tries to invoke its methods. }catch(Exception e){}
}
}

RMI VS CORBA
1. RMI is Java-centric while CORBA is not tied to a
single language.
2. RMI is easier to master particularly for Java
programmers and developers.
3. CORBA offers greater portability due to its high
adaptability to various programming languages.
4. CORBA can’t send new objects across networks

Transport Layer − This layer connects the client and


the server. It manages the existing connection and
also sets up new connections.
Stub − A stub is a representation (proxy) of the
remote object at client. It resides in the client system;
it acts as a gateway for the client program.
Skeleton − This is the object which resides on the
server side. stub communicates with this skeleton to
pass request to the remote object.
RRL(Remote Reference Layer) − It is the layer which
manages the references made by the client to the
remote object.

Importance of stub and skeleton


stub
The stub is an object, acts as a gateway for the client
side. All the outgoing requests are routed through it. It
resides at the client side and represents the remote
object. When the caller invokes method on the stub
object, it does the following tasks:
It initiates a connection with remote Virtual Machine
(JVM),
It writes and transmits (marshals) the parameters to
the remote Virtual Machine (JVM),
It waits for the result
It reads (unmarshals) the return value or exception,
andIt finally, returns the value to the caller.
skeleton
The skeleton is an object, acts as a gateway for the
server-side object. All the incoming requests are
routed through it. When the skeleton receives the
incoming request, it does the following tasks:
It reads the parameter for the remote method
It invokes the method on the actual remote object,
andIt writes and transmits (marshals) the result to the
caller.
Marshalling and Unmarshalling
The packing of parameter into bundle is known as
marshalling.
At the server side, the packed parameters are
unbundled and then the required method is invoked.
This process is known as unmarshalling.

RMI program to find sum of 2 numbers:


1) create the remote interface
import java.rmi.*;
public interface Adder extends Remote{
public int add(int x,int y)throws RemoteException;
}

2) Provide the implementation of the remote interface


import java.rmi.*;
import java.rmi.server.*;

You might also like