Advanced Java
Advanced Java
JAVA
By Jitendra Patel
PREFACE
ADVANCED JAVA: This book is especially for those who have basic knowledge of
JAVA and want to learn some advanced features of JAVA like Applet, AWT, SWINGs,
Servlet, JDBC, JSP etc
Also every one with interest in ADVANCED JAVA can refer this book to get the
knowledge of secure Web Application Development using Swing, JDBC, Servlet and JSP.
It covers virtually most of core features and some of the advanced features of Web site
Development including more than hands on examples tested in popular Web browser like
Chrome, IE and Firefox and platforms like Apache Web Server and WampServer. Most of
code samples are presented in easy to use way through any simple text editor starting from
notepad. Throughout the book most of the programming features are explained through
syntax and examples to develop state-of-the-art Web applications.
Table of Contents
Advanced JAVA
Copyright Reserved by the Author
PREFACE
Unit I JAVA Applets
Concept of Applet Programming
Designing a Web page
Short Questions and Answers
Exercise
Unit II Introduction of Abstract Window Toolkit: (AWT)
Working with Windows and AWT
Working with frame windows
Working with graphics: AWT controls
Layout Managers
Event Handling in Java
Event Classes and Listener Interfaces
GUI with Swing
Short Questions and Answers
Exercise
Unit III Java Data Base Client/ Server
Java as a Database front end Database client/server methodology
JDBC Architecture
Common JDBC Components
JDBC Database Example
Current JDBC Drivers
Advantages Using JDBC
Limitations Using JDBC
Security Considerations
Short Questions and Answers
Exercise
Unit IV Servlets
Introduction to Web
Introduction to Servlet
The Life Cycle Of a Servlet
Servlet Container
Installing Servlets
The Servlet API
Reading Servlet Parameters
Reading Initialization Parameters
Handling HTTP Requests and responses
Session Tracking
Reading and displaying Records using servlet
Short Questions and Answers
Exercise
Unit V Java Server Pages: (JSP)
JSP technology
JSP page
Relation of Applets and Servlets with JSP
Comments in JSP
Simple JSP program
JSP Scripting Elements
JSP Expressions
JSP Scriplets
JSP Declarations
JSP Directives
Predefined Variables/implicit objects
JSP Databse Access
Short Questions and Answers
Exercise
Local Applet
Remote Applets
The remote applets are stored in remote computer.
The web page requires internet connection to locate and load the remote
applet from the remote computer. To access a remote applet in your Web
page, you must know the applets URL and any parameters to supply in
order to display the applet correctly.
Web Browser
Remote Machine
Applet
Remote Applet
Specifying a Local Applet
The codebase attribute specifies a path name on your system for the local applet,
whereas the code attribute specifies the name of the byte-code file that contains the
applets code.
<applet
codebase=MyGame
code= MyGame.class
width=130
height=130>
</applet>
The path specified in the codebase attribute is relative to the folder containing the
HTML document that references the applet.
Specifying a Remote Applet
The codebase attribute specifies a URL on remote system for the remote applet,
whereas the code attribute specifies the name of the byte-code file that contains the
applets code.
<applet
codebase=http://www.website.com/applets/
code=MyGame.class
width=130
height=130>
</applet>
The only difference between accessing local and remote applet is the value of
the codebase attribute. In the first case, codebase specifies a local folder, and in the second
case, it specifies the URL at which the applet is located.
Difference between applet and application
The most important differences between applet and application include:
An applet is a Java class that extends the java.applet.Applet class.
Applet
Application
Execution
Privileges
Container
Communication
Lifecycle
Peer
Network
Access
Invoke Native
Methods
Runs standalone
None, Standalone
No restrictions
Controlled by JRE
No restrictions
Yes
classpath variable.
// Simple Java Applet: Drawing a String. SimpleApplet.java
import java.applet.*;
import java.awt.*;
</BODY>
</HTML>
1. In SimpleApplet.html add an applet tag to invoke the SimpleApplet.class
with a width of 350 and a height of 200
2. Run SimpleApplet.html using appletviewer as shown below.
Instead of creating a separate html document and then including the applet in that we
can directly use the <applet> tag to embed within the applet program itself as a comment
as shown below:
// This is a simple applet with embedded applet tag. SimpleApplet2.java
/*
<applet code = SimpleApplet2 width=350 height =200>
</applet>
*/
public class SimpleApplet2 extends Applet
{
public void paint (Graphics g)
{
g.drawString(Welcome to the applet world ,20,40);
}
}
We can also use any java supported web browser to execute the applets. To do so
follow these steps:
1.
2.
3.
4.
5.
6.
If your applet executes in the appletviewer, but does not execute in your Web
browser, Java may not be installed or configured for your browser. In this case, install
Java for your browser. In Internet Explorer, if this does not fix the problem, you need to
configure Internet Explorer to use J2SE 5.0. To do so, click the Tools menu and select
Internet Options, then click the Advanced tab in the window that appears. Locate the
option Use JRE v1.5.0 for <applet> (requires restart) and ensure that it is checked, and
then click OK. Close all your browser windows before attempting to execute another
applet in the browser.
Creating an Executable Applet
Executable applet is nothing but the .class file of the applet, which is obtained by
compiling the source code of the applet. Compiling an applet is exactly the same as
compiling an application. Therefore, we can use the Java compiler to compile the applet.
Assume that we have created a file called SimpleApplet.java for our applet. Here are
the steps required for compiling the SimpleApplet applet.
1. Move to the directory containing the source code and type the following command:
javac SimpleApplet.java
2. The compiled output file called SimpleApplet.class is placed in the same directory
as the source.
3. Correct errors if any and compile the applet again.
Example:
<applet code = SimpleApplet2 width=350 height =200>
</applet>
Simple Methods to Design Applet
Method
void
Description
setBackground
(Color colorname )
void
setForeground
To set the foreground color of an applet
(Color colorname )
window.
Color getBackground (
Color getForeground ( )
Applet getApplet
String name )
URL getCodeBase( )
</BODY>
</HTML>
The browser is told how to launch the HelloWorld.class file as specified. Java applets
can only be displayed within a Web browser by being embedded in a standard HTML
page. This does not mean that the actual bytecode or source code of the applet is included
within the HTML file. Instead, the HTML text contains a reference to the Java applet
known as a tag.
Running the Applet
To run an Applet, you can use appletviewer utility or a Web browser.
1. Running using appletviewer utility
You can run the applet using the applet viewer utility, which can be invoked from the
DOS
prompt using the appletviewer command.
Appletviewer Utility
JDK provides a utility called appletviewer.exe for testing applet. Since web
browser is everywhere nowadays, you should use a web browser to see the actual effect
instead. You should try on all the common browsers (such as IE, firefox, chrome, safari)
if you want to put your applet in production. appletviewer processes only
the <applet> tag, and ignores all other tags in the HTML file. To use the appletviewer,
issue the following command:
> appletviewer SimpleApplet.html
Description
This method is invoked when the applet is first loaded. It is
called (only once) when the applet is first loaded to initialize
variables, resize the applet, setting up GUI components, and etc
start()
stop()
destroy()
paint()
alternateHTML
</APPLET>
Example Applet with parameters
/*
* AppletWithPara.java
*
*/
import java.applet.*;
import java.awt.*;
/*
<applet code=AppletWithPara width=200 height =150>
<param name=author value=J.B.Patel>
<param name=age value=27>
<param name=designation value=Lecturer>
<param name=institute value=SSPC Visnagar>
</applet>
*/
public class AppletWithPara extends java.applet.Applet
{
public void paint (Graphics gp)
{
String au=getParameter(author);
String ag=getParameter(age);
String desg=getParameter(designation);
String inst=getParameter(institute);
gp.drawString(Author:+au,20,40);
gp.drawString(Age:+ag,20,70);
gp.drawString(Designation:+desg,20,100);
gp.drawString(Institute:+inst,20,130);
showStatus(Parameter methods);
}
}
Output:
Applet
Application
Security
No
Execution
Privileges
Container
Communication
default
Security
None, Standalone
No restrictions
Lifecycle
Controlled by browser
Peer
Controlled by JRE
Network
Access
Invoke Native
Methods
No
No restrictions
Yes
applet as a Dimension object, from which you extract separate width, height
fields. The following code explains this:
Dimension dim = getSize();
int appletwidth = dim.width();
int appletheight = dim.height();
1. What tags are mandatory when creating HTML to display an applet?
1. name, height, width
2. code, name
3. codebase, height, width
4. code, height, width
Correct answer is d.
1. What are the steps involved in Applet development?
Following are the steps involved in Applet development:
Create/Edit a Java source file. This file must contain a class which
extends Applet class.
Compile your program using javac
Execute the appletviewer, specifying the name of your applets source
file or html file. In case the applet information is stored in html file then
Applet can be invoked using java enabled web browser.
1. Which method is used to output a string to an applet? Which function is
this method included in?
drawString( ) method is used to output a string to an applet. This method is
included in the paint method of the Applet.
Exercise
1. What is an Applet? Explain life cycle of Applet.
2. Write an applet that displays a string. Write necessary applet tag for it.
3. Write short notes: - < PARAM >tag.
Component class is at the top of AWT hierarchy. Component is an abstract class that
encapsulates all attribute of visual component. A component object is responsible for
remembering the current foreground and background colors and the currently selected text
font.
AWT classes are contained in the java.awt package. It is one of the javas largest
packages. The java.awt package contains classes, which generates GUI components. AWT
provides graphical user interface (GUI) components that are used in all java applets and
applications. AWT contains classes that can be extended and their properties can be
inherited. AWT classes can also be abstract. Every GUI component must be a subclass of
the abstract class Component or MenuComponent
Windows Fundamentals
There are two types of GUI elements:
1. Component: Components are elementary GUI entities (such as Button, Label,
andTextField.)
2. Container: Containers (such as Frame,Panel and Applet) are used to hold
components in a specific layout (such as flow or grid). A container can also hold
sub-containers.
Components
GUI components are also called controls which allow users to interact with (i.e.,
control) the application through these components (such as button-click and text-entry).
There are five components: a Label (providing description), a TextField (for users to enter
text), and three Buttons (for user to trigger certain programmed actions). In a GUI
program, a component must be kept in a container.
Useful Methods of Component class
Method
Description
public
void
width,int height)
setSize(int
public
void
Defines the layout manager for the
setLayout(LayoutManager m)
component.
public void setVisible(boolean
Changes the visibility of the component,
status)
by default false.
Containers
In the above figure, there are three containers: a Frame and two Panels.
A Frame is the top-level container of an AWT program. A Frame has a title bar
(containing an icon, a title, and the minimize/maximize/close buttons), an
optional menu bar and the content display area.
A Panel is a rectangular area used to group related GUI components in a
certain layout. In the above figure, the top-level Frame contains two Panels.
You need to identify a container to hold the components. Every container has a method
called
add(Component
c).
A
container
(say
aContainer)
can
invoke aContainer.add(aComponent) to add aComponent into itself. For example,
Panel panel = new Panel(); // Panel is a Container
Button btn = new Button(Press); // Button is a Component
panel.add(btn); // The Panel Container adds a Button Component
Hierarchy of the AWT Container Classes
The hierarchy of the AWT Container classes is as follows:
The AWT provides four container classes. They are class Window and its two subtypes
class Frame and class Dialog as well as the Panel class. In addition to the containers
provided by the AWT, the Applet class is a container it is a subtype of the Panel class
and can therefore hold components. Brief descriptions of each container class provided by
the AWT are provided below.
Panel
Window
Frame
Above class extends from the Panel class. In the main() method, an instance of this
new class is created and added to the Frame object via a call to the add() method. The
result is then displayed. The results of both examples should look same.
Working with Window
A Window is a top-level display area that exists outside the browser or applet area you
are working in. It has no adornments, such as the borders, window title, or menu bar that a
typical window manager might provide. A Frame is a subclass of Window that adds these
parts (borders, window title). Normally you will work with the children of Window and
not Window directly. However, you might use a Window to create your own pop-up menu
or some other GUI component that requires its own window and isnt provided by AWT.
The default LayoutManager for Window is BorderLayout.
Constructors of Window
public Window (Frame parent)
There is one public constructor for Window. It has one parameter, which specifies the
parent of the Window. When the parent is minimized, so is the Window. In an application,
you must therefore create a Frame before you can create a Window; this isnt much of an
inconvenience since you usually need a Frame in which to build your user interface. In an
applet, you often do not have access to a Frame to use as the parent, so you can pass null
as the argument.
Working with Frame
A window that is not contained inside another window is a frame. Frames are
containers, which mean that a frame can contain other GUI components.
A Frame provides the main window for the GUI application, which has a title bar
(containing an icon, a title, minimize, maximize/restore-down and close buttons), an
optional menu bar, and the content display area. When a frame object is created, it is 0x0
pixels and invisible. You must call the show or setVisible methods to actually make the
frame appear on the screen. Then, you must set the size of the frame using setSize or
setBound() method.
Creating a Frame
There are two ways to create a Frame. They are,
1. By Instantiating Frame class
2. By extending Frame class
Creating Frame Window by Instantiating Frame class
import java.awt.*;
public class AWTDemo extends java.applet.Applet {
AWTDemo()
{
Frame fm=new Frame(); //Creating a frame.
Label lb = new Label(Welcome to Graphics); //Creating a label
fm.add(lb); //adding label to the frame.
fm.setSize(300, 300); //setting frame size.
fm.setTitle(AWT Demo);
fm.setVisible(true); //set frame visibilty true.
}
public static void main(String args[])
{
AWTDemo ta = new AWTDemo();
}
}
Output:
public AWTDemo2()
{
Button btn=new Button(Hello World);
add(btn); //adding a new Button.
setSize(250, 300); //setting size.
setTitle(Welcome to AWT); //setting title.
setLayout(new FlowLayout()); //set default layout for frame.
setVisible(true); //set frame visibilty true.
}
public static void main (String[] args)
{
AWTDemo2 test = new AWTDemo2(); //creating a frame.
}
}
Output:
</APPLET>
</body>
</html>
Output:
add(button);
}
public boolean action(Event evt, Object arg)
{
boolean visible = frame.isShowing();
if (visible)
{
frame.hide();
button.setLabel(Show Window);
}
else
{
frame.show();
frame.resize(200, 100);
button.setLabel(Hide Window);
}
return true;
}
}
Output:
Before
After
ScrollPane
The ScrollPane container was introduced with the 1.1 release of the Java Runtime
Environment (JRE) to provide a new Container with automatic scrolling of any ONE large
Component. That large object could be anything from an image that is too big for the
display area to a bunch of spreadsheet cells. All the event handling mechanisms for
scrolling are managed for you. Also, there is no LayoutManager for a ScrollPane since
there is only a single object within it.
The following example demonstrates the scrolling of a large image. Since an Image
object is not a Component, the image must be drawn by a component such as a Canvas .
//ScrollingImage.java
import java.awt.*;
import java.applet.*;
/* <applet code= ScrollingImage.class width=200 height=150></applet> */
}
}
public class ScrollingImage extends Applet {
public void init() {
setLayout(new BorderLayout());
ScrollPane sp =
new ScrollPane(ScrollPane.SCROLLBARS_ALWAYS);
Image im =
getImage(getCodeBase(), ./images/Penguins.jpg); // give any local image url
sp.add(new ImageCanvas(im));
add(sp, BorderLayout.CENTER);
}
}
Output:
Canvas
The Canvas class implements a GUI object that supports drawing. Drawing is not
implemented on the canvas itself, but on the Graphics object provided by the canvas.
The Canvas is a section of a window to draw graphics or display images. In that
respect, a canvas is more similar to a container than a componenthowever, a Canvas
component cannot be used as a place to put components.
Constructors of Canvas Class
Name
Canvas()
Description
This constructor
instance of a Canvas.
creates
Canvas(GraphicsConfiguration
This constructor creates
config)
instance of a Canvas with the
given
object
of
GraphicsConfiguration.
Methods of Canvas Class
Method
getAccessibleContext()
getBufferStrategy()
Description
This method gets the accessible
context of Canvas.
This method gets the Buffer
Strategy.
paint(Graphics g)
update(Graphics g)
createBufferStrategy(int
numBuffers)
This
method
BufferStrategy.
creates
the
The following code creates a Canvas component, resizes it to 50x50 pixels, sets the
background of the canvas to the color black, and adds the canvas to an applet window:
Example: Using Canvas
/*
canvasDemo.java
*/
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code=CanvasDemo.class height=150 width=200>
</applet>
*/
import java.awt.Canvas;
import java.awt.Graphics;
class DrawingRegion extends Canvas {
public DrawingRegion() {
setSize(100, 50);
}
public void paint(Graphics g) {
g.drawRect(0, 0, 99, 49); // draw border
g.drawString(A Canvas, 20,20);
}
}
Then you use it like any other component, adding it to a parent container, for example
in an Applet subclass.
import java.applet.Applet;
/*
<applet code= CanvasPaintTest.class height=150 width=200>
</applet>
*/
UI Component
Buttons
java.awt.Button
Checkboxes
java.awt.Checkbox
java.awt.TextField
Text Area
java.awt.TextArea
Labels
java.awt.Label
Lists
java.awt.List
java.awt.Choice
java.awt.Scrollbar
Drawing areas
java.awt.Canvas
Menus
java.awt.Menu,
java.awt.MenuItem,
java.awt.CheckboxMenuItem
Containers
An Anonymous Instance
You can create a Label without specifying an identifier, called anonymous instance. In
the case, the Java compiler will assign an anonymous identifier for the allocated object.
You will not be able to reference an anonymous instance in your program after it is
created. This is usually alright for a Label instance as there is often no need to reference
a Label after it is constructed.
Example of anonymous instance
// Allocate an anonymous Label instance. this container adds the instance into
itself.
add(new Label(Enter Name: , Label.RIGHT));
// Same as
Label lblXxx = new Label(Enter Name: , Label.RIGHT));
Example: Adding Component in a Container
import java.awt.*;
import java.applet.Applet;
c.init();
f.add(Center, c);
f.pack();
f.show();
}
}
Output:
Above code adds two buttons in the init() method because it is automatically called
during applet initialization. Therefore, no matter how the program is started, the buttons
are created, because init() is called by either the browser or by the main() method. Now
Lets see how all components used to create GUI.
Labels
A Label provides a text description message. The Label component is a string
displayed in the container that cannot be modified by the user.
Constructors of Label Component
Constructor
Action
Label( )
Label(String)
Label(String, int)
Method
Action
int getAlignment()
String getText()
void
setAlignment(int align)
void setText(String
label)
Adding Label
The following code is used to create a Label component and add it to an applet
window:
Label l = new Label(Counter );
add(l);
import java.awt.*;
{
setLayout(new GridLayout(3,1));
add(new Label(aligned left, Label.LEFT));
add(new Label(aligned center, Label.CENTER));
add(new Label(aligned right, Label.RIGHT));
}
}
Output:
TextField
Text Field is a GUI element used in applet to accept values from the user. The number
of characters visible in the text field is configurable.
TextField(int)
Action
Creates an empty TextField that is 0 characters wide
(it will be resized by the current layout manager).
Creates an empty text field. The integer argument
indicates the minimum number of characters to display.
TextField(String)
TextField(String, int)
Action
Returns the text this text field contains (as
a string)
setText(String)
getColumns()
select(int, int)
selectAll()
isEditable()
setEditable(boolean)
getEchoChar()
echoCharIsSet()
Adding TextField
Adding a TextField component to a window is the same as adding a button or any
other component. This can be done by instantiating the class TextFiled of java.awt
package as shown below.
TextField t = new TextField(12);
add(t);
After creating the text field, we need to add it to applet using add() method. This is
done in init() method of the applet.
To retrieve value from the text field, we use getText() method. But, this can return only
string value. Depending on our requirements we might need to convert this to other data
types. The syntax to get text value is shown below.
String val = t1. getText()
Example: Using a TextField Control
/* TextFieldsDemo.java*/
import java.awt.*;
}
}
Output:
{
t1.setText(0);
t2.setText(0);
t3.setText(0);
add(t1);
add(t2);
add(b1);
add(t3);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
int v1=Integer.parseInt(t1.getText());
int v2=Integer.parseInt(t2.getText());
t3.setText(String.valueOf(v1+v2));
}
}
Output:
TextArea
TextArea is the TextComponent for multiline input. Some constructors permit you to
set the rows and columns of the TextArea on the screen. However, the Layout Manager
may change your settings. As with TextField, the only way to limit the number of
characters that a user can enter is to override the keyDown() method. The text in a
TextArea appears left justified, and the justification is not customizable. Depending upon
Action
TextArea()
TextArea(int, int)
TextArea(String)
TextArea(String, int,
int)
int)
Action
getColumns()
getRows()
insertText(String,
replaceText(String,
Replaces the text between the given integer
int, int)
positions with the new string
Adding TextArea Component
The following code is used to create a TextArea component and add it to an applet
window:
TextArea t = new TextArea(5,20);
add(t);
Example: Using TextArea Component
/* TextAreaDemo.java */
import java.awt.*;
import java.awt.*;
import java.applet.*;
Push buttons
The Button component is a rectangular button that can be clicked with a mouse.
Action
Button()
Button(String)
Action
getLabel()
setLabel(string)
setEnable(boolean)
import java.awt.*;
import java.awt.*;
import java.applet.*;
add(b1);
add(b2);
}
public boolean action(Event evt, Object arg)
{
if(evt.target.equals(b1))
getAppletContext().showStatus(Button 1);
else if(evt.target.equals(b2))
getAppletContext().showStatus(Button 2);
// Let the base class handle it:
else
return super.action(evt, arg);
return true; // Weve handled it here
}
}
Output:
Button1 Clicked
Button2 Clicked
Check boxes
The Checkbox class is used to display checkbox controls. The checkbox has a label to
indicate its meaning. Checkbox component is toggle box that can be either selected or
Action
Checkbox()
Checkbox
(String)
Checkbox(String,
null, boolean)
Action
getLabel()
setLabel(String)
getState()
setState(boolean)
import java.awt.*;
import java.applet.*;
Output:
CheckboxGroup
To create a group of checkboxes, you use the CheckboxGroup class. The
CheckboxGroup class is used with the Checkbox class to implement radio buttons. All
Checkbox objects that are associated with a CheckboxGroup object are treated as a single
set of radio buttons. Only one button in the group may be set or on at a given point in
time.
Constructors of CheckboxGroup Component
To create a checkbox, use one of the following constructors:
Constructor
Action
CheckboxGroup()
The
CheckboxGroup
provides
single,
parameterless constructor.
Methods of CheckboxGroup Component
CheckboxGroup class also provides methods for getting and setting the Checkbox
object.
Method
Action
setCheckboxGroup()
setCurrent()
import java.awt.*;
add(c2);
Choice lists
A choice list provides a group of options and enables selection of one at a time. The
Choice class is used to create drop-down lists. From this lists a single choice can be
selected, similar to a group of checkboxes.
Methods of ChoiceList Component
Method
addItem()
getItem(int)
Action
This method is used to build the
choice list.
Returns the string item at the given
position (items inside a choice begin at 0,
just like arrays)
countItems()
getSelectedIndex()
getSelectedItem()
select(int)
select(String)
import java.awt.*;
public void init()
{
Choice c = new Choice();
c.addItem(Apples);
c.addItem(Oranges);
c.addItem(Strawberries);
c.addItem(Blueberries);
c.addItem(Bananas);
add(c);
}
}
Output:
Lists
The List component is a scrolling list of strings from which one or more strings can be
selected. The List class is use for creating single- and multiple-selection list GUI. The List
class provides facility to set display size (number of elements) and also allow selecting
multiple items from the list.
Constructors of List Component
Action
List()
List(int,
boolean)
Action
addItem()
getItem(int)
countItems()
getSelectedIndex()
getSelectedIndexes()
getSelectedItem()
getSelectedItems()
select(int)
select(String)
import java.awt.*;
import java.applet.Applet;
lst.addItem(CDR);
lst.addItem(CDRW);
lst.addItem(DVD);
lst.addItem(PenDrive);
lst.addItem(FloppyDisk);
lst.addItem(Zipdrive);
lst.addItem(ROM);
add(lst);
}
}
Output:
Menus
A Menu is a component of AWT but it is different from other components because it
cant be added to ordinary container and laid out by layout manager. Menu can be added
only to a menu container. A top-level window can have menu bar, which displays a list of
top - level menu choices and each choice is associated with a drop-down menu.
MenuComponent hierarchy
MenuBar
A menu bar is the first building block of a menu. First create a menu bar, then position
it on a frame. The menus are added to the menu bar just like a button or any component is
added to a container. In this case, the menu bar is like the container.
E.g.,myMenuBar.add(myEditMenu); adds a menu object called myEditMenu to the
menu bar.
It can only be added to a Frame object. A frame can display only one MenuBar at a
time. The MenuBar does not support any listener.
Constructor of Menubar
Constructor
MenuBar( )
Action
To create a
default menu bar.
Menu
A Menu component provides a basic pull-down menu. A Menu object is a drop-down
menu component that is deployed from a menu bar. It can be added either to a MenuBar or
to another Menu. Menus are used to display and control menu items.
Constructor of Menu
Constructor
Action
Menu( )
Menu( String
boolean flag)
MenuItem
MenuItem component are the text leaf nodes of a menu tree. MenuItems are added to a
Menu.
An ActionListener can be added to a MenuItem object.
Constructor of MenuItem
Constructor
Action
MenuItem( )
MenuItem(
String
MenuShortcut key)
str,
CheckboxMenuItem
CheckboxMenuItem is checkable menu item, which provides selection (on or off )
listed in menus.
CheckboxMenuItem can be controlled by the ItemListener interface. The
itemStateChanged( ) method is called, when the checkbox state is modified.
Constructor of CheckboxMenuItem
Constructor
Action
CheckboxMenuItem( )
To
create
default
CheckBoxMenuItem.
CheckboxMenuItem(
String str )
CheckboxMenuItem(
String str, boolean flag )
Methods of Menu
Following are some common methods, which are used while creating a menu.
Method
Action
isEnabled( )
String getLabel( )
boolean getState( )
add(MenuItem mi)
add(String label)
addSeparator()
getItem(int index)
getItemCount()
insert(MenuItem
item, int index)
menu
insertSeparator(int index)
remove(MenuComponent
This method remove menu item from
item)
menu.
remove(int index)
removeAll()
Menu fileMenu = new Menu(File);
myMenuBar.add(fileMenu);
Menu editMenu = new Menu(Edit);
myMenuBar.add(editMenu);
myFrame.setVisible(true);
}
public class Terminator
extends WindowAdapter
{
public void windowClosing(WindowEvent e)
{
myFrame.dispose();
// use System.exit(0) for applications
}
}
}
Output:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
add(myTextField);
myFrame.setBounds(200,200,300,300);
// place myMenuBar at top of myFrame
MenuBar myMenuBar = new MenuBar();
myFrame.setMenuBar(myMenuBar);
Menu fileMenu = new Menu(File);
myMenuBar.add(fileMenu);
Menu editMenu = new Menu(Edit);
myMenuBar.add(editMenu);
MenuItem myMenuItem;
myMenuItem = new MenuItem(Open);
myMenuItem.addActionListener(this);
fileMenu.add(myMenuItem);
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() instanceof MenuItem)
myTextField.setText(Your Choice:
+ e.getActionCommand());
}
public class Terminator
extends WindowAdapter
{
public void windowClosing(WindowEvent e)
{
myFrame.dispose();
// use System.exit(0) for applications
}
}
}
Output:
{
if (Quit.equals (o))
{
dispose();
System.exit(1);
}
else
{
System.out.println (User selected + o);
if (e.target instanceof CheckboxMenuItem) {
CheckboxMenuItem cb = (CheckboxMenuItem)e.target;
System.out.println (The value is: + cb.getState());
}
}
return true;
}
return false;
}
public static void main (String []args)
{
MenuTest f = new MenuTest ();
f.show();
}
Output:
Popup Menu
Example: Creating Popup Menu
/* PopupTest.java*/
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
mi.addActionListener (this);
popup.add(mi = new MenuItem (Paste));
mi.addActionListener (this);
popup.add(mi = new MenuItem(Delete)).setEnabled(false);
mi.addActionListener (this);
popup.addSeparator();
popup.add(mi = new MenuItem (Select All));
mi.addActionListener (this);
add (popup);
resize(200, 200);
enableEvents (AWTEvent.MOUSE_EVENT_MASK);
}
protected void processMouseEvent (MouseEvent e)
{
if (e.isPopupTrigger())
popup.show(e.getComponent(), e.getX(), e.getY());
super.processMouseEvent (e);
}
public void actionPerformed(ActionEvent e) {
System.out.println (e);
}
}
Output:
Before Click
Layout Managers
Layout Managers apply to all AWT containers. Java uses layout managers to arrange
components inside containers.
Every container has a default layout manager that determines the sizes and
positions of components within the container.
One reason that Java uses layout managers is so that containers can be resized
gracefully.
Layout Manager Classes
Some possible Layout Managers are listed in the table below, along with the constants
defined for each one the constants are usually used to position components in the
container. The java.awt package provides five layout manager classes
Layout
Manager
Description
Constants/Methods/Constructors
BorderLayout
Arranges
NORTH,
SOUTH,
components to the top, EAST,WEST,CENTER positions in
bottom, left, right, and the container
center of a container.
FlowLayout
Arranges
components
in
GridLayout
CardLayout
Displays
one
addLayoutComponent
(String
GridLayout
BorderLayout
CardLayout
Flow Layout
FlowLayout arranges swing components from left to right until theres no more space
available. Then it begins a new row below it and moves from left to right again. Each
component in a FlowLayout gets as much space as it needs and no more.
setLayout() method is used to for a container to use the FlowLayout manager as
follows:
setLayout( new FlowLayout() );
When there are too many components to fit, they wrap to a new row, similar to a
word processor with word wrap enabled.
Setting FlowLayout Alignment
You can change the alignment of a FlowLayout in the constructor. To do this just pass
one of the defined constants FlowLayout.LEFT, FlowLayout.RIGHT or
FlowLayout.CENTER to the constructor, e.g.
setLayout(new FlowLayout(FlowLayout.LEFT));
setLayout(new FlowLayout(FlowLayout.RIGHT));
setLayout(new FlowLayout(FlowLayout.CENTER));
Example: Using FlowLayout
/*FlowLayoytTest.java*/
import java.awt.*;
import java.applet.*;
After Resize
setLayout(new
FlowLayout(FlowLayout.LEFT));
setLayout(new
FlowLayout(FlowLayout.RIGHT));
setLayout(new
FlowLayout(FlowLayout.CENTER));
Border Layout
BorderLayout places swing components in the North, South, East, West and center of a
container. All extra space is placed in the center area. You can add horizontal and vertical
gaps between the areas. The BorderLayout is the default layout manager for all Window,
Dialog, and Frame classes.
NORTH
SOUTH
WEST
WEST
CENTER
East, West, or Center. This parameter specifies the location in the border layout for the
component.
Example: Using BorderLayout without location.
/**
* BorderLayoutTest.java
*/
import java.awt.*;
import java.applet.*;
After Resize
import java.awt.*;
import java.applet.*;
}
Output:
Before Resize
After Resize
Grid Layout
GridLayout is a layout manager arranges components in a rectangular grid inside the
container. The container is divided into equal-sized rectangles, and one component is
placed in each rectangle. The grid is given specific dimensions when created. Components
added to the container with the GridLayout manager are arranged in order from left to
right.
Component
1
Component
2
Component
4
Component
5
Component
Component
Component
6
7
This is similar to the way components are added with the FlowLayout manager, but
with GridLayout, components are given equal amounts of space in the container. The
components are resized to fill the grid cell, if possible. GridLayout can reposition or resize
objects after adding or removing components. Whenever the area is resized, the
components within it are resized.
The only parameter used with the add() method is the name of the object to add. The
GridLayout is widely used for arranging components in rows and columns. New rows are
added as neededif you create a three-by-three grid and add a tenth item, a fourth row is
added.
Example: Using GridLayout Manager
/*GridLayoutTest.java*/
import java.awt.*;
import java.applet.*;
After Resize
You can observe that the size of the buttons is changed to fit the area.
Card Layout
The CardLayout class is a special type of layout organizer. The CardLayout manager
treats each component in the container as a card. Only one card is visible at a time. All the
components are given the same size. Usually, the CardLayout manages a group of Panels
(or some other container), and each Panel contains several components of its own. Instead
of displaying several panels concurrently, it creates a stack of panels that can then be
displayed one at a time, much like the stack of cards in the Solitaire game. You can use the
CardLayout to create tab control for GUI.
With CardLayout we can assign names to the components and jump to a component by
name. We can also cycle through components in order.
The CardLayout class has its own group of methods that are used to control which
panel is displayed.
Following example uses a series of panels with different-colored canvases to illustrate
the CardLayout class.
Clicking on the applet area causes the layout manager to load the next panel.
If the last panel is already loaded, the CardLayout manager automatically returns to
the first panel.
Example: Using CardLayout
/*CardLayoutTest.java */
import java.awt.*;
import java.applet.*;
Output:
Before Resize
After Resize
canvasCards.setLayout( cardDeck );
c1.setBackground(Color.black);
c2.setBackground(Color.red);
c3.setBackground(Color.green);
p1.add(Center, c1);
p2.add(Center, c2);
p3.add(Center, c3);
canvasCards.add(p1, p1);
canvasCards.add(p2, p2);
canvasCards.add(p3, p3);
setLayout(new BorderLayout());
add(Center, canvasCards);
}
}
}
Output:
First Click (black)
The user interacts with the event source object (such as Button and Textfield). Upon
triggered, it creates an event object. This event object will be messaged to all
the registered listener object(s), and an appropriate event-handler method of the listener(s)
is called-back to provide the response. In other words, triggering a source fires an event to
its entire listener, and invokes an appropriate handler of the listener(s).
To express interest for a certain sources event, the listener(s) must be registered with
the source. In other words, the listener(s) subscribes to a sources event, and the source
publishes the event to all its subscribers upon activation. This is known as subscribepublish or observable-observer design pattern.
Event loop
When you run your Java program, it cycles around in a loop waiting for an event to
occur.
In Java, we create sections of code (methods) that the Java applet will automatically
execute when an event happens. Within these event handling methods we can check
what event has occurred and ensure the required processing takes place. In this program
we will listen for a button press as the event.
ContainerEvent
Adding/removing component
FocusEvent
Getting/losing focus
KeyEvent
MouseEvent
WindowEvent
For instance, typing the letter A on the keyboard generates three events, one for
pressing, one for releasing, and one for typing. Depending upon your interests, you can do
something for any of the three events.
Semantic Events
Semantic events represent interaction with a GUI component; for instance selecting a
button, or changing the text of a text field. Which components generate which events is
shown in the next section.
ActionEvent
Do the command
AdjustmentEvent
Value adjusted
ItemEvent
State changed
TextEvent
Text changed
Event Sources
The following table represents the different event sources. Keep in mind the object
hierarchy. For instance, when Component is an event source for something, so are all its
subclasses:
Semantic Events
Button
List
MenuItem
ActionListener
TextField
Choice
Checkbox
Checkbox
CheckboxMenuItem
List
Scrollbar
AdjustmentListener
TextArea
TextListener
TextField
Low-Level Events
Component
ItemListener
ComponentListener
FocusListener
KeyListener
MouseListener
MouseMotionListener
Container
ContainerListener
Window
WindowListener
Notice that although there is only one MouseEvent class, the listeners are spread
across two interfaces. This is for performance issues. Since motion mouse events are
generated more frequently, if you have no interest in them, you can ignore them more
easily, without the performance hit.
Event Classe
Description
Listener Interface
ActionEvent
ActionListener
MouseListener
KeyEvent
KeyListener
ItemEvent
ItemListener
TextEvent
TextListener
MouseWheelEvent
Generated when
wheel is moved
MouseWheelListener
WindowEvent
mouse
WindowListener
ComponentEventListener
ContainerEvent
ContainerListener
AdjustmentEvent
AdjustmentListener
manipulated
FocusEvent
FocusListener
Method
Descritpion
String
getActionCommand()
int getModifiers( )
AdjustmentEvent
adjustable
getAdjustable( )
ComponentEvent
int
getAdjustmentType( )
Component
getComponent()
ContainerEvent
Container
getContainer( )
boolean isTemporary(
boolean isAltDown( )
)
InputEvent
boolean
isControlDown( )
boolean isShiftDown(
object getItem( )
ItemSelectable
getItemSelectable( )
ItemEvent
Component getChild(
)
FocusEvent
event.
int getStateChange( )
KeyEvent
char getKeyChar( )
int getKeyCode( )
MouseEvent
WindowEvent
Point getPoint( )
int getClickCount( )
Window getWindow( )
Event Source
A source is an object that generates an event
Event generation occurs when internal state of that object changes in some way
A source must register listeners in order for the listeners to receive the
notifications about a specific type of events
Event
Description
Source
Button
Checkbox
Choice
List
Generates ActionEvent when an item is doubleclicked; generates ItemEvent when an item is selected or
deselected
Menu Item
Scroll bar
Text
Component
Window
Sources of Events
Following is the list of AWT component and the events that can be generated by them
Listener
Methods Provided
Description
Interface
ActionListener
AdjustmentListener
actionPerformed(ActionEvent ae)
adjustmentValueChanged
(AdjustementEvent ae)
Defines one
method to receive
ActionEvent
Defines one
method to receive
AdjustementEvent
ComponentListener
componentResized(ComponentEvent
Defines four
ce)
methods
to
componentMoved(ComponentEvent ce) recognize when a
component
is
componentShown(ComponentEvent ce) hidden, moved,
componentHidden(ComponentEvent ce) resized, or shown
ContainerListener
componentAdded(ContainerEvent ce)
two
componentRemoved(ContainerEvent
methods
to
recognize when a
component
is
added to or
removed from a
container
focusGained(FocusEvent fe)
Defines two
methods
to
recognize when a
component gains
ce)
FocusListener
Defines
focusLost(FocusEvent fe)
or loses keyboard
focus
ItemListener
itemStateChanged(ItemEvent ie)
Defines
method
one
to
recognize when
the state of an
item changes
KeyListener
keyPressed(KeyEvent ke)
keyReleased(KeyEvent ke)
keyTyped(KeyEvent ke)
MouseListener
mouseClicked(MouseEvent me)
mouseEntered(MouseEvent me)
mouseExited(MouseEvent me)
mousePressed(MouseEvent me)
mouseReleased(MouseEvent me)
MouseMotionListener
mouseDragged(MouseEvent me)
mouseMoved(MouseEvent me)
Defines three
methods
to
recognize when a
key is pressed,
released or typed
Defines five
methods
to
recognize when
mouse is clicked,
enters
a
component, exits
a component, is
pressed or is
released
Defines two
methods
to
recognize when
the mouse is
dragged
or
moved.
MouseWheelListener
TextListener
mouseWheelMoved(MouseWheenEvent
Defines one
me)
method
to
recognize when
the mouse wheel
is moved
textChanged(TextEvent te)
Defines
method
one
to
recognize when a
text value changes
WindowFocusListener
windowGainedFocus(WindowEvent
we)
windowLostFocus(WindowEvent we)
Defines two
methods
to
recognize when a
window gains or
loses input focus
WindowListener
windowActivated(WindowEvent we)
windowClosed(WindowEvent we)
windowClosing(WindowEvent we)
windowDeactivated(WindowEvent we)
windowDeiconified(WindowEvent we)
windowIconified(WindowEvent we)
windowOpened(WindowEvent we)
Defines seven
methods
to
recognize when a
window
is
activated, closed,
deactivated,
deiconified,,
iconified, opened
or quit
AdjustmentEvent
ItemEvent
Event Source
Button, List, MenuItem,
TextField
Scrollbar
Choice,
Checkbox,
CheckboxMenuItem, List
AdjustmentListener
ItemListener
TextEvent
TextArea, TextField
TextListener
ComponentEvent
Component
ComponentListener
ContainerEvent
Container
ContainerListener
FocusEvent
Component
FocusListener
KeyEvent
Component
KeyListener
MouseEvent
Component
WindowEvent
Window
MouseListener,
MouseMotionListener
WindowListener
String
getActionCommand()
Description
Description
}
@Override
public void actionPerformed(ActionEvent ae){
if(this.getExtendedState()==Frame.NORMAL)
setExtendedState(Frame.MAXIMIZED_BOTH);
else if(this.getExtendedState()==Frame.MAXIMIZED_BOTH)
setExtendedState(Frame.NORMAL);
}
public static void main(String args[])
{
new ActionEventDemo();
}
}
Output
Description
getClickCount()
getPoint()
getX()
getY()
Description
mousePressed
(MouseEvent
event)
void
mouseReleased
(MouseEvent
event)
void
mouseEntered
(MouseEvent
event)
void
mouseExited
(MouseEvent
event)
void
mouseClicked
(MouseEvent
event)
In this example, we setup a GUI with 4 components (two Labels and two noneditable TextFields), inside a top-level container Frame, arranged in FlowLayout.
To demonstrate the MouseEvent:
1. We use Frame as the source object.
2. The Frame fires a MouseEvent to its entire MouseEvent listener when you
click/press/release a mouse-button or enter/exit with the mouse-pointer.
3. We select this object as the MouseEvent listener (for simplicity).
4. We register this object as the MouseEvent listener to super Frame (source) via
the method addMouseListener(this).
5. The listener (this class) is required to implement the MouseListener interface,
which declares 5 abstract methods. We override the mouseClicked() to display
the (x, y) co-ordinates of the mouse click on the two displayed TextFields.
MouseEvent and MouseMotionListener Interface
A MouseEvent is also fired when you moved and dragged the mouse pointer at the
source object. But you need to use MouseMotionListener to handle the mouse-move and
mouse-drag. TheMouseMotionListener interface declares the following two abstract
methods:
MouseMotionListener
Method
Description
void
mouseMoved
Invoked when the mouse is moved but no
(MouseEvent event)
buttons on the mouse have been pressed
void
mouseDragged
Invoked when the mouse has been moved
(MouseEvent event)
while a button is pressed (i.e. click and drag of
the mouse)
Example: Using MouseEvent and MouseListener
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
public class MouseMotionDemo extends Frame
implements MouseListener, MouseMotionListener {
// This class acts as MouseListener and MouseMotionListener
// To display the (x, y) coordinates of the mouse-clicked
private TextField tx;
private TextField ty;
// To display the (x, y) coordinates of the current mouse position
private TextField xpos;
private TextField ypos;
public MouseMotionDemo() {
setLayout(new FlowLayout());
add(new Label(X Co-Ordinate: ));
tx = new TextField(10);
tx.setEditable(false);
add(tx);
add(new Label(Y Co-Ordinate: ));
ty = new TextField(10);
ty.setEditable(false);
add(ty);
add(new Label(X Position: ));
In this example:
Description
void
public
void
keyPressed(KeyEvent e)
public
void
keyReleased(KeyEvent e)
Example: Using KeyEvent and KeyListener
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class KeyEventDemo extends Frame implements KeyListener {
// This class acts as KeyEvent Listener
private TextField Input;
private TextArea Display;
public KeyEventDemo() {
setLayout(new FlowLayout());
In this example:
We use the Input (TextField) as the source object.
The source fires a KeyEvent when you press/release/type a key to all
its KeyEvent listener(s).
We select this object as the KeyEvent listener.
We register this object as the KeyEvent listener to the source TextField via
method Input.addKeyListener(this).
The KeyEvent listener (this class) needs to implement
the
KeyListener
interface,
which
declares
3
abstract
methods: keyTyped(), keyPressed(), keyReleased().
We override the keyTyped() to display key typed on the display TextArea. We
ignore the keyPressed() and keyReleased().
Window Event and Window Listener Interface
This is an interface in the java.awt.event package that specify the methods for
controlling a particular window. It has the following method specifications:
Method
Purpose
windowActivated(WindowEvent
windowClosed(WindowEvent e)
windowClosing(WindowEvent e)
e)
windowDeactivated(WindowEvent
windowDeiconified(WindowEvent
windowIconified(WindowEvent e)
windowOpened(WindowEvent e)
e)
e)
import java.awt.*;
import java.awt.event.*;
class WindowEventDemo extends Frame
{
public WindowEventDemo()
{
// Set the frame properties
setTitle(Button with ActionListener Demo);
setSize(400,400);
setLayout(new FlowLayout());
setLocationRelativeTo(null);
setVisible(true);
// Add window listener
addWindowListener(new WindowListener(){
public void windowOpened(WindowEvent we)
{
System.out.println(Window Opened);
}
public void windowClosing(WindowEvent we)
{
System.out.println(Window Closing);
System.exit(0);
}
public void windowClosed(WindowEvent we)
{
// Will not be printed
System.out.println(Window Closed);
}
public void windowIconified(WindowEvent we)
{
setTitle(Iconified);
}
public void windowDeiconified(WindowEvent we)
{
setTitle(Deiconified);
}
public void windowActivated(WindowEvent we)
{
System.out.println(Window Activated);
}
public void windowDeactivated(WindowEvent we)
{
System.out.println(Window Deactivated);
}
});
}
public static void main(String args[])
{
new WindowEventDemo();
}
}
Output:
Swing API is set of extensible GUI Components to ease developers life to create
JAVA based Front End/ GUI Applications. It is build upon top of AWT API and acts as
replacement of AWT API as it has almost every control corresponding to AWT controls.
Swing component follows a Model-View-Controller architecture to fulfill the following
criterias.
A single API is to be sufficient to support multiple look and feels.
API is to model driven so that highest level API is not required to have the
data.
API is to use the Java Bean model so that Builder Tools and IDE can provide
better services to the developers to use it.
Swing features
Light Weight - Swing component are independent of native Operating
Systems API as Swing API controls are rendered mostly using pure JAVA code
instead of underlying operating system calls.
Rich controls - Swing provides a rich set of advanced controls like Tree,
TabbedPane, slider, colorpicker, table controls
Highly Customizable - Swing controls can be customized in very easy way as
visual apperance is independent of internal representation.
Pluggable look-and-feel- SWING based GUI Application look and feel can be
changed at run time based on available values.
Swing Package Overview
javax.swing
javax.swing.border
javax.swing.colorchooser
javax.swing.event
.
javax.swing.filechooser
javax.swing.plaf.*
javax.swing.table
javax.swing.text
.
javax.swing.text.html.*
javax.swing.text.rtf
javax.swing.tree
javax.swing.undo
.
javax.accessibility
Swing classes.
Swing Controls
Every user interface considers the following three main aspects:
UI elements: Core visual elements user interacts with.
Layouts: They define how UI elements should be organized on the screen and
provide a final look and feel to the GUI (Graphical User Interface).
Behavior: These are events which occur when the user interacts with UI
elements.
The Swing set includes
JButton
JDesktopPane
JInternalFrame
JMenuIte
JCheckbox
JDialog
JLabel
JOptionP
JCheckboxMenuItem
JDirectoryPane
JLayeredPane
JPanel
JColorChooser
JEditorPane
JList
JPasswor
JComboBox
JFileChooser
JMenu
JPopupM
JDesktopIcon
JFrame
JMenuBar
JProgress
JRadioButton
JSlider
JTextPane
JWindow
JRadioButtonMenuItem
JSplitPane
JToggleButton
JRootPane
JTabbedPane
JToolBar
JScrollBar
JTable
JToolTip
JScrollPane
JTextArea
JTree
JSeparator
JTextField
JViewport
Components Hierarchy
Jcomponent
Swing components are implemented as subclasses of the JComponent class, which
inherits from the Container class. Swing components inherit the following functionality
from JComponent:
Tool Tips -By specifying a string with the setToolTipText( ) method, you can
provide help to users of a component. When the cursor pauses over the
component, the specified string is displayed in small window that appears near
the component.
Look and Feel -Subject to the security restrictions, you can choose the look and
feel used by all Swing components by invoking the
UIManager.setLookAndFeel( ) method.
Borders -Using the setBorder() method, you can specify the border that a
component displays around its edges.
JFrame
The JFrame class is an extension to the AWT Frame class. An instance of the JFrame
class is a heavyweight component. It creates a top-level window that can be positioned
and sized independently of other windows. The JFrame instance is managed by the system
window manager.
To create an instance of a JFrame class, you can write:
JFrame frame=new JFrame (My Frame);
frame.setSize(300,300); // to give size to a frame
gr.setColor( Color.black );
gr.fillRect( 0, 0, 150, 150 );
}
}
Output:
JFrame
JFrame is the Swing equivalent of AWT Frame. It adds double buffering to avoid
flickering during drawing.
It has a slightly different interface to geometry management - things are added to a
contentPane. It can hold a JMenuBar.
Example: Using JFrame
import javax.swing.*;
public class JFrameDemo extends JFrame {
public static void main(String argv[])
{
new JFrameDemo();
}
JFrameDemo() {
JLabel hello = new JLabel(Hello World);
getContentPane().add(hello, Center);
setSize(200, 200);
setTitle(JFrame Demo);
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
setVisible(true);
}
}
Output:
JLabel
A JLabel is a single line label similar to java.awt.Label. Additional functionality that a
JLabel has the ability to:
Add an Icon
Set the vertical and horizontal position of text relative to the Icon
Set the relative position of contents within component
Constructor:
JLabel(String text, int horizontalAlignment): Creates a JLabel instance with
the specified text and horizontal alignment.
Example: Using JLabel with Frame Container
import javax.swing.*;
import java.awt.*;
public class JLabelDemo extends JFrame {
public JLabelDemo(String title ) {
super( title );
}
Output
fancyLabel.setHorizontalAlignment(JLabel.RIGHT);
// Add to JApplet
add(fancyLabel);
}
}
Output
JButton
A JButton can be used in a GUI just like a java.awt.Button. It behaves like an AWT
1.1 Button, notifying ActionListener list elements when pushed.
JButtons can have an image and/or text label with controllable placement
Constructor:
JButton(): creates a button with no text and icon.
JButton(String s): creates a button with the specified text.
JButton(Icon i): creates a button with the specified icon object.
Example: Using JButton
import javax.swing.*;
import java.awt.*;
public class JButtonDemo extends JFrame {
public JButtonDemo(String title) {
super(title);
setLayout(new GridLayout(3, 2));
JTextField
The class JTextField is a component which allows the editing of a single line of text.
JTextField(String text, int columns): Constructs a new TextField initialized
with the specified text and columns.
Example: Using JTextField
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SwingTextDemo extends JFrame {
f.getContentPane().setLayout(new FlowLayout());
f.getContentPane().add(new JTextField(Hello));
f.getContentPane().add(new JTextField(How r U?, 8));
JTextField t = new JTextField(8);
t.setHorizontalAlignment(JTextField.RIGHT);
t.setText(Name Please!);
f.getContentPane().add(t);
t = new JTextField(, 15);
t.setHorizontalAlignment(JTextField.CENTER);
f.getContentPane().
add(t);
f.pack();
f.setVisible(true);
}
}
Output:
JCheckBox
A JCheckBox is similar to an AWT Checkbox that is not in a CheckboxGroup. The
class JCheckBox is an implementation of a check box - an item that can be selected or
deselected, and which displays its state to the user.
JCheckBox(String text, Icon icon, boolean selected) : Creates a check box
with text and icon, and specifies whether or not it is initially selected.
Example: Using JCheckbox
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*<applet code= CheckboxDemo.class width=200 height=150></applet>*/
public class CheckboxDemo extends JApplet {
public CheckboxDemo () {
ob.setVisible( true );
}
}
class ToggleIcon implements Icon {
boolean state;
public ToggleIcon (boolean s) {
state = s;
}
public void paintIcon (Component c, Graphics g, int x, int y) {
int width = getIconWidth();
int height = getIconHeight();
g.setColor (Color.black);
if (state)
g.fillRect (x, y, width, height);
else
g.drawRect (x, y, width, height);
}
public int getIconWidth() {
return 10;
}
public int getIconHeight() {
return 10;
}
}
Output:
JRadioButton class
The JRadioButton class is used to create a radio button. It is used to choose one option
from multiple options. It is widely used in exam systems or quiz.
It should be added in ButtonGroup to select one radio button only.
Constructors:
JRadioButton(): creates an unselected radio button with no text.
JRadioButton(String s): creates an unselected radio button with specified
text.
JRadioButton(String s, boolean selected): creates a radio button with the
specified text and selected status.
Example: Using JRadioButton
import javax.swing.*;
import java.awt.*;
public class RadioButtonDemo extends JFrame {
// Instantiate a ButtonGroup
ButtonGroup rbg = new ButtonGroup();
}
Output:
JComboBox
The JComboBox class is used to create the combobox (drop-down list). At a time only
one item can be selected from the item list. The JComboBox offers an editable option. You
can offer a JComboBox with a list of default choices, but still permit the entry of another
value. The nicest part about this control is that when the user presses the key for the first
letter of an entry, it changes the highlighted selection.
Example: Using JComboBox
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ComboBoxDemo extends JFrame {
String Seasons[] = {Winter, Summer, Monsoon};
public ComboBoxDemo(String title) {
super(title);
setLayout(new GridLayout(3, 2));
JLabel fs=new JLabel(Select your favorite season?);
JComboBox s = new JComboBox();
for (int i=0;i<Seasons.length;i++) {
s.addItem (Seasons[i]);
}
s.setEditable(false);
s.setSelectedItem(Monsoon);
s.setMaximumRowCount(4);
add(fs);
add(s);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main ( String[] args )
{
ComboBoxDemo ob = new ComboBoxDemo(JComboBox Demo) ;
ob.setSize( 300, 100 );
ob.setVisible( true );
}
}
Output:
Menus
The menuing model used in Swing is nearly identical to that used in AWT. There are
three key exceptions:
The menu classes (JMenuItem, JCheckBoxMenuItem, JMenu, and JMenuBar)
are all subclasses of JComponent. They are not off in their own independent
class hierarchy. As a result of this, you can place a JMenuBar within any
Container, including Applet. [The JApplet class has a setJMenuBar() method to
add a JMenuBar.]
There is a new menu class, JRadioButtonMenuItem, to provide a set of
mutually exclusive checkboxes on a menu, when placed within a ButtonGroup.
public JMenuDemo() {
super (JMenu Demo);
setJMenuBar (jmb);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main ( String[] args )
{
JMenuDemo ob = new JMenuDemo() ;
ob.setSize( 300, 100 );
ob.setVisible( true );
}
}
Output:
First Menu
Second Menu
Third Menu
A layout manager organizes the objects in a container. Different layouts are used to
organize or to arrange objects
Border Layout:
It has five areas for holding components: north, east, west, south and center
When there are only 5 elements to be placed, border layout is the right choice
Flow Layout:
Default layout manager.
It lays out the components from left to right
Card Layout:
Different components at different times are laid out
Controlled by a combo box, determining which panel the Card layout displays
Grid Layout:
A group of components are laid out I equal size and displays them in certain
rows and columns
What is the difference between GridLayout & GridBagLayout manager?
GridLayout class lays all components in a rectangular grid like structure of container.
The container is divided into an equal sized rectangles and each component is placed
inside a rectangle.
The GridBagLayout class is a flexible layout manager that aligns components
vertically and horizontally, without requiring that the components be of the same size.
Each GridBagLayout object maintains a dynamic, rectangular grid of cells, with each
component occupying one or more cells, called its display area.
Each component managed by a GridBagLayout is associated with an instance of
GridBagConstraints. The constraints object specifies where a components display area
should be located on the grid and how the component should be positioned within its
display area. In addition to its constraints object, the GridBagLayout also considers each
components minimum and preferred sizes in order to determine a components size.
Exercise
1. Write short note:- Awt packge
2. Explain AWT? Write steps for creating list, checkbox, label, Text field and Text
area.
3. Lists containers and suggest where we have to use which container.
4. Explain layout manager in brief.
5. Explain panel & canvas in java.
6. Give difference: Check box & Radio
7. With respect to AWT package explain flow Layout with example.
8. Write a difference between Text field and Text area.
9. With respect to awt package explain Grid Layout with example.
10. Differentiate Between following:
Border layout & flow layout
Check box & radio button
1. Describe mouse listener and mouse events using proper example.
2. What is swing? What is difference between Swing and AWT?
3. Explain any one swing component using example.
Programming Exercise:
1. Develop an applet that receive two numeric values as input from the user and
display the addition & multiplication of these two nos.
2. Develop an applet that receives three numeric values from the user and then
displays the largest of the three on the screen. Write a HTML page and test the
applet.
3. Write a program to demonstrate background color of an applet. Take four radio
buttons of different colors to select a color.
4. Develop an applet that receives three numeric values as input from the user
And then display the largest of three on the screen.
5. Develope an applet that receive one string and display in reverse fashion (e.g.
Hellow should be display Wolleh). Write HTML page and test the applet.
6. Write an applet this display a string. Write necessary applet tag for
it.
7. Devlope an applet that receives two numbers from the user to perform +, -, *, /
operation write the HTML code and test the applet.
JDBC Architecture
The JDBC Architecture consists of two layers:
The JDBC API, which provides the application-to-JDBC Manager connection
The JDBC API uses a driver manager and database-specific drivers to
provide transparent connectivity to different databases.
The JDBC Driver API, which supports the JDBC Manager-to-Driver
Connection
The JDBC driver manager ensures that the correct driver is used to access
each data source. The driver manager is capable of supporting multiple
concurrent drivers connected to multiple different databases.
Two models for database access are supported by the JDBC API. They are the two-tier
model and the three-tier model. The last one is mentioned more generally as a multitier or
n-tier.
The two-tier model
In the two-tier model, a Java applet or application talks directly to the database. This
requires a JDBC driver that can communicate with the particular database management
system (DBMS) being accessed. SQL statements are delivered to the database, and the
results are sent back to the user.
client and the machine housing the database is the server. The database may be located on
another machine to which the user is connected via a network.
The three-tier model
In the three-tier model, commands are sent to a middle tier of services, which then
send SQL statements to the database. The database processes the SQL statements and
sends the results back to the middle tier, which then sends them to the user.
This model makes it possible to maintain control over access and the kinds of updates
that can be made to corporate data. Another advantage of the middle tier model is that the
user can employ an easy-to-use higher-level API which is translated by the middle tier into
the appropriate low-level calls. The middle-tier architecture can provide performance
advantages.
Database vendors support JDBC through the JDBC driver interface or through the
ODBC connection. Each driver must provide implementations of java.sql.Connection,
java.sql.Statement, java.sql.PreparedStatement, java.sql.CallableStatement, and
java.sql.ResultSet. They must also implement the java.sql.Driver interface for use by the
generic java.sql.DriverManager interface.
JDBC API - The JDBC 4.0 APIs come in two packages: java.sql and javax.sql
and these packages contain all the APIs which provide programmatic access to
a relational database (like Oracle, SQL Server, MySQL, etc.) from Java.
Using JDBC API, frontend java applications can execute query and fetch data
from connected databases. JDBC API can also connect with multiple
applications with same database or same application with multiple Databases
which may be residing in different computers (distributed environment).
JDBC Driver Manager - JDBC Driver Manager Interface defines objects
which are used to connect java application with different JDBC Drivers. JDBC
Driver Manager manages the all the JDBC Drivers loaded in clients system.
JDBC Driver Manager loads the most appropriate driver among all the Drivers
for creating a connection. There are two ways of connecting to a database
One, by using the DriverManager class (the traditional way of
establishing connection to a database from Java) and
Second, by using a Data Source. This method requires javax.naming and
javax.sql packages to find a DataSource object registered with JNDI, and
to establish connection using that DataSource object. This is the
recommended approach of establishing connection to a database from
Java.
JDBC Test Suite JDBC Test Suite is used to check compatibility of a JDBC
driver with J2EE platform. It also check whether a Driver follow all the
standard and requirements of J2EE Environment. This suite do contain almost
all the standard test cases required to test the many JDBC features. You may
only need to add the application specific test cases.
JDBC-ODBC Bridge - as the name suggests this enables JDBC access via
ODBC drivers. Though this is normally used only for development and testing
purposes and not for production use. The JDBC Driver contact to the ODBC
Driver for connection to the database. The ODBC Driver is already installed or
come as default driver in windows. In Windows using this data source name
(DSN) you can connect JDBC to ODBC.
The JDBC API
JDBC API is a part of the Java platform that has included Java Standard Edition (Java
SE) and the Java Enterprise Edition (Java EE) in itself. The JDBC (Java Database
Connectivity) API defines interfaces and classes for writing database applications in Java
by making database connections. JDBC is a Java API for executing SQL statements.
Using JDBC you can send SQL, PL/SQL statements to almost any relational database.
JDBC is a Java API for executing SQL statements and supports basic SQL functionality. It
provides RDBMS access by allowing you to embed SQL inside Java code. With Java and
the JDBC API, it is possible to publish a web page containing an applet that uses
information obtained from a remote database. Applets embedded in Web pages can
contain downloadable JDBC code to enable remote database access.
The JDBC API can also interact with multiple data sources in a distributed
environment. Due to JDBC API technology, user can also access other tabular data
sources like spreadsheets or flat files even in the heterogeneous environment.
The JDBC API has four main interfaces. The latest version of JDBC 4.0 application
programming interface is divided into two packages
java.sql
javax.sql.
Java SE and Java EE platforms are included in both the packages.
java.sql package
This package includes classes and interface to perform almost all JDBC operation such
as creating and executing SQL Queries.
Important classes and interface of java.sql package
The mechanism to communicate with database servers exists as standard Java classes.
This ensures that the security features of Java remain and that JDBC code integrates
cleanly in Java code. The JDBC API is expressed through several abstract Java interf aces
that allow to link to any number of databases. The interfaces are:
java.sql.DriverManager: handles the loading and unloading of the appropriate
database drivers required to make the connection.
java.sql.Connection: exposes the database to the developer, representing the
connection as an accessible Java component.
java.sql.Statement: provides a container for executing SQL statements using a
connection.
java.sql.ResultSet: exposes the data that returns from the database server to the
Java application.
The JDBC API Components
The JDBC API provides the following interfaces and classes:
DriverManager: This class manages a list of database drivers. Matches
connection requests from the java application with the proper database driver
using communication subprotocol. The first driver that recognizes a certain
subprotocol under JDBC will be used to establish a database Connection.
Driver: This interface handles the communications with the database server.
You will interact directly with Driver objects very rarely. Instead, you use
DriverManager objects, which manage objects of this type. It also abstracts the
details associated with working with Driver objects
Connection: This interface with all methods for contacting a database. The
connection object represents communication context, i.e., all communication
with database is through connection object only.
Statement: You use objects created from this interface to submit the SQL
statements to the database. Some derived interfaces accept parameters in
addition to executing stored procedures.
ResultSet: These objects hold data retrieved from a database after you execute
an SQL query using Statement objects. It acts as an iterator to allow you to
move through its data.
SQLException: This class handles any errors that occur in a database
application.
The JDBC API uses a Driver Manager and database-specific drivers to provide
transparent connectivity to different databases.
The JDBC Driver Manager
The JDBC Driver Manager can connect Java applications to a JDBC driver. Driver
Manager is the backbone of the JDBC architecture. It is quite small and simple. The JDBC
driver manager is used to provide a means of managing the different types of JDBC
database driver running on an application.
The main responsibility of JDBC database driver is to load all the drivers found in
the system properly as well as to select the most appropriate driver from opening a
connection to a database. The Driver Manager also helps to select the most appropriate
driver from the previously loaded drivers when a new open database is connected.
JDBC Driver Manager functionality is available in following two Standard Extension
packages:
javax.naming and
javax.sql
The JDBC Test Suite
The function of JDBC driver test suite is to make ensure that the JDBC drivers will
run users program or not. The test suite of JDBC application program interface is very
useful for testing a driver based on JDBC technology during testing period. It ensures the
requirement of Java Platform Enterprise Edition (J2EE).
JDBC Drivers
JDBC Driver is a software component that enables java application to interact with the
database. JDBC drivers have a specific purpose and properties of its own. There are four
types of JDBC drivers available:
Once your database engine is installed and your database is all set up, you will
need a JDBC driver for that database engine.
The more commercial database engines like Oracle have commercial JDBC
drivers.
Most of them, however, allow you to have a free trial period for experimenting
with the driver.
Follow the install instructions for the driver you choose, and remember that
some JDBC drivers require to you install native code on client machines.
To help you understand what different drivers require, the following driver
categorization system id defined:
Type 1: JDBC-ODBC Bridge driver (Bridge)
Type 2: Native-API/partly Java driver (Native)
Type 3: All Java/Net-protocol driver (Middleware)
Type 4: All Java/Native-protocol driver (Pure)
Two
Two
Driver
mechanism
JDBC-ODBC
Description
Three
Native protocol
The driver does not require anything and
- Pure Java Drivers directly calls the database. This driver is the
fastest among all the four drivers. This driver is
pure java driver. This driver is convert JDBC
commands.
Advantage
Easy to use
Allow easy connectivity to all database supported by the ODBC Driver.
Disadvantage
Advantage
Faster as compared to Type-1 Driver
Contains additional features.
Disadvantage
Requires native library
Increased cost of Application
Type-3 (JDBC-Net Pure Java Drivers)
Type 3 drivers provide a client with a generic network API that is then
translated into database specific access at the server level.
In other words, the JDBC driver on the client uses sockets to call a
middleware application on the server that translates the client requests into
an API specific to the desired driver.
As it turns out, this kind of driver is extremely flexible since it requires no
code installed on the client and a single driver can actually provide access to
multiple databases.
Advantage
Does not require any native library to be installed.
Database Independency.
Provide facility to switch over from one database to another database.
Disadvantage
Slow due to increase number of network call.
Type-4 (Native Protocol Pure Java Driver)
This is Driver called Pure Java Driver because these drivers interact directly with
database. It does not require any native database library, which is why it is also known as
Thin Driver.
Advantage
Does not require any native library.
Does not require any Middleware server.
Better Performance than other driver.
Disadvantage
Slow due to increase number of network call.
MySQL
com.mysql.jdbc.Driver
jdbc:mysql://hostname/databasename
ORACLE
oracle.jdbc.driver.OracleDriver
jdbc:oracle:thin:@hostname:port:databa
DB2
com.ibm.db2.net.DB2Driver
jdbc:db2:hostname:portno/databasenam
Sybase
com.sybase.jdbc.SybDriver
jdbc:Sybase:Tds:hostname/databasenam
MS-
sun.jdbc.odbc.JdbcOdbcDriver
jdbc:odbc:databasename
ACCESS
Example to register the OracleDriver class
Class.forName(oracle.jdbc.driver.OracleDriver);
2) Create the connection object
The getConnection() method of DriverManager class is used to establish connection
with the database.
Syntax of getConnection() method
1) public static Connection getConnection(String url)throws SQLException
Connection c=DriverManager.getConnection(jdbc:oracle:thin:@localhost:1521:xe,system
3) Create the Statement object
The createStatement() method of Connection interface is used to create statement. The
object of statement is responsible to execute queries with the database.
Syntax of createStatement() method
public Statement createStatement()throws SQLException
Example to create the statement object
Statement stmt=con.createStatement();
4) Execute the query
The executeQuery() method of Statement interface is used to execute queries to the
database. This method returns the object of ResultSet that can be used to get all the
records of a table.
Syntax of executeQuery() method
public ResultSet executeQuery(String sql)throws SQLException
Example to execute query
ResultSet rs=stmt.executeQuery(select * from student);
while(rs.next()){
System.out.println(rs.getInt(1)+ +rs.getString(2));
}
5) Close the connection object
By closing connection object statement and ResultSet will be closed automatically.
The close() method of Connection interface is used to close the connection.
Syntax of close() method
public void close()throws SQLException
Example to close connection
con.close();
Connection Class
Methods
Statement createStatement()throws SQLException
Creates a Statement object for sending SQL statements to the
database. SQL statements without parameters are normally executed
using Statement objects.
If the same SQL statement is executed many times, it may be more
efficient to use a PreparedStatement object.
Statement createStatement(int resultSetType,int resultSetConcurrency)
throws SQLException
Creates a Statement object that will generate ResultSet objects with
the given type and concurrency.
type;
one
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.TYPE_SCROLL_SENSITIVE
of
or
Import the packages: Requires that you include the packages containing the
JDBC classes needed for database programming. Most often, using import
java.sql.* will suffice.
Register the JDBC driver: Requires that you initialize a driver so you can
open a communications channel with the database.
Open
a
connection:
Requires
using
the DriverManager.getConnection() method to create a Connection object,
which represents a physical connection with datbase server.
To create a new database, you need not to give any database name while preparing
database URL as mentioned in the below example.
Execute a query: Requires using an object of type Statement for building and
submitting an SQL statement to the database.
Clean up the environment: Requires explicitly closing all database resources
versus relying on the JVMs garbage collection.
Example: Creating new database in MySQL
Copy and past following example in JDBCExampleDB.java, compile and run as
follows:
//STEP 1. Import required packages
import java.sql.*;
// Database credentials
static final String USER = root;
static final String PASS = ;
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println(Goodbye!);
}//end main
}//end JDBCExample
Now let us compile above example as follows:
C:\>javac JDBCExample.java
C:\>
When you run JDBCExample, it produces following result:
C:\>java JDBCExample
Connecting to database
Creating database
Database created successfully
Goodbye!
C:\>
Connecting to MySQL Database using Thin Driver
To connect a Java application with MySQL database using Thin Driver. You need to
follow the following steps
You will also require Username and Password of your MySQL Database Server for
creating connection.
1. Loading jar file: To connect your java application with MySQL, you will also
need to load mysql-connector.jar file.
Download
the
latest
MySQL
JDBC
driver
from http://dev.mysql.com/downloads MySQL Connectors
Connector/J Connector/J 5.1.{XX} select Platform Independent
ZIP Archive (e.g., mysql-connector-java-5.1.{XX}.zip, where {XX} is the
latest release number).
UNZIP the download file into any temporary folder.
Copy the JAR file mysql-connector-java-5.1.{XX}-bin.jar to your
JDKs
Extension
Directory
at
<JAVA_HOME>\jre\lib\ext
(where <JAVA_HOME> is the JDK installed directory, e.g., c:\program
files\java\jdk1.7.0_{XX}\jre\lib\ext).
Set classpath variable to include the location of mysql-connector-java-5.1.
{XX}-bin.jar file.
Set classpath= C:\Program Files\Java\jre1.8.0_25\lib\ext\mysql-connector-java5.1.34-bin.jar;%classpath%;
Example: Using JDBC with MySQL
1) Creating a table in MySQL Using JDBC
import java.sql.*;
// Database credentials
static final String USER = root;
static final String PASS = ;
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
Class.forName(com.mysql.jdbc.Driver);
System.out.println(Connecting to database);
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println(Creating table);
stmt = conn.createStatement();
String sql = CREATE TABLE STUDINFO(rollno int, name varchar(50));;
stmt.executeUpdate(sql);
System.out.println(Table created successfully);
}
catch(SQLException se){
se.printStackTrace();
}
catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}
finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}
catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}
catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println(Goodbye!);
}
}
Output
Connecting to database
Creating table
Table created successfully
Goodbye!
Process completed.
2) Inserting records into a table in MySQL Using JDBC
import java.sql.*;
// Database credentials
static final String USER = root;
static final String PASS = ;
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
Class.forName(com.mysql.jdbc.Driver);
System.out.println(Connecting to database);
conn = DriverManager.getConnection(DB_URL, USER, PASS);
try{
if(conn!=null)
conn.close();
}
catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println(Goodbye!);
}
}
Output:
Connecting to database
Inserting Records into table
Records inserted successfully
Goodbye!
Process completed.
3) Accessing record from Student table in Java application
import java.sql.*;
// Database credentials
static final String USER = root;
static final String PASS = ;
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
Class.forName(com.mysql.jdbc.Driver);
System.out.println(Connecting to database);
conn = DriverManager.getConnection(DB_URL, USER, PASS);
while(rs.next()){
System.out.println(rs.getInt(1)+ +rs.getString(2));
}
finally{
//finally block used to close resources
try{
if(conn!=null)
conn.close();
}
catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println(Goodbye!);
}
}
Output:
Connecting to database
Displaying Records from table
101 Jainik
102 Krinal
Goodbye!
Process completed.
Connecting to Access Database using Type-1 Driver
To connect a Java application with Access database using JDBC-ODBC Bridge(type1) Driver. You need to follow the following steps
Create DSN Name
Go to control panel
Go to Administrative tools
while(rs.next()){
System.out.println(rs.getInt(1)+ +rs.getString(2));
}
con.close(); //closing connection
}catch(Exception e)
{
e.printStackTrace();
}
}
}
Connecting to Oracle Database using Thin Driver
To connect a Java application with Oracle database using Thin Driver. You need to
follow the following steps
1. Load Driver Class: The Driver Class for oracle database is
oracle.jdbc.driver.OracleDriver
and
Class.forName(oracle.jdbc.driver.OracleDriver) method is used to load the
driver class for Oracle database.
2. Create Connection: For creating a connection you will need a Connection
URL. The Connection URL for Oracle is
You will also require Username and Password of your Oracle Database Server for
creating connection.
1. Loading jar file: To connect your java application with Oracle, you will also
need to load ojdbc14.jar file. This file can be loaded into 2 ways.
1. Copy the jar file into C:\Program Files\Java\jre7\lib\ext folder.
or,
1. Set it into classpath.
NOTE: Here we are discussing about Oracle 10g as database. For other version of
Oracle you will be require to do some small changes in the Connection URL.
Security Considerations
There are two main JDBC scenarios to consider for security purposes:
In the case of Java applications, the Java code is trusted. We also consider
trusted applets in this category for security purposes.
In contrast, untrusted Java applets are not permitted access to local files and or
network connections to arbitrary hosts.
Securing JDBC with untrusted applets
JDBC should follow the standard applet security model. Specifically:
JDBC should assume that normal unsigned applets are untrustworthy
JDBC should not allow untrusted applets access to local database data
If a downloaded JDBC Driver registers itself with the JDBC DriverManager,
then JDBC should only use that driver to satisfy connection requests from code
which has been loaded from the same source as the driver.
An untrusted applet will normally only be allowed to open a database
connection back to the server from which it was downloaded
JDBC should avoid making any automatic or implicit use of local credentials
when making connections to remote database servers.
If the JDBC Driver level is completely confident that opening a network connection to
a database server will imply no authentication or power beyond that which would be
obtainable by any random program running on any random internet host, then it may allow
an applet to open such a connection. This will be fairly rare, and would require for
example, that the database server doesnt use IP addresses as a way of restricting access.
These restrictions for untrusted applets are fairly onerous. But they are consistent with
the general applet security model and we can see no good way of relaxing them.
Securing JDBC with Java applications
For a normal Java application (i.e. all Java code other than untrusted applets) JDBC
should happily load drivers from the local classpath and allow the application free access
database
JDBC allows operations on a database, such as creating tables, querying data,
updating data, inserting data from a Java application
The results can be obtained and modified to and from a JDBC application
The metadata of tables can be obtained
Allowing only to navigate the result set in unidirectional, avoiding updates to
the tables
What is JDBC API and when do we use it?
Java DataBase Connectivity API allows us to work with relational databases. JDBC
API interfaces and classes are part of java.sql and javax.sql package. We can use JDBC
API to get the database connection, run SQL queries and stored procedures in the database
server and process the results.
JDBC API is written in a way to allow loose coupling between our Java program and
actual JDBC drivers that makes our life easier in switching from one database to another
database servers easily.
What are different types of JDBC Drivers?
There are four types of JDBC drivers. Any java program that works with database has
two parts, first part is the JDBC API and second part is the driver that does the actual
work.
JDBC-ODBC Bridge plus ODBC Driver (Type 1): It uses ODBC driver to
connect to database. We should have ODBC drivers installed to connect to
database, thats why this driver is almost obsolete.
Native API partly Java technology-enabled driver (Type 2): This driver
converts JDBC class to the client API for the database servers. We should have
database client API installed. Because of extra dependency on database client
API drivers, this is also not preferred driver.
Pure Java Driver for Database Middleware (Type 3): This driver sends the
JDBC calls to a middleware server that can connect to different type of
databases. We should have a middleware server installed to work with this
driver. This adds to extra network calls and slow performance and thats why
not widely used JDBC driver.
Direct-to-Database Pure Java Driver (Type 4): This driver converts the JDBC
calls to the network protocol understood by the database server. This solution is
simple and suitable for database connectivity over the network. However for
this solution, we should use database specific drivers, for example OJDBC jars
by Oracle for Oracle DB and MySQL Connector/J for MySQL databases.
What is JDBC Connection? Explain steps to get Database connection in a simple
java program.
JDBC Connection is like a Session created with the database server. You can also think
Connection is like a Socket connection from the database server.
Creating a JDBC Connection is very easy and requires two steps:
Register and Load the Driver: Using Class.forName(), Driver class is registered
to the DriverManager and loaded in the memory.
Use DriverManager to get the Connection object: We get connection object
from DriverManager.getConnection() by passing Database URL String,
username and password as argument.
What is the use of JDBC DriverManager class?
JDBC DriverManager is the factory class through which we get the Database
Connection object. When we load the JDBC Driver class, it registers itself to the
DriverManager, you can look up the JDBC Driver classes source code to check this. Then
when we call DriverManager.getConnection() method by passing the database
configuration details, DriverManager uses the registered drivers to get the Connection and
return it to the caller program.
What is JDBC Statement?
JDBC API Statement is used to execute SQL queries in the database. We can create
the Statement object by calling Connection getStatement() method. We can use Statement
to execute static SQL queries by passing query through different execute methods such as
execute(), executeQuery(), executeUpdate() etc.
By default, only one ResultSet object per Statement object can be open at the same
time. Therefore, if we want to work with multiple ResultSet objects, then each must have
been generated by different Statement objects. All execute() methods in the Statement
interface implicitly close a statments current ResultSet object if an open one exists.
State the functionalities of important classes in JDBC packages.
The important interfaces in JDBC are:
You should use execute() method only when you are not sure about the type of
statement else use executeQuery or executeUpdate method.
What is JDBC ResultSet?
JDBC ResultSet is like a table of data representing a database result set, which is
usually generated by executing a statement that queries the database.
ResultSet object maintains a cursor pointing to its current row of data. Initially the
cursor is positioned before the first row. The next() method moves the cursor to the next
row. If there are no more rows, next() method returns false and it can be used in a while
loop to iterate through the result set.
What are different types of ResultSet?
There are different types of ResultSet objects that we can get based on the user input
while creating the Statement. If you will look into the Connection methods, you will see
that createStatement() and prepareStatement() method are overloaded to provide ResultSet
type and concurrency as input argument.
There are three types of ResultSet object.
ResultSet.TYPE_FORWARD_ONLY: This is the default type and cursor can
only move forward in the result set.
ResultSet.TYPE_SCROLL_INSENSITIVE: The cursor can move forward and
backward, and the result set is not sensitive to changes made by others to the
database after the result set was created.
ResultSet.TYPE_SCROLL_SENSITIVE: The cursor can move forward and
backward, and the result set is sensitive to changes made by others to the
database after the result set was created.
Based on the concurrency there are two types of ResultSet object.
ResultSet.CONCUR_READ_ONLY: The result set is read only, this is the
default concurrency type.
ResultSet.CONCUR_UPDATABLE: We can use ResultSet update method to
update the rows data.
What is the different between ResultSet and RowSet?
RowSet objects are derived from ResultSet, so they have all the features of ResultSet
with some additional features. One of the huge benefits of RowSet is that they can be
disconnected and that makes it lightweight and easy to transfer over a network.
Whether to use ResultSet or RowSet depends on your requirements but if you are
planning to use ResultSet for longer duration, then a disconnected RowSet is better choice
to free database resources.
What are common JDBC Exceptions?
Some of the common JDBC Exceptions are:
java.sql.SQLException This is the base exception class for JDBC exceptions.
java.sql.BatchUpdateException This exception is thrown when Batch
operation fails, but it depends on the JDBC driver whether they throw this
exception or the base SQLException.
java.sql.SQLWarning For warning messages in SQL operations.
java.sql.DataTruncation when a data values is unexpectedly truncated for
reasons other than its having exceeded MaxFieldSize.
Multiple Choice Questions
A.
One
B.
Two
C.
Three
D.
Four
A.
B.
C.
D.
Which JDBC driver Type(s) can be used in either applet or servlet code?
A.
B.
C.
D.
Type 4 only
Exercise
What is JDBC? Explain Two Tier JDBC Architecture.
What is JDBC? Explain Three Tier JDBC Architecture.
List and explain common JDBC Components.
Describe various JDBC Drivers in details.
List advantages and dis-advantages of JDBC Drivers
List advantages and dis-advantages of JDBC.
Give statement to connect Java with oracle
Unit IV Servlets
Introduction to Web
Web consist of many clients and server connected together using networks. The web
clients makes request to web server. The web server receives the request, finds the
resources and return response to the client. Server answers a request with some type of
content to the client. The client uses web browser to send request to the server. The server
sends responds to the browser with a set of instructions written in HTML (HyperText
Markup Language). All browsers know how to display HTML page to the client.
Web Application
Web applications run over the web and are consumed by end user. A web site is a
collection of static files such as HTML pages, images, graphics etc. A Web application is
a web site with dynamic functionality on the server. Google, Facebook, Twitter are
examples of web application. A typical example of Web Application would be a Shopping
Kart Application, which can be accessed over HTTP protocol from a web browser.
HTTP
HTTP is a protocol that clients and server uses on the web to communicate.
HTTP is a stateless protocol i.e HTTP supports only one request per
connection.This means that with HTTP the clients connects to the server to
send one request and then disconnects. This mechanism allows more users to
connect to a given server over a period of time.
The client sends an HTTP request and the server answer with a HTML pages to
the client, using HTTP.
Introduction to Servlet
Servlet technology is used to create web application. Servlet technology uses Java
language to create dynamic web application.
Servlets are a powerful addition to the Java environment. They are fast, safe, reliable,
and 100% pure Java. Because servlets plug into an existing server, they leverage a lot of
existing code and technology. The server handles the network connections, protocol
negotiation, class loading, and more; all of this work does not need to be replicated! And,
because servlets are located at the middle tier, they are positioned to add a lot of value and
flexibility to a system.
Servlets are not tied to a specific client-server protocol but they are most commonly
used with HTTP and the word Servlet is often used in the meaning of HTTP Servlet.
A servlet can be plugged into a Java-enabled web server to provide custom services.
These services can include:
New features
Runtime changes to content
Runtime changes to presentation
New standard protocols (such as FTP)
New custom protocols
Features of servlet
Servlets execute as a thread within the Web server. Threaded execution avoids
the overhead of creating separate processes for each call.
Servlets may retain data between executions using session tracking mechanism.
For example, a servlet could retain a network connection or access counter
between executions.
A servlet may connect to any computer on the network or write files on the
server. Java servlets allow a platform independent implementation.
A Servlet is a Java program that runs on a Web Container. The Web Container
is capable of handling HTTP requests and responses. A Servlet can run on any
web container as it is developed using a common Servlet-API.
Servlets act as an inter-mediatory interface between HTTP requests originated
from Web Browsers (IE, Chrome etc) and Java Applications hosted on
Application Servers
Servlet runs as a light-weight thread instead of a separate OS process.
Servlets can be used to collect form inputs from a page.
Servlet specification is released by Oracle, which vendors implement to create
Managing state information on top of the stateless HTTP, e.g. for an online
shopping cart system which manages shopping carts for many concurrent
customers and maps every request to the right customer.
As Servlet Technology uses Java, web application made using Servlet
are secured, scalable and robust.
Advantage of Servlet
Portability
Servlets are written in java and follow well known standardized APIs so they
are highly portable across operating systems and server implementations. We
can develop a servlet on Windows machine running the tomcat server or any
other server and later we can deploy that servlet effortlessly on any other
operating system like UNIX server running on the iPlanet/Netscape
Application server. So servlets are write once, run anywhere (WORA) program.
Powerful
We can do several things with the servlets which were difficult or even
impossible to do with CGI, for example the servlets can talk directly to the web
server while the CGI programs cant do. Servlets can share data among each
other, they even make the database connection pools easy to implement. They
can maintain the session by using the session tracking mechanism which helps
them to maintain information from request to request. It can do many other
things which are difficult to implement in the CGI programs.
Efficiency
As compared to CGI the servlets invocation is highly efficient. When the
servlet get loaded in the server, it remains in the servers memory as a single
object instance. However with servlets there are N threads but only a single
copy of the servlet class. Multiple concurrent requests are handled by separate
threads so we can say that the servlets are highly scalable.
Safety
As servlets are written in java, servlets inherit the strong type safety of java
language. Javas automatic garbage collection and a lack of pointers mean that
servlets are generally safe from memory management problems. In servlets we
can easily handle the errors due to Javas exception handling mechanism. If any
Applet
server
Servlet are more powerful than Applet
Web browser
Java Applets are limited to certain
operations on the browser.
data validation.
data validation.
1. Loading Servlet Class: A Servlet class is loaded when first request for the
servlet is recieved by the Web Container.
2. Create Servlet instance: After the Servlet class is loaded, Web Container
creates the instance of it. Servlet instance is created only once in the life cycle.
3. Call the init() method: init() is called by the Web Container on servlet
instance to initialize the servlet.
4. Call the service() method: The container calls the service() method each time
the request for servlet is received.
5. Call destroy() method: The Web container calls the destroy() method before
removing servlet instance giving a chance for cleanup activity.
Usefule Servlet methods
init() method
The servlet is initialized by calling the init () method.
The init method is called only one time, when servlet is first created, never called
again for each user request.
The init() method simply create or load some data that will be used overall life of the
servlet.
public void init() throws ServletException {
//initialize code.
}
This method allows the servlet to per form any setup processing such as opening files
or establishing connections to their servers. If a servlet has been permanently installed in a
server, it loads when the server starts to run.
The init() method takes one argument, a reference to a ServletConfig object which
provides initialization arguments for the servlet.
service()method
The service() method is the heart of the servlet. Each request message from a client
results in a single call to the servlets service() method. The service() method reads the
request and produces the response message from its two parameters:
A ServletRequest object with data from the client.
A ServletResponse represents the servlets reply back to the client.
The service() methods job is conceptually simpleit creates a response for each
client request sent to it from the host server. The servlet container calls the service()
method to handle requests coming from the client or browsers and to write the formatted
response back to the client.
The service() method checks the HTTP request type such as GET, POST etc and calls
doGet, doPost etc.
public void service (ServletRequest request, ServletResponse response)
throws ServletException, IOException
{
}
doGet() Method
GET is HTTP method. It works to tell server to get a resource and send it.
It should be handled by doGet() method.
public void doGet (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// Servlet code
}
The doPost() Method
With POST, you can request something and at same time send form data to server.
It should be handled by doPost() method.
public void doPost (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// Servlet code
}
destroy() method
The destroy() method is called to allow your servlet to clean up any resources (such as
open files or database connections) before the servlet is unloaded. If you do not require
any clean-up operations, this can be an empty method.
The server waits to call the destroy() method until either all service calls are complete,
or a certain amount of time has passed. The destroy() method is called only one time at the
end of the life cycle of a servlet.
public void destroy()
{
// Finalization code
}
Servlet Container
The most popular Servlet Container today is Tomcat. It is very light-weight and easy
to develop and deploy applications on Tomcat. Originally Tomcat was built by Sun
MicroSystems, and later was handed over to the Apache Software Foundation in October
1999. It can be easily integrated with all popular IDEs (like Eclipse, NetBeans etc) and
1. The container finds the servlet using deployment descriptor and creates two
objects
a. HttpServletRequest
b. HttpServletResponse
1. The container creates or allocates a thread for that request and calls the
servlets service() method and passes the request, response objects as
argument
1. The service method decide which servlet method doGet() or doPost() to call
based on HTTP Request Method(Get,Post) sent by the client. Suppose the
client sent an HTTP GET request, so the service() method calls
servlets doGet() method
1. The servlet uses response object to write the response back to the client
1. After the service() method is completed the thread dies. The request and
response object are ready for garbage collection
Installing Servlets
Servlets are not run in the same sense as applets and applications. Servlets provide
functionality that extends a server. In order to test a servlet, two steps are required:
1. Install the servlet in a hosting server
2. Request a servlets service via a client request
There are many web servers that support servlets. It is beyond the scope of this course
to cover different ways to install servlets in each server. This course examines the JSDKs
servletrunner utility and the Apache Web Server.
The Java Servlet Development Kit
For both JDK 1.1 and the Java 2 platform, you need to install the Java Servlet
Development Kit (JSDK) to run servlet. JSDK (Java Servlet Development Kit) is a
package containing all the classes and interfaces needed to develop servlets. JSDK also
contains a web server and servlet engine to test your creations. The servlet engine
provided in JSDK is a basic one (but free). There are many other servlet engines much
more robust and can be interfaced with most major web servers of the market.
This is an Add-on to the regular JDK (Java Developers Kit). The JSDK has the
additional files needed in order to compile Java servlets.
Included in the JSDK is a Java Servlet Runner program. The Servlet Runner is a
program that runs on your workstation, and allows you to test servlets you have written
without running a web server. Other files included are the several Java Servlet examples.
Included are the .java and .class files for testing purposes and to help you understand how
the Java code is implemented. Another important file that is included is the jsdk.jar file.
This file includes the class information necessary to compile the servlets.
Installing JSDK
To install JSDK simply doublie-click on the executable under Windows:
Install JSDK 2.0 to C:\JSDK20 to make it easier when searching for the
directory.
In order to use both the JDK and JSDK together, the java compiler (javac.exe)
needs to know where the class files are located.
First put the bin directory for the JDK in the path. This will make it easy to find
the javac.exe program when compiling code.
Second, add the jsdk.jar file to the classpath. This can be done by adding a SET
statement. The SET statement should read SET CLASSPATH = C:\JSDK
install path\lib\jsdk.jar (ex. SET CLASSPATH = C:\jsdk20\lib\jsdk.jar). Once
this is done, you will have no problem compiling your java servlets. You can
observe following screenshot:
server to associate the servlet object with its initialization arguments: they both have the
same name. Even if your servlet does not use initialization parameters, it is recommended
that it have this property, so that clients can access the servlet using its name.
Using the Initargs Property
The value of the servlet.name.initArgs property holds the servlets initialization
parameters.
The syntax of a single parameter is
parameterName=parameterValue.
The entire property (the entire key-value pair) must be a single logical line.
Starting servletrunner
To use servletrunner, make sure your PATH environment variable points to its
directory. For the JSDK 2.0 installed with all default options, that location is:
c:\jsdk2.0\bin on a Windows platform.
To make sure that servletrunner has access to the Java servlet packages, check that
your CLASSPATH environment variable is pointing to the correct JAR file,
c:\jsdk2.0\lib\jsdk.jar on a Windows platform. With the Java 2 platform, instead of
modifying the CLASSPATH, it is easier to just copy the JAR file to the ext directory under
the Java runtine environment. This treats the servlet packages as standard extensions.
To verify that the installation was performed correctly, simply start the servletrunner
utility, the servlet engine included in the JSDK, that is to say, a basic server running on
port 8080. If JSDK utility is correctly installed servletrunner should return the following
lines (available at C:\jsdk20\bin\servletrunner.exe from command prompt) :
servletrunner
servletrunner starting with settings :
port = 8080
backlog = 50
max handlers = 100
timeout = 5000
servletdir = ./examples
document dir = ./examples
HelloServlet.java
in
}
}
}
After creating above .java Servlet file compile it as follows:
Note: We have included jsdk.jar file in the classpath it is necessary to compile the
servlet.
Before running any newly created servlet using servletrunner utility we need to create
its entry in the servlet.propertis file.
The Property File
Properties are stored in a file that is, by default, called servlet.properties, though you
can specify another name when servletrunner is started. The file should hold the properties
for all the servlets that servletrunner will run. It should be plain text. You can create it in
any editor. It is located under <Drive>:\JSDK20\examples directory.
For example, to run the HelloServlet Servlet modify servlet.properties file as follows:
i.e.
set
JAVA_HOME=C:\Program
JAVA_HOME
in
variable
Click OK->OK->OK
name
and
value=
C:\Program
Set
the
current
directory
to
a. Restart your Tomcat server to pick up the hello webapp. Check the
Tomcats console to confirm that hello application has been properly
deployed.
a. You can issue the following URL to access the web application hello
a. Access
this
page
in
browser
http://localhost:9999/hello/HelloHome.html
by
URL:
a. Compile the Servlet. We need the Servlet API to compile the servlet.
Servlet API is NOT part of JDK. Tomcat provides in lib
directory:/lib/servlet-api.jar. We need to include this JAR file in the
compilation via the -cp (classpath) option.
the
request
URL:
1. This is the end of the demo of running Servlet on Apache Tomcat 8.x.
Example 2: To create a Servlet that output HTML not just plain text
//HelloWWW.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWWW extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType(text/html);
PrintWriter out = response.getWriter();
String docType =
<!DOCTYPE HTML PUBLIC -//W3C//DTD HTML 4.0 +
Transitional//EN>\n;
out.println(docType +
<HTML>\n +
<HEAD><TITLE>Hello World in HTML</TITLE></HEAD>\n +
<BODY>\n +
<H1>Hello, World!</H1>\n +
</BODY></HTML>);
}
}
Servlet API consists of two important packages that encapsulate all the important
classes and interface.
javax.servlet
javax.servlet.http
It defines Life Cycle methods that all Servlets must implement.
Method
Description
void
init(ServletConfig
config)
throws ServletException
public ServletConfig
getServletConfig()
public
void
Called by the Web Container to allow the servlet to
service(ServletRequest
respond to a request. Parameters: Object of
req,
ServletRequest(req) that contains the clients request and
ServletResponse res)
Object of ServletResponse(res)that contains the servlets
throws ServletException, response. An IOException is thrown if IO problem occurs.
IOException
String
getServletInfo()
Description/Use
HttpServletRequest
HttpServletResponse
HttpSession
HttpSessionBindingListener
The following table summarizes the core classes that are provided in this package. The
most important of these is HttpServlet. Servlet developers typically extend this class in
order to process HTTP requests.
Class
Description/Use
Cookie
HttpSer vlet
Provides
methods
to handle HTTP requests and responses.
HttpSessionEvent
HttpSessionBindingEvent
doPost(request, response);
}
protected void doPost( HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.getWriter().write(GET/POST response);
}
}
<html>
<head>
<meta http-equiv=Content-Type content=text/html; charset=UTF-8>
<title>Login Page</title>
</head>
<body>
<form id=loginForm action=/login method=post>
<label>Username</label>
<input type=text name=username />
<label>Password</label>
<input type=password name=password />
<input type=submit value=Login />
</form>
</body>
</html>
In this form youll have to input box for username and password. You also have a
submit button for executing the login procces. Now we have the form, lets create the
login servlet(LoginServlet.java inside /LoginDemo/WEB-INF/classes).
//LoginServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
doLogin(request, response);
}
doLogin(request, response);
}
protected void doLogin(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// Reading the parameters from servlet request
String username = request.getParameter(username);
String password = request.getParameter(password);
PrintWriter pw = response.getWriter();
if (username != null && username.equals(administrator)
&& password != null && password.equals(secret)) {
// authentication accepted!
pw.println(Success!);
} else {
// authentication denied!
pw.println(Denied!);
}
pw.close();
}
}
For our servlet to work you must register the servlet in the web.xml file under the
WEB-INF folder. You can find the configuration below (web.xml inside
/LoginDemo/WEB-INF/).
Content of Web.xml file
<?xml version=1.0 encoding=UTF-8?>
<web-app
id=WebApp_ID
xmlns=http://java.sun.com/xml/ns/j2ee
xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance
xsi:schemaLocation=http://java.sun.com/xml/ns/j2ee
version=2.4
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd>
<display-name>java-web-examples</display-name>
<servlet>
<description>
</description>
<display-name>LoginServlet</display-name>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.javacoderanch.example.servlet.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>
Now you have everything, you can deploy the application on your servlet container,
for example Apache Tomcat. Access you login page in the following address:
http://localhost:9999/LoginDemo/LoginDemo.html
You can also access the servlet directly from the following URL:
http://localhost:9999/LoginDemo/index.html
To pass the username and password information you can append the parameter like:
http://localhost:9999/LoginDemo/login?username=administrator&password=secret
This will call the servlet and validate your login information as follows:
After inputing username and password correctly as shown above when you press the
login button:
In order to get all Request Parameters in Servlet, one should take the following steps:
Create a handleRequest
in doGet and doPostmethods.
method
so
you
can
use
it
both
import javax.servlet.http.HttpServlet;
to
get
the
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class GetAllParams extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res) throws
IOException {
handleRequest(req, res);
}
public void doPost(HttpServletRequest req, HttpServletResponse res) throws
IOException {
handleRequest(req, res);
}
public void handleRequest(HttpServletRequest req, HttpServletResponse res)
throws IOException {
PrintWriter out = res.getWriter();
res.setContentType(text/plain);
Enumeration<String> parameterNames = req.getParameterNames();
while (parameterNames.hasMoreElements()) {
String paramName = parameterNames.nextElement();
out.write(paramName);
out.write(n);
String[] paramValues = req.getParameterValues(paramName);
for (int i = 0; i < paramValues.length; i++) {
String paramValue = paramValues[i];
out.write(\t + paramValue);
out.write(\n);
}
}
out.close();
}
}
Now lets create servlet web deployment descriptor in web.xml file
<?xml version=1.0 encoding=UTF-8?>
<web-app
id=WebApp_ID
xmlns=http://java.sun.com/xml/ns/j2ee
xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance
xsi:schemaLocation=http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd>
<display-name>Reading Parameters</display-name>
<servlet>
<servlet-name>GetAllParams</servlet-name>
<servlet-class>GetAllParams</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GetAllParams</servlet-name>
<url-pattern>/getall</url-pattern>
</servlet-mapping>
</web-app>
URL:
version=2.4
After submitting username and password when you press login button you are
redirected to servlet processing:
Description
getInitParameter(String
Enumeration
getInitParameterNames()
public
getServletContext()
There are two types of init parameters available. They are both referred to as init
parameters, although defined in defferent elements.
servlet init parameters (defined in <init-param> element).
Servlet init parameters are available to only the servlet for which
the <init-param> was confgured.
Servlet init parameters are defined within the <servlet> element for each
specific servlet.
context init parameters (defined in <context-param> element)
Context init parameters are available to any servlet or JSP that are part
of the current web app.
Context init parameters are defined within the <web-app> element.
Servlet init parameters
Initialization information is passed to the servlet via the ServletConfig parameter of
the init() method. The initialization parameters of a servlet can only be accessed by that
servlet. Accessing servlet init parameter in a servlet for which it was defined in DD:
getServletConfig().getInitParameter(username);
An alternative way of getting servlet init parameter is using method defined in the
class GenericServlet:
getInitParameter(username);
This method is supplied for convenience. It gets the value of the named parameter
from the servletsServletConfig object.
Here is how you configure them in the web.xml file:
<?xml version=1.0 encoding=UTF-8?>
<web-app
id=WebApp_ID
xmlns=http://java.sun.com/xml/ns/j2ee
xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance
xsi:schemaLocation=http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd>
<servlet>
version=2.4
<servlet-name>InitParamServlet</servlet-name>
<servlet-class>InitParamServlet</servlet-class>
<display-name>InitParamServlet</display-name>
<init-param>
<param-name>username</param-name>
<param-value>Jbpatel</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>InitParamServlet</servlet-name>
<url-pattern>/InitParam</url-pattern>
</servlet-mapping>
</web-app>
Here is how you read the init parameters from inside your servlet
(InitParamServlet.java) - in the servlets init() method:
//GetAllParams.java
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.ServletConfig;
public class InitParamServlet extends GenericServlet{
protected String myParam = null;
public void init(ServletConfig servletConfig) throws ServletException{
this.myParam = servletConfig.getInitParameter(username);
}
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
response.getWriter().write(<html><body>username = +
this.myParam + </body></html>);
}
}
A servlets init() method is called when the servlet container loads the servlet for the
first time. No one can access the servlet until the servlet has been loaded, and
the init() method has been called successfully.
index.htm
<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN
http://www.w3.org/TR/html4/loose.dtd>
<html>
<head>
<meta http-equiv=Content-Type content=text/html; charset=UTF-8>
<title>Servlet Initialization Paramaters</title>
</head>
<body>
<form id=GetAllParams action=/InitParams/InitParam method=post>
<label>Press to Login</label>
<input type=submit value=Login />
</form>
</body>
</html>
Output:
After pressing login button initialization parameters are read from web.xml file and
used by servlet:
<html>
<head>
<meta http-equiv=Content-Type content=text/html; charset=UTF-8>
<title>Servlet Context Initialization Paramaters</title>
</head>
<body>
<form id=ContextParam action=/ServletParam/ContextParam method=GET>
<label>Press to Login</label>
<input type=submit value=Login />
</form>
</body>
</html>
ContextParam.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
<servlet-name>ContextParam</servlet-name>
<url-pattern>/ContextParam</url-pattern>
</servlet-mapping>
<context-param>
<param-name>email</param-name>
<param-value>admin@example.com</param-value>
</context-param>
</web-app>
Output:
HTTP request can be made using a variety of methods, but the ones you will use most
often are Get andPost. The method name tells the server the kind of request that is being
made, and how the rest of the message will be formated.
HTTP Method and Descriptions
Method
Description
OPTIONS
GET
HEAD
POST
DELETE
CONNECT
The GET and POST requests are commonly used when handling form input.
Difference between GET and POST request
GET Request
Data is sent in header to the
server
POST Request
Data is sent in request body
Get
request
bookmarked.
can
Description
return attribute set on request object by name
Enumeration
getAttributeName()
int getContentLength()
int getContentType()
ServletInputStream
getInputStream()
String
getParameter(String
name)
String getLocalAddr()
Enumeration
getParameterNames()
String[]
returns an array of String objects containing all of
getParameterValues(String the values the given request parameter has, or null if
name)
the parameter does not exist
ServletContext
getServletContext()
String
getServerName()
int getServerPort()
boolean isSecure()
void
removeAttribute(String
name)
void
setAttribute(String name,
Object o)
HttpServletRequest interface
HttpServletRequest interface adds the methods that relates to the HTTP protocol.
Description
String
returns the portion of the request URI that indicates the
getContextPath() context of the request
Cookies
getCookies()
String
returns the query string that is contained in the request URL
getQueryString() after the path
HttpSession
getSession()
String
getMethod()
Part
getPart(String
name)
String
getPathInfo()
String
getServletPath()
returns the part of this requests URL that calls the servlet
Servlet Response
Servlet
API
provides
two
important
interfaces ServletResponse and HttpServletResponse to assist in sending response to
client.
HttpResponse class
The purpose of the HttpResponse object is to represent the HTTP response your web
application sends back to the browser, in response to the HTTP request the browser send
to your web application.
The HttpResponse object has a lot of methods, so I will just cover the most commonly
used here. The rest you can read about in the JavaDoc, if you are interested.
Some important methods of ServletResponse
Methods
PrintWriter
getWriter()
Description
returns a PrintWriter object that can send character
text to the client.
void
Sets the preferred buffer size for the body of the
setBufferSize(int size) response
void
setContentLength(int
len)
void
sets the content type of the response being sent to the
setContentType(String client before sending the respond.
type)
void
sets the preferred buffer size for the body of the
setBufferSize(int size) response.
boolean
isCommitted()
void
setLocale(Locale loc)
HttpServletResponse interface
HttpServletResponse interface adds the methods that relates to the HTTP response.
Methods
Description
void
addCookie(Cookie
cookie)
void
sendRedirect(String
location)
int getStatus()
String
getHeader(String
name)
void
setHeader(String
name, String value)
void setStatus(int
name.
sc)
void sendError(int
sends an error response to the client using the
sc, String msg)
specified status and clears the buffer
Handling HTTP GET Requests
Here we will develop a servlet that handles an HTTP GET request. The servlet is
invoked when a form on a web page is submitted. The example contains two files. A web
page is defined in ColorGet.htm, and a servlet is defined in ColorGetServlet.java. The
HTML page ColorGet.htm defines a form that contains a select element and a submit
button. Notice that the action parameter of the form tag specifies a URL. The URL
invokes a servlet to process the HTTP GET request.
ColorGet.html
</body>
</html>
ColorGetServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ColorGetServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
id=WebApp_ID
xmlns=http://java.sun.com/xml/ns/j2ee
xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance
xsi:schemaLocation=http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd>
<display-name>Reading Parameters</display-name>
<servlet>
<display-name>ColorGetServlet</display-name>
<servlet-name>ColorGetServlet</servlet-name>
<servlet-class>ColorGetServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ColorGetServlet</servlet-name>
version=2.4
<url-pattern>/ColorGetServlet</url-pattern>
</servlet-mapping>
</web-app>
Steps for Executing above example:
Compile the servlet.
Copy it to the appropriate directory
Update the web.xml file to include ColorGet servlet.
Start Tomcat, if it is not already running.
Display the web page in a browser.
Select a color.
Submit the web page.
After completing these steps, the browser will display the response that is dynamically
generated by the servlet.
Output:
Parameters for an HTTP GET request are included as part of the URL that is sent to
the web server. Assume that the user selects the blue option and submits the form. The
URL sent from the browser to the server is
http://localhost:8080/ColorGetServlet?color=Blue
The characters to the right of the question mark are known as the query string.
Handling HTTP POST Requests
Now we will develop a servlet that handles an HTTP POST request.
The servlet is invoked when a form on a web page is submitted. This example also
contains two files. A web page is defined in ColorPost.htm, and
a servlet is defined in ColorPostServlet.java. The method parameter for the form tag is set
to POST.
ColorPOST.html
<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN
http://www.w3.org/TR/html4/loose.dtd>
<html>
<head>
<meta http-equiv=Content-Type content=text/html; charset=UTF-8>
<title>Handling HTTP Request using POST Method</title>
</head>
<body>
<form id=ContextParam action=/PostDemo/ColorPostServlet method=POST>
<B>Color:</B>
<select name=color size=1>
<option value=Red>Red</option>
<option value=Green>Green</option>
<option value=Blue>Blue</option>
</select>
<br><br>
<input type=submit value=Submit>
</form>
</body>
</html>
The
source
code
for
ColorPostServlet.java
is
shown
in
the following listing. The doPost( ) method is overridden to process any HTTP POST
requests that are sent to this servlet. It uses the getParameter(
) method of HttpServletRequest to obtain the selection that was made by the user. A
response is then formulated.
ColorPostServlet .html
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ColorPostServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String color = request.getParameter(color);
response.setContentType(text/html);
PrintWriter pw = response.getWriter();
pw.println(<B>The selected color is: );
pw.println(color);
pw.close();
}
}
web.xml
<?xml version=1.0 encoding=UTF-8?>
<web-app
id=WebApp_ID
xmlns=http://java.sun.com/xml/ns/j2ee
xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance
version=2.4
xsi:schemaLocation=http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd>
<display-name>Reading Parameters</display-name>
<servlet>
<display-name>ColorPostServlet</display-name>
<servlet-name>ColorPostServlet</servlet-name>
<servlet-class>ColorPostServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ColorPostServlet</servlet-name>
<url-pattern>/ColorPostServlet</url-pattern>
</servlet-mapping>
</web-app>
Compile and Test the Servlet.
Output
action=/HeadDemo/HeadRequestServlet
<label>Username</label>
<input type=text name=name />
<br><br>
<input type=submit value=Submit>
</form>
</body>
</html>
HeadRequestServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HeadRequestServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException {
// Set the Content-Type header
res.setContentType(text/html);
// Return early if this is a HEAD
if (req.getMethod().equals(HEAD))
return;
// Proceed otherwise
PrintWriter out = res.getWriter();
String name = req.getParameter(name);
out.println(<HTML>);
out.println(<HEAD><TITLE>Hello, + name + </TITLE></HEAD>);
out.println(<BODY>);
out.println(Hello, + name);
out.println(</BODY></HTML>);
}
}
web.xml
<?xml version=1.0 encoding=UTF-8?>
<web-app
id=WebApp_ID
xmlns=http://java.sun.com/xml/ns/j2ee
xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance
xsi:schemaLocation=http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd>
<display-name>Reading Parameters</display-name>
<servlet>
<display-name>HeadRequestServlet</display-name>
<servlet-name>HeadRequestServlet</servlet-name>
<servlet-class>HeadRequestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HeadRequestServlet</servlet-name>
<url-pattern>/HeadRequestServlet</url-pattern>
</servlet-mapping>
</web-app>
Output:
version=2.4
Notice that we set the Content-Type header, even if we are dealing with a HEAD
request. Headers such as these are returned to the client. Some header values, such
as Content-Length, may not be available until the response has already been calculated. If
you want to be accurate in returning these header values, the effectiveness of this shortcut
is limited.
Make sure that you end the request handling with a return statement. Do not
call System.exit(). If you do, you risk exiting the web server.
Session Tracking
Session
A session can be defined as a series of related interactions between a single client and
the Web server over a period of time. HTTP is a stateless protocol, where each request
is independent of the previous one. However, in some applications, it is necessary to save
state information so that information can be collected from several interactions between a
browser and a server. Sessions provide such a mechanism. Sessions provide such a
mechanism.
A new session is created if one does not already exist.
It is required to implement session management capabilities that link both the
authentication and access control modules commonly available in web
applications.
Session Tracking
To track data among requests in a session is known as session tracking.
Approaches to Session-Tracking:-
boolean b=s.IsNew();
Description
This method is use to reterive the current HttpSession
that is associated with user. if session does not exist,then
a session can be created by using getSession(true)
Returns the Value true If the new Session ID has been
created and has not been sent the client.
s.invalidate()
long
l=s.getCreationTime();
long
l=s.getLastAccessedTime();
s.setAttribute(userid,a)
Object
o=s.getAtribute(userid);
HttpSession s=request.getSession()
Setting Session timeout
You dont have to use them to get rid of stale (inactive) sessions. The container can do
it for you.
Three ways a session can die(timeout)
1. It times out.
2. You call invalidate () on the session object.
3. The application goes down (Crashes or is undeployed).
Configure Session Time out in Deployment Descriptor (i.e. web.xml file)
<session-config>
<session-timeout>15</session-timeout> //15 min
</session-config>
Or
session.setMaxInactiveInterval (20*60); //20 minute
It is important to note that session state is shared among all the servlets that are
associated with a particular client. The following servlet illustrates how to use session
state. The getSession( ) method gets the current session. A new session is created if one
does not already exist. The getAttribute( ) method is called to obtain the
object that is bound to the name date. That object is a Date object that encapsulates the
date and time when this page was last accessed. (Of course, there is no
such binding when the page is first accessed.) A Date object encapsulating the current date
and time is then created. The setAttribute( ) method is called to bind the name date
to this object.
Example: Handling Sessions
Index.html
<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN
http://www.w3.org/TR/html4/loose.dtd>
<html>
<head>
<label>Username</label>
<input type=text name=name />
<br><br>
<input type=submit value=Submit>
</form>
</body>
</html>
SessionServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SessionServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType(text/html);
PrintWriter out = response.getWriter();
String n=request.getParameter(name);
out.print(Welcome: +n);
HttpSession session=request.getSession();
session.setAttribute(uname,n);
out.print(<a href=SessionTrack> Check Session Tracking</a>);
out.close();
}catch(Exception e){System.out.println(e);}
}
}
SessionTrack.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SessionTrack extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
{
try{
response.setContentType(text/html);
PrintWriter out = response.getWriter();
HttpSession session=request.getSession(false);
String n=(String)session.getAttribute(uname);
out.print(Hello +n);
out.close();
}
catch(Exception e){System.out.println(e);}
}
}
web.xml
<?xml version=1.0 encoding=UTF-8?>
<web-app
id=WebApp_ID
xmlns=http://java.sun.com/xml/ns/j2ee
xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance
xsi:schemaLocation=http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd>
<display-name>Reading Parameters</display-name>
<servlet>
<servlet-name>SessionServlet</servlet-name>
<servlet-class>SessionServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SessionServlet</servlet-name>
<url-pattern>/SessionServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>SessionTrack</servlet-name>
<servlet-class>SessionTrack</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SessionTrack</servlet-name>
<url-pattern>/SessionTrack</url-pattern>
</servlet-mapping>
</web-app>
version=2.4
Output:
Observe that the name of user is made available to second servlet through use of
session.
Using Cookies
Cookies
HTTP Cookies are little pieces of data that a web application can store on the client
machine of users visiting the web application. Typically up to 4 kilo bytes of data.
Cookies are small text files that are used by a Web server to keep track of users.
A cookie has value in the form of key-value pairs.
They are created by the server and sent to the client with the HTTP response
headers.
javax.servlet.http.Cookie class is used to represent a cookie.
A server can send one or more cookies to the client.
A web-browser, which is the client software, is expected to support 20 cookies
per host and the size of each cookie can be a maximum of 4 bytes each.
Important Methods of Cookie class
Cookie Method
Cookie
Description
c=new
Cookie(theme,decent);
c.setMaxAge(int);
HttpServletResponse.addCookie(c);
Cookie
c[]=HttpServletResponse.getCookies.
c.getName()
Writing cookie
You can write cookies using the HttpServletResponse object like this:
Cookie cookie = new Cookie(myCookie, myCookieValue);
response.addCookie(cookie);
Whenever the browser accesses the web application it submits the cookies stored on
the client machine to the web application. Only cookies stored by the accessed web
application are submitted. Cookies from other web applications are not submitted.
Reading Cookies Sent From the Browser
A web-browser, which is the client software, is expected to support 20 cookies per host
and the size of each cookie can be a maximum of 4 bytes each. You can read the cookies
via the HttpServletRequest like this:
Cookie c[]=request.getCookies();
Now, lets develop a servlet that illustrates how to use cookies.
The servlet is invoked when a form on a web page is submitted. The example contains
three files as summarized here:
AddCookie.htm
Allows a user to specify a value for the cookie named MyCookie.
AddCookieServlet.java
Processes the submission of AddCookie.htm.
GetCookiesServlet.java
Displays cookie values.
The HTML source code for AddCookie.htm is shown in the following listing. This
page contains a text field in which a value can be entered. There is also a submit button on
the page. When this button is pressed, the value in the text field is sent
to AddCookieServlet via an HTTP POST request.
AddCookie.html
<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN
http://www.w3.org/TR/html4/loose.dtd>
<html>
<head>
<meta http-equiv=Content-Type content=text/html; charset=UTF-8>
<title>Handling Session using Cookie</title>
</head>
<body>
<form
id=CookieDemo
method=POST>
action=/CookieDemo/AddCookieServlet
}
}
The code for GetCookiesServlet.java is shown above. It invokes
the getCookies() method to read any cookies that are included in the HTTP GET request.
The names and values of these cookies are then written to the HTTP response.
Observe that the getName( ) and getValue( ) methods are called to obtain this information.
Executing the Cookie example:
Compile the servlets.
Copy to the appropriate directory
Update the web.xml file to include the servlets.
Start Tomcat, if it is not already running.
Display AddCookie.htm in a browser.
Enter a value for MyCookie.
Submit the web page.
After completing these steps, you will observe that a feedback message is displayed by
the browser.
Next, request the following URL via the browser:
http://localhost:9999/GetCookiesServlet
Observe that the name and value of the cookie are displayed in the browser.
Output:
Cookie Expiration
One important Cookie setting is the cookie expiration time. This time tells the browser
receiving the cookie how long time it should keep the cookie before deleting it.
You can set the cookie expiration time using the setMaxAge() method. This method
takes the number of seconds the cookie is to live as parameter. Here is an example:
Cookie cookie = new Cookie(username, Jbpatel);
cookie.setMaxAge(24 * 60 * 60); // 24 hours.
response.addCookie(cookie);
This example first creates a Cookie instance with the name username and the value
Jbpatel. Second, it sets the expiration to 24 hours using the setMaxAge() method. 24
hours is 60 seconds x 60 minutes x 24 hours (24 x 60 x 60). Finally the example sets the
cookie on the HttpServletResponse object, so the cookie is included in the response sent to
the browser.
Removing Cookies
You can remove a cookie from the browser by setting the cookie expiration time
0 or -1. If you set the expiration time to 0 the cookie will be removed immediately from
the browser. If you set the expiration time to -1 the cookie will be deleted when the
browser shuts down. Here is an example:
Cookie cookie = new Cookie(username, );
cookie.setMaxAge(0);
response.addCookie(cookie);
If the browser already has a cookie stored with the name username, it will be deleted
after receiving the cookie with the same name (username) with an expiration time of 0.
If the browser did not already have the cookie stored, this new cookie is just thrown out
immediately since its expiration time is 0.
Using Hidden Form Fields
A hidden form field is simplest session tracking techniques. It can be used to keep
track of users by placing hidden fields in a form. The values that have been entered in
these fields are sent to the server when the user submits the form.
For Example:
<input type=hidden name=text1 value=20>
URL-Rewritting
If web browser at Client side has disabled Cookie then Session API fails. If client
wont take cookies, you can use URL rewriting as a back up. URL rewriting is a better
way to maintain sessions when the browsers dont support cookie. So URL rewriting is a
better way to maintain sessions.
// Database credentials
final String USER = root;
catch(SQLException se){
se.printStackTrace();
}
//Display values
out.println(Students Roll No: + rno + );
out.println(, Name: + sname + <br>);
}
out.println(</body></html>);
// Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
} //end try
}
}
index.html
<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN
http://www.w3.org/TR/html4/loose.dtd>
<html>
<head>
id=ContextParam
action=/DatabaseServlet/LoadRecords
method=GET>
<label>Press to Display Student Records</label>
<input type=submit value=Display />
</form>
</body>
</html>
web.xml
<servlet>
<servlet-name>LoadRecords</servlet-name>
<servlet-class>LoadRecords</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoadRecords</servlet-name>
<url-pattern>/LoadRecords</url-pattern>
</servlet-mapping>
Output:
Before running this servlet care following:
Copy
mysql-connector-java-5.1.34-bin.jar
file
to
C:\Program
Files\Java\jdk1.8.0_25\jre\lib\ext folder
Set classpath to include servlet-api.jar file and mysql-connector-java-5.1.34bin.jar file.
What is a servlet?
Java Servlet is server side technologies to extend the capability of web servers by
providing support for dynamic response and data persistence.
The javax.servlet and javax.servlet.http packages provide interfaces and classes for
writing our own servlets.
All servlets must implement the javax.servlet.Servlet interface, which defines servlet
lifecycle methods. When implementing a generic service, we can extend the
GenericServlet class provided with the Java Servlet API. The HttpServlet class provides
methods, such as doGet() and doPost(), for handling HTTP-specific services.
Most of the times, web applications are accessed using HTTP protocol and thats why
we mostly extend HttpServlet class. Servlet API hierarchy is shown in below image.
What are the uses of Servlet?
The important used of HTTP Servlets are:
Storage and processing of data submitted by an HTML form.
Providing dynamic content to the client for example outputting the result of
a query.
Improving the system performance by handling multiple requests at a time.
Managing state information on top of the stateless HTTP.
Web server.
Multithreading support: Automatically creating a new thread for every
servlet request and finishing it when the Servlet service() method is over.
Declarative security: Managing the security inside the XML deployment
descriptor file.
JSP support: Converting JSPs to servlets and maintaining them.
What is the difference between GET and POST method?
GET Request
POST Request
can
be
application using PHP. Java provides web application support through Servlets and JSPs
that can run in a servlet container and provide dynamic content to client browser.
When using servlets to build the HTML, you build a DOCTYPE line, why do you
do that?
Building a DOCTYPE line informs the HTML validators about the version of HTML
you are using. This tells them the specification against which your document should be
checked.
These validators work as valuable debuggers which help you catch the HTML syntax
errors.
What is ServletConfig object?
javax.servlet.ServletConfig is used to pass configuration information to Servlet. Every
servlet has its own ServletConfig object and servlet container is responsible for
instantiating this object. We can provide servlet init parameters in web.xml file or through
use of WebInitParam annotation. We can use getServletConfig() method to get the
ServletConfig object of the servlet.
What is ServletContext object?
javax.servlet.ServletContext interface provides access to web application parameters
to the servlet. The ServletContext is unique object and available to all the servlets in the
web application. When we want some init parameters to be available to multiple or all of
the servlets in the web application, we can use ServletContext object and define
parameters in web.xml using <context-param> element. We can get the ServletContext
object via the getServletContext() method of ServletConfig. Servlet containers may also
provide context objects that are unique to a group of servlets and which is tied to a specific
portion of the URL path namespace of the host.
ServletContext is enhanced in Servlet Specs 3 to introduce methods through which we
can programmatically add Listeners and Filters and Servlet to the application. It also
provides some utility methods such as getMimeType(), getResourceAsStream() etc.
What is difference between ServletConfig and ServletContext?
Some of the differences between ServletConfig and ServletContext are:
ServletConfig is a unique object per servlet whereas ServletContext is a
unique object for complete application.
ServletConfig is used to provide init parameters to the servlet whereas
ServletContext is used to provide application level init parameters that all other
servlets can use.
We cant set attributes in ServletConfig object whereas we can set attributes
in ServletContext that other servlets can use in their implementation.
Why is a constructor needed in a servlet even if we use the init method?
Although the init method of the servlet initializes it, a constructor instantiates it. A
developer might never explicitly call the servlets constructor but a container uses it to
create an instance of the servlet.
What is difference between PrintWriter and ServletOutputStream?
PrintWriter is a character-stream class whereas ServletOutputStream is a byte-stream
class. We can use PrintWriter to write character based information such as character array
and String to the response whereas we can use ServletOutputStream to write byte array
data to the response.
We can use ServletResponse getWriter() to get the PrintWriter instance whereas we
can use ServletResponse getOutputStream() method to get the ServletOutputStream object
reference.
Can we get PrintWriter and ServletOutputStream both in a servlet?
We cant get instances of both PrintWriter and ServletOutputStream in a single servlet
method, if we invoke both the methods; getWriter() and getOutputStream() on response;
we will get java.lang.IllegalStateException at runtime with message as other method has
already been called for this response.
When should you prefer to use doGet() over doPost()?
GET is preferred over POST in most of the situations except for the following:
for HTTP clients. A low-level API controls the cookies. It is quite difficult to implement
them.
How can the session in Servlet be destroyed?
There are two ways to destroy a session:
Programatically: By using session.invalidate() method. It makes the container
abandon the session on which the method is called.
When the server shuts down.
Exercise
What is servlet?
What is difference between Applet and Servlet?
Explain the life cycle of Servlet.
What are the uses of Servlets?
Whats the Servlet Interface?
What is web container? Explain its working.
Explain following methodsof using Servlet in JAVA
Using Servletrunner utility
Using WebServer
List interfaces and class available in Servlet API.
How HTTP Servlet handles client requests?
When a servlet accepts a call from a client, it receives two objects. What are
they?
What information that the ServletRequest interface allows the servlet access
to?
What information that the ServletResponse interface gives the servlet
methods for replying to the client?
If you want a servlet to take the same action for both GET and POST
request, what you should do?
Write Servlet to read parameters using GET method.
Write Servlet to read parameters using POST method.
Write Servlet to read servlet initialization parameters.
Write Servlet to read context initialization parameters.
Write Servlet to provide session management using session tracking API.
Write Servlet to provide session management using Cookie.
Which code line must be set before any of the lines that use the PrintWriter?
When using servlets to build the HTML, you build a DOCTYPE line, why
do you do that?
JSP page
A JSP page is a text-based document that contains two types of text: static template
data, which can be expressed in any text-based format such as HTML, SVG, WML, and
XML, and JSP elements, which construct dynamic content.
Life cycle of JSP Page
The generated servlet class for a JSP page implements the HttpJspPage interface of the
javax.servlet.jsp package. The HttpJspPage interface extends the JspPage interface which
inturn extends the Servlet interface of the javax.servlet package. The generated servlet
class thus implements all the methods of these three interfaces. The JspPage interface
declares only two mehtods - jspInit() and jspDestroy() that must be implemented by all
JSP pages regardless of the client-server protocol. However the JSP specification has
provided the HttpJspPage interfaec specifically for the JSp pages serving HTTP requests.
This interface declares one method _jspService().
JSP page looks like a HTML page but is a servlet. When presented with JSP page the
JSP engine does the following 7 phases.
1. Translation JSP container checks the JSP page code and parses it to generate
the servlet source code. For example in Tomcat you will find generated servlet
class files at <tomcat>/WEBAPP/org/apache/jsp directory. If the JSP page
name is home.jsp, usually the generated servlet class name is home_jsp and file
name is home_jsp.java
2. Compilation JSP container compiles the jsp class source code and produce
class file in this phase.
3. Class Loading Container loads the class into memory in this phase.
4. Instantiation Container invokes the no-args constructor of generated class to
load it into memory and instantiate it.
5. Initialization Container invokes the init method of JSP class object and
initializes the servlet config with init params configured in deployment
descriptor. After this phase, JSP is ready to handle client requests. Usually from
translation to initialization of JSP happens when first request for JSP comes but
we can configure it to be loaded and initialized at the time of deployment like
servlets using load-on-startup element.
6. Request Processing This is the longest lifecycle of JSP page and JSP page
processes the client requests. The processing is multi-threaded and similar to
servlets and for every request a new thread is spawned and ServletRequest and
ServletResponse object is created and JSP service method is invoked.
7. Destroy This is the last phase of JSP lifecycle where JSP class is unloaded
from memory. Usually it happens when application is undeployed or the server
is shut down.
JSP lifecycle methods
JSP lifecycle methods are:
1. jspInit(): This method is declared in JspPage and its implemented by JSP
container implementations. This method is called once in the JSP lifecycle to
initialize it with config params configured in deployment descriptor. We can
override this method using JSP declaration scripting element to initialize any
resources that we want to use in JSP page.
2. _jspService(): This is the JSP method that gets invoked by JSP container for
each client request by passing request and response object. Notice that method
name starts with underscore to distinguish it from other lifecycle methods
because we cant override this method. All the JSP code goes inside this
method and its overridden by default. We should not try to override it using
JSP declaration scripting element. This method is defined in HttpJspPage
interface.
3. jspDestroy(): This method is called by container when JSP is unloaded from
memory such as shutting down application or container. This method is called
only once in JSP lifecycle and we should override this method to release any
resources created in JSP init method.
Servlet
Comments in JSP
Following syntax is sued to put comment in JSP Page.
<% JSP Comment %>
<! HTML Comment >
excellent server side scripting support for creating database driven web applications. JSP
enable the developers to directly insert java code into jsp file, this makes the development
process very simple and its maintenance also becomes very easy. JSP pages are efficient,
it loads into the web servers memory on receiving the request very first time and the
subsequent calls are served within a very short period of time.
In todays environment most web sites servers dynamic pages based on user request.
Database is very convenient way to store the data of users and other things. JDBC provide
excellent database connectivity in heterogeneous database environment. Using JSP and
JDBC its very easy to develop database driven web application.
Java is known for its characteristic of write once, run anywhere. JSP pages are
platform independent. Your port your .jsp pages to any platform.
Java Server Pages are saved with .jsp extension.
Installation and execution of JSP
Follow these steps to run JSP Page:
Step 1: Download and install latest Apache Tomcat and JAVA.
Step 2: Create directory JSPDemo and JSPDemo\WEB-INF directories under
the webapps as shown here:
Step 3: Create simple HelloWorld.jsp program using any editor like notepad:
<%
Document : HelloJSP.jsp
Author : J.B.Patel
%>
<%@page contentType=text/html pageEncoding=UTF-8%>
<!DOCTYPE HTML PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN
http://www.w3.org/TR/html4/loose.dtd>
<html>
<head>
<meta http-equiv=Content-Type content=text/html; charset=UTF-8>
<title>First JSP Page</title>
</head>
<body>
<p> Hi, <h3><%=Hello! %></h3></p>
</body>
</html>
Step 5: Before run this code, start apache tomcat as you have learned in Servlet
Section.
Step 6: Set path, java_home, and classpath variable as required from command line.
For example:
set JAVA_HOME=C:\Program Files\Java\jdk1.8.0_25\
set PATH=%JAVA_HOME%;%PATH%
set
CLASSPATH=.;D:\apache-tomcat-8.0.15\lib\servlet-api.jar;D:\apache-tomcat8.0.15\lib\jsp-api.jar;D:\apache-tomcat-8.0.15\lib\el-api.jar;
D:\apache-tomcat8.0.15\webapps\JSPDemo; %classpath%
Step 7:Start or Restart (if already running) Apache Tomcat Server
JSP engine then executes the compiled JSP file, or servlet, using the request values the
user submitted.
When you use scripting elements in a JSP file, you should know when they are
evaluated. Declarations are processed at HTTP translation time and are available to other
declarations, expressions, and scriptlets in the compiled JSP file. Expressions are also
evaluated at HTTP translation time. The value of each expression is converted to a String
and inserted in place in the compiled JSP file. Scriptlets, however, are evaluated at request
processing time, using the values of any declarations and expressions that are made
available to them.
JSP Expressions
A JSP expression is used to insert Java values directly into the output. It has the
following syntax:
<%= Java Expression %>
The Java expression is evaluated, converted to a string, and inserted in the page. This
evaluation is performed at run-time (when the page is requested), and thus has full access
to information about the request.
For example, the following shows the date/time that the page was requested:
Current time: <%= new java.util.Date() %>
To simplify these expressions, there are a number of predefined variables that you can
use. The most important ones are:
request, the HttpServletRequest;
response, the HttpServletResponse;
session, the HttpSession associated with the request (if any); and
out, the PrintWriter (a buffered version of type JspWriter) used to send output
to the client.
Heres an example:
<%
Document : ExpressionDemo.jsp
Author : J.B.Patel
%>
JSP Scriplets
A scriptlet tag is used to execute java source code in JSP. If you want to do something
more complex than insert a simple expression, JSP scriptlets let you insert arbitrary code
into the servlet method that will be built to generate the page. Scriptlets have the following
syntax:
<% Java Code %>
Scriptlets have access to the same automatically defined variables as expressions. So,
for example, if you want output to appear in the resultant page, you would use the out
variable.
Example: Using scriplet tag
<%
Document : ScripletDemo.jsp
Author : J.B.Patel
%>
<%@page contentType=text/html pageEncoding=UTF-8%>
<!DOCTYPE HTML PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN
http://www.w3.org/TR/html4/loose.dtd>
<html>
<head>
<meta http-equiv=Content-Type content=text/html; charset=UTF-8>
<title>JSP Scriplet Demo</title>
</head>
<body>
<p> <% out.print(This is Java Code inside JSP Page); %> </p>
</body>
</html>
Output:
Note that code inside a scriptlet gets inserted exactly as written and any static HTML
(template text) before or after a scriptlet gets converted to print statements. This means
that scriptlets need not contain complete Java statements, and blocks left open can affect
the static HTML outside of the scriptlets.
Example: JSP containing mixed HTML and scriptlets
<%
Document : ScripletDemo2.jsp
Author : J.B.Patel
%>
<%@page contentType=text/html pageEncoding=UTF-8 language=java%>
<!DOCTYPE HTML PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN
http://www.w3.org/TR/html4/loose.dtd>
<html>
<head>
<meta http-equiv=Content-Type content=text/html; charset=UTF-8>
<title>JSP Scriplet Demo2</title>
</head>
<body>
<p> <%!int age=23;%>
<% if (age < 18) { %>
You can not <B>Vote</B> baby!
<% } else { %>
Welcome to <B>voting club</B> Dear!
<% } %>
</p>
</body>
</html>
Output:
JSP Declarations
A JSP declaration lets you define methods or fields that get inserted into the main body
of the servlet class (outside of the service method processing the request). It has the
following synntax:
<%! Java Code %>
Since declarations do not generate any output, they are normally used in conjunction
with JSP expressions or scriptlets.
Example: Using declaration tag in JSP
<%
Document : DeclarationDemo.jsp
Author : J.B.Patel
%>
<%@page contentType=text/html pageEncoding=UTF-8%>
<!DOCTYPE HTML PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN
http://www.w3.org/TR/html4/loose.dtd>
<html>
<head>
<meta http-equiv=Content-Type content=text/html; charset=UTF-8>
JSP Directives
A JSP directive affects the overall structure of the servlet class. It usually has the
following syntax:
<%@ directive attribute=value %>
You can also combine multiple attribute settings for a single directive, as follows:
<%@ directive attribute1=value1 attribute2=value2 attributeN=valueN %>
The XML equivalent of defining directives is:
<jsp:directive.directiveType attribute=value />
For example, the XML equivalent of
<%@ page import=java.util.* %>
is
<jsp: directive.page import=java.util.* />
There are two main types of JSP directive:
Page Directove
Used to ets you do things like import classes, customize the servlet
superclass, and the like.
Include Directive
Used to insert a file into the servlet class at the time the JSP file is
translated into a servlet.
JSP page Directive
The page directive lets you define one or more of the following case-sensitive
attributes:
Attribute
Import
To
specify
what
packages
should be
imported.
The
import
attribute
is
the
only one
that is
Syntax
Example
import=package.class
<%@ page import=java.util.*
or import=package.class1, %>
,package.classN.
allowed
to appear
multiple
times.
contentType
contentType=MIME-
<%@
page
To
specify
the
MIME
Type or
contentType=text/plain %>
contentType=MIME-Type; Same effect as the scriptlet
charset=Character-Set
<%
response.setContentType(text/plain);
type of
the
output.
%>
The
default is
text/html.
isThreadSafe=true|false
A value of false indicates that the servlet should implement
SingleThreadModel, with requests either delivered serially or with simultaneous
requests being given separate servlet instances.
session=true|false
A value of true (the default) indicates that the predefined variable session (of
type HttpSession) should be bound to the existing session if one exists;
otherwise a new session should be created and bound to it.
A value of false indicates that no sessions will be used, and attempts to access
the variable session will result in errors at the time the JSP page is translated
into a servlet.
buffer=sizekb|none
This specifies the buffer size for the JspWriter out. The default is serverspecific, but must be at least 8kb.
autoflush=true|false
A value of true, the default, indicates that the buffer should be flushed when it is
full.
A value of false, indicates that an exception should be thrown when the buffer
overflows. A value of false is illegal when also using buffer=none.
extends=package.class
This defines a string that can be retrieved via the getServletInfo method.
errorPage=url.
*
This specifies a JSP page that should process any Throwables thrown but not
caught in the current page.
isErrorPage=true|false.
*
This indicates whether or not the current page can act as the error page for
another JSP page. The default is false.
language=java.
*
Description
request
response
client.
out
session
application
This
is
the
ServletContext
getServletConfig().getContext().
config
as
obtained
via
pageContext
page
This is simply a synonym for this, and is not very useful in Java. It
was created as a placeholder for the time when the scripting language
could be something other than Java.
</html>
Output:
con=DriverManager.getConnection(url,root,);
stmt=con.createStatement();
rst=stmt.executeQuery(SELECT * FROM studentinfo);
if (rst.next()) {
%>
<TABLE BORDER=1 BGCOLOR=C0C0C0>
<TH WIDTH=200 BGCOLOR=white> <I>Roll No</I> </TH>
<TH WIDTH=100 BGCOLOR=white> <I>Name</I> </TH>
<TR> <TD ALIGN=CENTER> <%= rst.getInt(1) %> </TD>
<TD ALIGN=CENTER> <%= rst.getString(2) %> </TD>
</TR>
<% while (rst.next()) {
%>
<TR> <TD ALIGN=CENTER> <%= rst.getInt(1) %> </TD>
<TD ALIGN=CENTER> <%= rst.getString(2) %> </TD>
</TR>
<% }
%>
</TABLE>
<% }
else {
%>
<P> Sorry, the query returned no rows! </P>
<%
}
rst.close();
stmt.close();
} catch (SQLException e) {
out.println(<P> + There was an error doing the query:);
out.println (<PRE> + e + </PRE> \n <P>);
}
%>
</table>
</center>
</body>
Output:
Before running this servlet care following:
Copy
mysql-connector-java-5.1.34-bin.jar
file
to
C:\Program
Files\Java\jdk1.8.0_25\jre\lib\ext folder
Set classpath to include servlet-api.jar file and mysql-connector-java-5.1.34bin.jar file.
set JAVA_HOME=C:\Program Files\Java\jdk1.8.0_25\
set PATH=%JAVA_HOME%;%PATH%
set
CLASSPATH=.;D:\apache-tomcat-8.0.15\lib\servlet-api.jar;
C:\Program
Files\Java\jdk1.8.0_25\jre\lib\ext\ mysql-connector-java-5.1.34-bin;D:\apache-tomcat8.0.15\lib\jsp-api.jar;D:\apache-tomcat-8.0.15\lib\el-api.jar;
D:\apache-tomcat8.0.15\webapps\JSPDemo; %classpath%
Syntax Summary
JSP
Element
JSP
Expression
Syntax
<%=
expression
%>
Interpretation
Notes
Expression
is
XML equivalent is
evaluated and placed <jsp:expression>
in output.
expression
</jsp:expression>.
Predefined
variables
are
<%
code %>
JSP
<%!
Declaration code %>
JSP
<%@
Code is inserted in
service method.
XML equivalent is
<jsp:scriptlet>
code
</jsp:scriptlet>.
Code is inserted in
XML equivalent is
body of servlet class, <jsp:declaration>
outside of service code
method.
</jsp:declaration>.
Directions to the
XML equivalent is
page
Directive
page
att=val
%>
JSP
include
Directive
<%@
include
file=url
%>
XML equivalent is
<jsp:directive.include
file=url\>.
The URL must be a relative one.
Use the jsp:include action to
include a file at request time
instead of translation time.
<%
Comment; ignored
JSP
Comment
generate HTML / XML documents. JSP allows the java code dynamically embedded
within a web page like HTML and gets executed when the page is served by the server.
After the page is served, the dynamic content is sent to the client. With the script, the page
is run on the server before it reaches to the client. JSP are used to invoke the built-in
functionalities. In addition to the HTML, the JSP technology adds a tag library which
provides a platform independent extending capabilities of a web server.
What is JSP and why do we need it?
JSP stands for JavaServer Pages. JSP is java server side technology to create dynamic
web pages. JSP is extension of Servlet technology to help developers create dynamic
pages with HTML like syntax.
We can create user views in servlet also but the code will become very ugly and error
prone. Also most of the elements in web page are static, so JSP page is more suitable for
web pages. We should avoid business logic in JSP pages and try to use it only for view
purpose. JSP scripting elements can be used for writing java code in JSP pages but its best
to avoid them and use JSP action elements, JSTL tags or custom tags to achieve the same
functionalities.
One more benefit of JSP is that most of the containers support hot deployment of JSP
pages. Just make the required changes in the JSP page and replace the old page with the
updated jsp page in deployment directory and container will load the new JSP page. We
dont need to compile our project code or restart server whereas if we make change in
servlet code, we need to build the complete project again and deploy it. Although most of
the containers now provide hot deployment support for applications but still its more
work that JSP pages.
What are the JSP lifecycle phases?
If you will look into JSP page code, it looks like HTML and doesnt look anything like
java classes. Actually JSP container takes care of translating the JSP pages and creates the
servlet class that is used in web application. JSP lifecycle phases are:
1. Translation JSP container checks the JSP page code and parses it to generate
the servlet source code. For example in Tomcat you will find generated servlet
class files at <tomcat>/WEBAPP/org/apache/jsp directory. If the JSP page
name is home.jsp, usually the generated servlet class name is home_jsp and file
name is home_jsp.java
2. Compilation JSP container compiles the jsp class source code and produce
the page comprises all the actions that are part of the JSP.
What are different types of comments in JSP?
JSP pages provide two types of comments that we can use:
HTML Comments: Since JSP pages are like HTML, we can use HTML
comments like < HTML Comment >. These comments are sent to client
also and we can see it in HTML source. So we should avoid any code level
comments or debugging comments using HTML comments.
JSP Comments: JSP Comments are written using scriptlets like <% JSP
Comment %>. These comments are present in the generated servlet source
code and doesnt sent to client. For any code level or debugging information
comments we should use JSP comments.
What are Scriptlet, Expression and Declaration in JSP?
Scriptlets, Expression and Declaration are scripting elements in JSP page using which
we can add java code in the JSP pages.
A scriptlet tag starts with <% and ends with %>. Any code written inside the scriptlet
tags go into the _jspService() method. For example;
<%
Date d = new Date();
System.out.println(Current Date=+d);
%>
Since most of the times we print dynamic data in JSP page using out.print() method,
there is a shortcut to do this through JSP Expressions. JSP Expression starts with <%= and
ends with %>.
<% out.print(Jitendra); %> can be written using JSP Expression as <%= Jitendra
%>
Notice that anything between <%= %> is sent as parameter to out.print() method. Also
notice that scriptlets can contain multiple java statements and always ends with semicolon
(;) but expression doesnt end with semicolon.
JSP Declarations are used to declare member methods and variables of servlet class.
JSP Declarations starts with <%! and ends with %>.
For example we can create an int variable in JSP at class level as <%! public static int
count=0; %>.
What is JSP Expression Language and what are its benefits?
Most of the times we use JSP for view purposes and all the business logic is present in
servlet code or model classes. When we receive client request in servlet, we process it and
then add attributes in request/session/context scope to be retrieved in JSP code. We also
use request params, headers, cookies and init params in JSP to create response views.
We can use scriptlets and JSP expressions to retrieve attributes and parameters in JSP
with java code and use it for view purpose.
What are JSP implicit objects?
JSP implicit objects are created by container while translating JSP page to Servlet
source to help developers. We can use these objects directly in scriptlets that goes in
service method; however we cant use them in JSP Declaration because that code will go
at class level.
We have 8 implicit objects that we can directly use in JSP page. Seven of them are
declared as local variable at the start of _jspService() method whereas one of them are part
of _jspService() method argument that we can use.
1. out Object
2. request Object
3. response Object
4. config Object
5. application Object
6. session Object
7. pageContext Object
8. page Object
Can we use JSP implicit objects in a method defined in JSP Declaration?
No we cant because JSP implicit objects are local to service method and added by JSP
Container while translating JSP page to servlet source code. JSP Declarations code goes
outside the service method and used to create class level variables and methods and hence
cant use JSP implicit objects.
Exercise
1. What is JSP technology?
2. What is JSP page?
3. What are the implicit objects?
4. How many JSP scripting elements and what are they?
Table of Contents
Advanced JAVA
Copyright Reserved by the Author
PREFACE
Unit I JAVA Applets
Concept of Applet Programming
Designing a Web page
Short Questions and Answers
Exercise
Unit II Introduction of Abstract Window Toolkit: (AWT)
Working with Windows and AWT
Working with frame windows
Working with graphics: AWT controls
Layout Managers
Event Handling in Java
Event Classes and Listener Interfaces
GUI with Swing
Short Questions and Answers
Exercise
Unit III Java Data Base Client/ Server
Java as a Database front end Database client/server methodology
JDBC Architecture
Common JDBC Components
JDBC Database Example
Current JDBC Drivers
Advantages Using JDBC
Limitations Using JDBC
Security Considerations
Short Questions and Answers
Exercise
Unit IV Servlets
Introduction to Web
Introduction to Servlet
The Life Cycle Of a Servlet
Servlet Container
Installing Servlets
The Servlet API
Reading Servlet Parameters
Reading Initialization Parameters
Handling HTTP Requests and responses
Session Tracking
Reading and displaying Records using servlet
Short Questions and Answers
Exercise
Unit V Java Server Pages: (JSP)
JSP technology
JSP page
Relation of Applets and Servlets with JSP
Comments in JSP
Simple JSP program
JSP Scripting Elements
JSP Expressions
JSP Scriplets
JSP Declarations
JSP Directives
Predefined Variables/implicit objects
JSP Databse Access
Short Questions and Answers
Exercise