Professional Documents
Culture Documents
Advanced-Java by Jitendra Patel PDF
Advanced-Java by Jitendra Patel PDF
JAVA
By Jitendra Patel
Copyright © Reserved by the Author
All rights reserved. No part of this book shall be reproduced, stored in a retrieval
system, or transmitted by any means, electronic, mechanical, photocopying, recording, or
otherwise, without written permission from the publisher. No patent liability is assumed
with respect to the use of the information contained herein. Although every precaution has
been taken in the preparation of this book, the publisher and author assume no
responsibility for errors or omissions. Nor is any liability assumed for damages resulting
from the use of the information contained herein.
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
Unit I JAVA Applets
Applets were intended to supply small functionality for activating Web pages.
However, as Java has matured, applets are now one way of delivering component-based
functionality to Web pages. The original intent is that applets would be small applications
- hence the name. Java applets take advantage of features that are built into Web browsers.
This enables developers to write applets that can contain a rich amount of functionality
with a minimal amount of code. One of the major uses of applets is to display graphics
and images. To incorporate GIF or JPEG files into a Java applet, it is not necessary to
write any special decoding methods to interpret the image files. Instead applets can use the
browser’s built-in decoder to display the images.
Applets are extensible. If a new image file format becomes the hot format and is
incorporated into the browser, the Java applet will automatically be able to handle the new
format.
Applets themselves are not written in HTML. Applets are written in Java.
Applet can be embedded in webpage. Applets are included in HTML page
using <APPLET> tag.
Applets are not executed on the server side. They are transferred to user’s
machine and then executed by the browser’s Java Virtual Machine (JVM).
Applets are executed inside the browser via the so-called “Java Plug-in”, which
is a JRE capable of running Java applets in a secure manner.
An applet has no life outside an HTML page that is being processed by a browser.
Thus the browser is the “container” of the applet and depends on the browser to call its
methods. In a sense, a specification between the browser and the applet exists, which is
driven by both the browser and the Java language.
Local and remote applets
There are two different applet types. The applet types vary based on how the applet is
embedded into web page. Applet Types are:
Local Applets
The web page will search the local system directories, find the local
applet and execute it.
Local Applet
Remote Applets
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 applet’s URL and any parameters to supply in
order to display the applet correctly.
Web Browser
Remote Machine
Applet
Remote Applet
<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
applet’s 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.
The JVM creates an instance of the applet class and invokes methods defined
within the applet during the applet’s lifetime.
Let’s begin with a quick introduction to some basic elements of applet programming.
Each applet starts out with a class definition, like this:
// to do
}
In this example, MyApplet is the name of the applet’s class.
All applets extend the java.applet.Applet class, also referred to simply as the
Applet class.
Another way to write the class definition is to use import to load the Applet class and
simplify the declaration:
import java.applet.Applet
// to do
}
Building applet code
The superclasses of Applet give all applets a framework on which you can build user
interface. These superclasses also provide a structure for the applet that must be used
when the program is developed. Here are steps to build a simple Applet in JAVA.
import java.awt.*;
1. Save the file, exit the editor, compile using javac and correct errors
<HTML>
<HEAD>
</HEAD>
<BODY>
</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
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:
/*
<applet code = SimpleApplet2 width=350 height =200>
</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.
Designing a Web page
Web documents are written in Hypertext Markup Language (HTML). HTML uses
tags to describe the structure of Web documents. Tags are used to identify headings,
paragraphs, and lists, as well as other elements of Web pages such as links, images,
forms, and applets. Applets are displayed as a part of a Web page by using the HTML tag
<APPLET>.
Example:
Method Description
An applet is like a child application of the browser. The browser launches the applet in
a predefined environment inside the browser. From within HTML, the syntax to specify
the execution of an applet is provided by the applet and parameter tags.
The applet tag provides all the information needed to launch the applet. Everything
from the base directory to command-line parameters can be specified from within this tag.
<HTML>
<HEAD>
<BODY>
</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.
You can run the applet using the applet viewer utility, which can be invoked from the
DOS
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
Applet ran using appletviewer utility
Running an Applet from a Web browser is straightforward. We simply need to add the
following applet tag somewhere in the body of the HTML.
This tag tells the Web browser to load the Applet from AppletHelloWorld.class and to
display it in an area that is 450 pixels wide by 100 pixels high. Because the code attribute
does not indicate a path, the Web browser will search for the AppletHelloWorld.class file
in the same directory that contains the HTML file.
A minimalistic HTML file for the Applet created above is shown below. To run the
Applet, click on the file title or the Java icon.
<html>
<head>
<title>Applet Hello World</title>
</head>
<body>
<applet
code=“AppletHelloWorld.class”
width=“450”
height=“100”>
Your browser does not support Applets.
</applet>
</body>
</html>
A screenshot of the Applet running from Firefox on Windows 7 is shown here:
There are five primary methods in the Applet class. The java.applet.Applet class
defines these methods for managing the life-cycle of the applets.
Method Description
start() Invoked every time the browser displays the web page
containing the applet. The start method is automatically called once
the browser calls the init method.
stop() Invoked when the browser is closed (and, some browsers, when
the browser is minimized or when the user leaves the web page by
going to another URL) – stops or suspends anything the applet is
doing e.g. if the start method started an animation, it should be
stopped in this method
destroy() Invoked when the browser determines that it no longer needs the
applet – this is when the applet is removed from the browser’s cache.
Therefore the invocation of this method is controlled by the browser
itself. Use to release resources used by the applet – but should do
this in the other methods e.g in stop() as it may be a long time before
destroy() is invoked.
paint() Called back when the applet drawing area must be refreshed,
e.g., another window partially covers the applet etc. Called
immediately after start, the paint method is what displays your
applet on a webpage. Paint is also called any time the applet needs
to repaint itself.
Applet Life Sequence
import java.awt.*;
public class LifeCycle extends Applet
{
String msg=“The currently executing method”;
public void init()
msg+=“init()”;
msg+=“start()”;
}
msg+=“stop()”;
{
g.drawString(msg,100,100);
showStatus(“Test applet”);
}
}
Compile and run the applet:
Parameters
Parameters are analogous to command-line arguments; they provide a way to pass
information to an applet. Each <param> tag contains a name and a value that are passed as
strings to the applet:
<APPLET
CODEBASE = codebaseURL
CODE = appletFile
ALT = alternateText
NAME = appletInstanceName
WIDTH = pixels HEIGHT = pixels
ALIGN = alignment
>
<PARAM NAME = appletAttribute1 VALUE = value>
<PARAM NAME = appletAttribute2 VALUE = value>
…
alternateHTML
</APPLET>
Example Applet with parameters
/*
* AppletWithPara.java
*/
import java.applet.*;
import java.awt.*;
/*
</applet>
*/
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:
Java applets retrieve parameter values using the getParameter() method in the applet’s
init() method.
The applet has to call the getParameter() method supplied by the java.applet.Applet
parent class to capture the passed parameters. Calling getParameter(“color”) using the
previous Java applet example would return a String value containing the text “blue”.
URL getCodeBase()
This method returns the URL of the applet
URL getDocumentBase()
This method returns the URL of the document containing the applet
Advantages of applets
1. An applet has limited access to the local and remote file systems. This is due in
part to both the security features of Java as well as the browser.
2. An applet class that was loaded from the Internet is not allowed to make any
native calls. These remote classes cannot execute any local commands. This
restriction is lifted for classes that are used by the applet but are loaded from
the local machine.
3. An applet cannot be a network socket server and may only open a socket
connection to the server machine that served the applet’s HTML page.
4. There are restrictions imposed on inter-applet communication that are also
driven by the browser.
destroy( ) method - called when the browser is finished with the applet.
1. What is the sequence for calling the methods by AWT for applets? - When
an applet begins, the AWT calls the following methods, in this sequence:
init()
start()
paint()
stop()
destroy()
We can pass parameters to an applet using <param> tag in the following way:
2. code, name
Correct answer is d.
Create/Edit a Java source file. This file must contain a class which
extends Applet class.
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.
Unit II Introduction of Abstract Window Toolkit: (AWT)
There are two sets of Java APIs for graphics programming: AWT
(Abstract Windowing Toolkit) and Swing.
1. AWT API was introduced in JDK 1.0. Most of the AWT components have
become obsolete and should be replaced by newer Swing components.
2. Swing API, a much more comprehensive set of graphics libraries that enhances
the AWT, was introduced as part of Java Foundation Classes (JFC) after the
release of JDK 1.1. JFC consists of Swing, Java2D, Accessibility,
Internationalization, and Pluggable Look-and-Feel Support APIs. JFC was an
add-on to JDK 1.1 but has been integrated into core Java since JDK 1.2.
AWT classes
WindowListener),
Event Listener Adapter classes (such as MouseAdapter, KeyAdapter,
and WindowAdapter).
AWT provides a platform-independent and device-independent interface to develop
graphic programs that runs on all platforms, such as Windows, Mac, and Linux.
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 java’s 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
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 setSize(int Sets the size (width and height) of the
width,int height) component.
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
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
Panel class is concrete sub class of Container. Panel does not contain title bar, menu
bar or border. It is the simplest of all the containers. It is used to layout a set of related
GUI components in pattern such as grid or flow. A Panel has no physical appearance. It is
just a rectangular display area. Its purpose is to provide a way to organize components as
they’re laid out in a window. The default LayoutManager of Panel is FlowLayout.
A Panel is the basic building block of an applet. It provides a container with no special
features. It provides a single constructor that takes no parameters. The Applet class of the
java.applet package is a subclass of the Panel class.
Example: A frame with an empty panel
import java.awt.*;
public class PanelDemo extends Panel
{
public static void main(String [] args)
f.pack();
f.show();
}
}
Output:
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.
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
fm.setTitle(“AWT Demo”);
Output:
import java.awt.*;
import java.awt.event.*;
public AWTDemo2()
Output:
By deriving the new class from class Applet instead of class Panel, this example can
now run as either a standalone application or as an applet embedded in a Web page.
import java.awt.*;
f.add(“Center”, a);
f.pack();
f.show();
Output
<html>
<head>
<title></title>
</head>
<body>
<APPLET code=“FrameAppletDemo.class” width=350 height=200>
</APPLET>
</body>
</html>
Output:
/*FrameApplet.java */
import java.awt.*;
import java.applet.*;
Frame frame;
Button button;
{
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> */
image = i;
}
g.drawImage(image, 0, 0, this);
}
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 component—however, a Canvas
component cannot be used as a place to put components.
Constructors of Canvas Class
Name Description
Method Description
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:
canvasDemo.java
*/
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code=CanvasDemo.class height=150 width=200>
</applet>
*/
Canvas c;
c=new Canvas( );
c.setBackground(Color.black);
c.setSize(50,90);
add(c);
}
}
Output:
import java.awt.Graphics;
public DrawingRegion() {
setSize(100, 50);
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>
*/
}
Output:
Working with graphics: AWT controls
AWT provides many ready-made and reusable GUI components. The frequently-used
are: Button, TextField, Label, Checkbox, CheckboxGroup(radio buttons), List,
and Choice, as illustrated below.
Buttons java.awt.Button
Checkboxes java.awt.Checkbox
Labels java.awt.Label
Lists java.awt.List
To be useful, a user interface must consist of more than just a container — it must
contain components. Components are added to containers via a container’s add()method.
There are three basic forms of the add() method. The method to use depends on the
container’s layout manager.
Example
Label lblInput; // Declare an Label instance called lblInput
lblInput = new Label(“Enter ID”); // Construct by invoking a constructor via the new
operator
add(lblInput); // this.add(lblInput) - “this” is typically a subclass of Frame
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.
// Allocate an anonymous Label instance. “this” container adds the instance into
itself.
// Same as
import java.awt.*;
import java.applet.Applet;
add(new Button(“Two”));
}
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
Let’s see how all components used to create GUI.
Labels
Constructor Action
Adding Label
The following code is used to create a Label component and add it to an applet
window:
add(l);
import java.awt.*;
{
public void init()
{
setLayout(new GridLayout(3,1));
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.
Constructor Action
Method Action
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.
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.
/* TextFieldsDemo.java*/
import java.awt.*;
{
public void init()
add(new TextField(12));
add(t);
}
Output:
import java.awt.*;
import java.awt.event.*;
t1.setText(“0”);
t2.setText(“0”);
t3.setText(“0”);
add(t1);
add(t2);
add(b1);
add(t3);
b1.addActionListener(this);
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
the LayoutManager, the TextAreas could be resized automatically.
Constructor Action
TextArea(int, int) Creates an empty text area with the given number of
rows and columns (characters)
TextArea(String, int, Creates a text area displaying the given string and
int) with the given dimensions
Method Action
/* TextAreaDemo.java */
import java.awt.*;
import java.awt.*;
import java.applet.*;
add(t1);
add(t2);
}
}
Output:
Push buttons
The Button component is a rectangular button that can be clicked with a mouse.
Constructor Action
Method Action
Creating a Button component and adding it to an applet window requires two lines:
add(b);
Because the add(b) method does not refer to a specific container object, it defaults to
adding the button to the applet surface. You can also create a new Panel and add a new
Button component to that panel:
p.add(b);
/*ButtonsDemo.java */
import java.awt.*;
import java.awt.*;
import java.applet.*;
add(b2);
if(evt.target.equals(b1))
getAppletContext().showStatus(“Button 1”);
else if(evt.target.equals(b2))
getAppletContext().showStatus(“Button 2”);
else
Output:
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
deselected indicating presence or absence of choice.
If a Checkbox object is not in a CheckboxGroup object, it is implemented as a
simple checkbox.
Constructor Action
Method Action
The following code is used to create a Checkbox component and add it to an applet
window:
Checkbox c = new Checkbox(“Listening Music”);
add(c);
/*CheckboxDemo.java */
import java.awt.*;
import java.awt.*;
import java.applet.*;
{
setLayout(new FlowLayout(FlowLayout.LEFT));
add(new Checkbox(“Floppy”));
add(new Checkbox(“CD”));
add(new Checkbox(“DVD”));
add(new Checkbox(“Pen Drive”, null, true));
add(new Checkbox(“Zip Drive”));
}
}
Output:
CheckboxGroup
Constructor Action
Method Action
c1.setCheckboxGroup(cbg);
c1.setState(false);
add(c1);
/*CheckboxgroupDemo.java */
import java.awt.*;
import java.applet.Applet;
{
CheckboxGroup cbg = new CheckboxGroup();
c1.setCheckboxGroup(cbg);
c1.setState(false);
add(c1);
add(c3);
}
Output:
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 Action
To create a list, you instantiate the list, add individual items to it, and then add the
loaded list to an applet window:
c.addItem(“Winter “);
c.addItem(“Summer “);
c.addItem(“Monsoon”);
add(c);
import java.awt.*;
import java.awt.*;
import java.applet.Applet;
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
The List class has two constructors:
Constructor Action
Method Action
The following code is used to create a scrolling list, add items to it, and then add the
list to an applet window:
lst.addItem(“CDR”);
lst.addItem(“CDRW”);
lst.addItem(“DVD”);
lst.addItem(“PenDrive”);
add(lst);
/*ScrollingListDemo.java */
import java.awt.*;
import java.awt.*;
import java.applet.Applet;
public void init() {
List lst = new List(5, true);
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 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.
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 Action
MenuBar( ) To create a
default menu bar.
Menu
Constructor of Menu
Constructor Action
MenuItem
MenuItem component are the text leaf nodes of a menu tree. MenuItems are added to a
Menu.
Constructor Action
MenuItem( String str, key is the short cut key for that
MenuShortcut key) Menu Item
CheckboxMenuItem
Constructor of CheckboxMenuItem
Constructor Action
Methods of Menu
Following are some common methods, which are used while creating a menu.
Method Action
/*MenuBarDemo.java*/
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
myFrame.setBounds(200,200,300,300);
myMenuBar.add(fileMenu);
Menu editMenu = new Menu(“Edit”);
myMenuBar.add(editMenu);
myFrame.setVisible(true);
}
extends WindowAdapter
myFrame.dispose();
}
}
Output:
Example: Using Menu Component
/*MenuDemo.java*/
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public void init()
{
myFrame = new Frame();
myFrame.addWindowListener(new Terminator());
myFrame.setBounds(200,200,300,300);
myFrame.setMenuBar(myMenuBar);
myMenuBar.add(editMenu);
MenuItem myMenuItem;
myMenuItem.addActionListener(this);
fileMenu.add(myMenuItem);
fileMenu.add(myMenuItem);
editMenu.add(myMenuItem);
myFrame.show();
}
{
if (e.getSource() instanceof MenuItem)
myTextField.setText(“Your Choice: ”
+ e.getActionCommand());
extends WindowAdapter
myFrame.dispose();
}
}
Output:
Example 2: Using Menu Component
/*MenuTest.java*/
import java.util.Vector;
import java.awt.*;
{
MenuTest ()
{
super (“MenuTest”);
MenuItem mi;
file.add (extras);
file.addSeparator();
file.add (“Quit”);
help.add (“About”);
MenuBar mb = new MenuBar();
mb.add (help);
mb.add (file);
mb.setHelpMenu (help);
setMenuBar (mb);
if (e.id == Event.WINDOW_DESTROY)
{
System.exit(0);
}
if (“Quit”.equals (o))
dispose();
System.exit(1);
else
{
System.out.println (“User selected ” + o);
CheckboxMenuItem cb = (CheckboxMenuItem)e.target;
return true;
return false;
}
Output:
Popup Menu
Example: Creating Popup Menu
/* PopupTest.java*/
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
PopupMenu popup;
MenuItem mi;
popup = new PopupMenu(“Title Goes Here”);
mi.addActionListener (this);
popup.addSeparator();
mi.addActionListener (this);
add (popup);
resize(200, 200);
enableEvents (AWTEvent.MOUSE_EVENT_MASK);
if (e.isPopupTrigger())
super.processMouseEvent (e);
}
}
}
Output:
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
FlowLayout
GridLayout
BorderLayout
CardLayout
Flow Layout
FlowLayout arranges swing components from left to right until there’s 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.
When there are too many components to fit, they “wrap” to a new row, similar to a
word processor with word wrap enabled.
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));
import java.awt.*;
import java.applet.*;
setLayout(new FlowLayout());
add(new Button(“One”));
add(new Button(“Two”));
add(new Button(“Three”));
add(new Button(“Four”));
add(new Button(“Five”));
add(new Button(“Six”));
Output:
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
When you add a component to the layout, you must specify which area to place it in.
The order in which components are added to the screen is not important but you can have
only one component in each area.
The add() method takes an additional parameter—a string that can be North, South,
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.*;
setLayout(new BorderLayout());
add(new Button(“One”));
add(new Button(“Two”));
add(new Button(“Three”));
add(new Button(“Four”));
add(new Button(“Five”));
add(new Button(“Six”));
}
}
Output:
/**
* BorderLayoutTest.java
*/
import java.awt.*;
import java.applet.*;
setLayout(new BorderLayout());
add(new Button(“One”),BorderLayout.NORTH);
add(new Button(“Two”),BorderLayout.SOUTH);
add(new Button(“Three”),BorderLayout.CENTER);
add(new Button(“Four”),BorderLayout.EAST);
add(new Button(“Five”),BorderLayout.WEST);
add(new Button(“Six”),BorderLayout.WEST);
}
}
Output:
Grid Layout
Component
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 needed—if you create a three-by-three grid and add a tenth item, a fourth row is
added.
import java.awt.*;
import java.applet.*;
add(new Button(“One”));
add(new Button(“Two”));
add(new Button(“Three”));
add(new Button(“Four”));
add(new Button(“Five”));
add(new Button(“Six”));
}
}
Output:
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.
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.
import java.awt.*;
import java.applet.*;
/*<applet code=CardLayoutTest.class width=200 height=100></applet>*/
cardPanel.setLayout(cards);
cardPanel.add(panel1, “First”);
cardPanel.add(panel3, “Third”);
}
}
Output:
/*CardStack.java*/
import java.awt.*;
import java.applet.*;
{
Panel canvasCards = new Panel();
canvasCards.setLayout( cardDeck );
p1.setLayout (new BorderLayout());
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);
}
{
cardDeck.next(canvasCards);
return true;
}
Output:
The GUI in Java processes the interactions with user via mouse; keyboard and various
user controls such buttons, checkbox, text-field etc. as the events. These events are to be
handled properly to implement Java Programming as an Event-Driven Programming.
How Events are handled?
To express interest for a certain source’s event, the listener(s) must be registered with
the source. In other words, the listener(s) “subscribes” to a source’s event, and the source
“publishes” the event to all its subscribers upon activation. This is known as subscribe-
publish 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.
Event Classes and Listener Interfaces
Java’s event handling mechanism is represented by event classes. At the root of the
java event class hierarchy is EventObject in java.util, which is the super class for all
events.
Low-level Events
Low-level events represent a low-level input or window operation, like a key press,
mouse movement, or window opening. The following table displays the different low-
level events, and the operations that generate each event (each operation corresponds to a
method of the listener interface):
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.
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 ActionListener
List
MenuItem
TextField
Choice ItemListener
Event class hierarchy
Checkbox
The super class of all the events Checkbox
is java.util.EventObject. This class CheckboxMenuItem
contains getSource() method which List
returns the source of the generated
event. An immediate subclass Scrollbar AdjustmentListener
of EventObject is the AWTEvent class
which is the super class of all AWT TextArea TextListener
based events. TextField
Low-Level Events
Component 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 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
Following is the list of AWT component and the events that can be generated by them
The event model supports the notion of event listeners – from the class
java.util.EventListener.
Java has defined a set of interfaces for receiving and processing the events under
the java.awt.event package
componentRemoved(ContainerEvent methods to
recognize when a
ce)
component is
added to or
removed from a
container
Action events are generated by specific types of action that you might want to respond
to, for example:
Clicking a button
ActionEvent Description
Method
ActionListener Description
Method
import java.awt.*;
import java.awt.event.*;
Button b;
public ActionEventDemo()
b=new Button(“Maximize/Restore”);
add(b);
b.addActionListener(this);
setLayout(new FlowLayout());
setLocationRelativeTo(null);
setVisible(true);
}
@Override
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
A MouseEvent is fired to all its registered listeners, when you press, release, or click
(press followed by release) a mouse-button (left or right button) at the source object; or
position the mouse-pointer at (enter) and away (exit) from the source object.
MouseEvent Description
Method
getClickCount() Returns the number of times the mouse was
clicked (use to determine if a double-click occurred
– so can have different responses to single and
double clicks)
MouseListener Description
Method
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public MouseEventDemo() {
setLayout(new FlowLayout());
tx.setEditable(false);
add(tx);
addMouseListener(this);
// “super” frame fires the MouseEvent so adds “this” object as MouseEvent listener
setTitle(“MouseEvent Demo”);
setSize(350, 100);
setVisible(true);
// MouseEvent handlers
@Override
tx.setText(e.getX() + ””);
ty.setText(e.getY() + ””);
@Override
public void mousePressed(MouseEvent e) { }
@Override
public void mouseReleased(MouseEvent e) { }
@Override
public void mouseEntered(MouseEvent e) { }
@Override
public void mouseExited(MouseEvent e) { }
}
Output:
In this example, we setup a GUI with 4 components (two Labels and two non-
editable TextFields), inside a top-level container Frame, arranged in FlowLayout.
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.
4. We register this object as the MouseEvent listener to super Frame (source) via
the method addMouseListener(this).
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 Description
Method
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
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);
xpos.setEditable(false);
add(xpos);
ypos.setEditable(false);
add(ypos);
addMouseListener(this);
addMouseMotionListener(this);
setTitle(“MouseMotion Demo”);
setSize(400, 120);
setVisible(true);
}
/** MouseListener handlers */
ty.setText(e.getY() + ””);
}
// Not Used, but need to provide an empty body for compilation
@Override
@Override
public void mouseReleased(MouseEvent e) { }
@Override
@Override
public void mouseExited(MouseEvent e) { }
@Override
xpos.setText(e.getX() + ””);
ypos.setText(e.getY() + ””);
Output:
In this example:
The MouseMotionListener (this class) needs to implement 2 abstract
methods: mouseMoved() and mouseDragged() declared in
the MouseMotionListener interface.
We override the mouseMoved() to display the (x, y) position of the mouse pointer.
We ignore the MouseDragged() handler by providing an empty body for
compilation.
A KeyEvent is fired (to all its registered KeyListeners) when you pressed, released,
and typed (pressed followed by released) a key on the source object. A KeyEvent listener
must implement KeyListenerinterface, which declares three abstract methods:
Method Description
public void Invoked when a key has been typed (pressed and
keyTyped(KeyEvent e) released).
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
setLayout(new FlowLayout());
add(new Label(“Enter Text: “));
add(Input);
Input.addKeyListener(this);
setSize(400, 200);
setVisible(true);
new KeyEventDemo();
// Called back when a key has been typed (pressed and released)
@Override
public void keyTyped(KeyEvent e) {
@Override
public void keyPressed(KeyEvent e) { }
@Override
public void keyReleased(KeyEvent e) { }
}
Output:
In this example:
We register this object as the KeyEvent listener to the source TextField via
method Input.addKeyListener(this).
Method Purpose
import java.awt.*;
import java.awt.event.*;
public WindowEventDemo()
setSize(400,400);
setLayout(new FlowLayout());
setLocationRelativeTo(null);
setVisible(true);
{
System.out.println(“Window Opened”);
}
System.out.println(“Window Closing”);
System.exit(0);
{
// Will not be printed
System.out.println(“Window Closed”);
setTitle(“Iconified”);
{
setTitle(“Deiconified”);
}
public void windowActivated(WindowEvent we)
{
System.out.println(“Window Activated”);
}
public void windowDeactivated(WindowEvent we)
{
System.out.println(“Window Deactivated”);
}
});
{
new WindowEventDemo();
Output:
Swing
Swing is a new feature provided by the JFC 1.1. Swing extends AWT by supplying
many more types of GUI components, providing 100% pure Java implementations of
these components, and gives the capability to change the appearance and behavior of these
components on different platforms. The Swing components are 100% pure Java. This
means that they don’t depend on the native window implementation to support them.
Swing components are available and consistent across all platforms. Swing components
do not use AWT components. In fact, all the traditional AWT components are re-
implemented as Swing components.
Swing API is set of extensible GUI Components to ease developer’s 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
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.
javax.swing.text The text package contains the support classes for the
Swing document framework
.
Swing Controls
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.
Components Hierarchy
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.
It contains the default Java icon on the far left of the titlebar, title in the center, the
minimize and maximize buttons, as well as a close button to the far right of the titlebar,
The icon can be changed to any image by using the setIconImage method. The current
image can be queried with the getIconImage method.
Using JFrame, you can to add the child to the JFrames contentPane as:
frame.getContentpane().add(child);
Note: Content Pane is a layer on some of the swing components eg. JFrame and
Japplet and acts like a container for other components, when it is necessary to have a
different look and feel for the same components.
JApplet
JApplet is a java swing public class designed for developers usually written in Java.
JApplet is generally in the form of Java bytecode that runs with the help of a Java virtual
machine (JVM) or Applet viewer from Sun Microsystems. It was first introduced in 1995.
JApplet can also be written in other programming languages and can later be compiled to
Java byte code.
import javax.swing.JApplet;
import java.awt.*;
/*<applet code= JAppletDemo.class width=200 height=150></applet>*/
{
final int radius = 25;
{
gr.setColor( Color.black );
}
Output:
JFrame
JFrame is the Swing equivalent of AWT Frame. It adds double buffering to avoid
flickering during drawing.
{
new JFrameDemo();
}
JFrameDemo() {
setTitle(“JFrame Demo”);
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
setVisible(true);
}
Output:
JLabel
Add an Icon
Set the vertical and horizontal position of text relative to the Icon
Set the relative position of contents within component
Constructor:
import javax.swing.*;
import java.awt.*;
add(plainLabel);
// Create a 2nd JLabel
fancyLabel.setFont(fancyFont);
// Create an Icon
fancyLabel.setIcon(tigerIcon);
fancyLabel.setHorizontalAlignment(JLabel.RIGHT);
// Add to panel
add(fancyLabel);
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
public static void main ( String[] args )
{
JLabelDemo test = new JLabelDemo( “JLabel Demo” ) ;
test.setSize ( 300, 100 );
test.setVisible( true );
}
}
Output
import java.awt.*;
/*<applet code= JLabelDemo2.class width=200 height=150></applet>*/
public JLabelDemo2( ) {
add(plainLabel);
// Create an Icon
Icon tigerIcon = new ImageIcon(“Plus.gif”);
// 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.
JButton’s can have an image and/or text label with controllable placement
Constructor:
import javax.swing.*;
import java.awt.*;
super(title);
setLayout(new GridLayout(3, 2));
Icon plus = new ImageIcon(“plus.gif”);
add(b1);
add(b2);
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
test.setVisible( true );
Output:
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.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SwingTextDemo extends JFrame {
public SwingTextDemo(String title){
super(title);
setSize(400,400);
add(userText);
setVisible(true);
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
Output:
import java.awt.event.*;
import javax.swing.*;
JFrame f = new JFrame(“Text Field Examples”);
f.getContentPane().setLayout(new FlowLayout());
f.getContentPane().add(new JTextField(“Hello”));
t.setText(“Name Please!”);
f.getContentPane().add(t);
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.
public CheckboxDemo () {
cb1.setIcon(unchecked);
cb1.setSelectedIcon(checked);
cb2.setIcon(unchecked);
cb2.setSelectedIcon(checked);
add(Hobby);
add(cb1);
add(cb2);
}
public static void main ( String[] args )
{
CheckboxDemo ob = new CheckboxDemo () ;
state = s;
}
public void paintIcon (Component c, Graphics g, int x, int y) {
g.setColor (Color.black);
if (state)
else
}
public int getIconWidth() {
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.
Constructors:
JRadioButton(): creates an unselected radio button with no text.
import java.awt.*;
add (radioButton);
rbg.add (radioButton);
radioButton.setSelected(true);
add (radioButton);
rbg.add (radioButton);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main ( String[] args )
{
RadioButtonDemo ob = new RadioButtonDemo (“JRadioButton Demo”) ;
}
}
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.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
super(title);
setLayout(new GridLayout(3, 2));
}
s.setEditable(false);
s.setSelectedItem(“Monsoon”);
s.setMaximumRowCount(4);
add(fs);
add(s);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
{
ComboBoxDemo ob = new ComboBoxDemo(“JComboBox Demo”) ;
ob.setVisible( true );
Output:
Menus
The menuing model used in Swing is nearly identical to that used in AWT. There are
three key exceptions:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
System.out.println (e.getActionCommand());
}
public JMenuDemo() {
JMenuItem item;
item.addActionListener (this);
file.addSeparator();
jmb.add (file);
item.addActionListener (this);
item.addActionListener (this);
//item.addActionListener (this);
jmb.add (edit);
check.addActionListener (this);
choice.add (check);
choice.add (rad);
rbg.add (rad);
rad.addActionListener (this);
rad = new JRadioButtonMenuItem (“Black & White”);
choice.add (rad);
rbg.add (rad);
rad.addActionListener (this);
jmb.add (choice);
setJMenuBar (jmb);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
{
JMenuDemo ob = new JMenuDemo() ;
ob.setVisible( true );
}
}
Output:
Layout manager is used for laying the components that are added to the
container.
The sizes and the positions of the components are set by using layout managers
The rules for arranging components are different for each layout mangers.
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:
Card Layout:
Grid Layout:
A group of components are laid out I equal size and displays them in certain
rows and columns
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.
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.
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.
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.
Unit III Java Data Base Client/ Server
Database is organized collection of data. Database Management System provides
mechanisms for storing, organizing, retrieving and modifying data. Relational DBMS is
popular standard. SQL is a language used to create, manipulate, examine, and manage
relational databases. SQL was standardized in 1992 so that a program could communicate
with most database systems without having to change the SQL commands.
JDBC is a Java API for executing SQL statements. It is a considered as standard for
Java Database Connectivity. JDBC consists of a set of classes and interfaces written in
Java. Using JDBC, it is easy to send SQL statements to virtually any relational database.
The combination of Java and JDBC makes it possible for a programmer to “write it once
and run it anywhere”.
JDBC Architecture
The JDBC Architecture consists of two layers:
The JDBC API, which provides the application-to-JDBC Manager 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.
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.
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 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.
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.sql package
This package includes classes and interface to perform almost all JDBC operation such
as creating and executing SQL Queries.
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.
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.
javax.naming and
javax.sql
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:
Three JDBC - Net - This driver passes the JDBC calls to proxy
Pure Java Drivers server which communicates with the database.
This driver converts JDBC calls into DBMS
independent network protocol that is sent to the
middleware server. This will translate this
DBMS independent network protocol into
DBMS specific protocol, which is sent to a
particular database. The results are again
rooted back to middleware server and sent
back to client.
Two 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
Slow execution time
Dependent on ODBC Driver.
Uses Java Native Interface (JNI) to make ODBC call.
Advantage
Faster as compared to Type-1 Driver
Contains additional features.
Disadvantage
Requires native library
Increased cost of Application
Advantage
Disadvantage
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
Disadvantage
Creating connection
Creating statement
Executing queries
Closing connection
Class.forName(“oracle.jdbc.driver.OracleDriver”);
while(rs.next()){
System.out.println(rs.getInt(1)+” ”+rs.getString(2));
con.close();
Connection Class
Methods
Parameters:
resultSetType - a result set type; one of
ResultSet.TYPE_FORWARD_ONLY,
ResultSet.TYPE_SCROLL_INSENSITIVE, or
ResultSet.TYPE_SCROLL_SENSITIVE
Statement Class
Methods
Following steps are required to create a new Database using JDBC application:
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.
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.
import java.sql.*;
// Database credentials
static final String USER = “root”;
try{
//STEP 2: Register JDBC driver
Class.forName(“com.mysql.jdbc.Driver”);
System.out.println(“Connecting to database…”);
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println(“Creating database…”);
stmt = conn.createStatement();
stmt.executeUpdate(sql);
System.out.println(“Database created successfully…”);
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end try
System.out.println(“Goodbye!”);
}//end main
}//end JDBCExample
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
1. Load Driver Class: The Driver Class for MySQL database is
com.mysql.jdbc.Driver and Class.forName(“com.mysql.jdbc.Driver”) method
is used to load the driver class for MySQL database.
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.
// Database credentials
public static void main(String[] args) {
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);
catch(SQLException se){
se.printStackTrace();
}
catch(Exception e){
e.printStackTrace();
}
finally{
try{
if(stmt!=null)
stmt.close();
catch(SQLException se2){
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…
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) {
try{
Class.forName(“com.mysql.jdbc.Driver”);
System.out.println(“Connecting to database…”);
pst.setInt(1,101);
pst.setString(2,“Jainik”);
pst.executeUpdate();
pst.setInt(1,102);
pst.setString(2,“Krinal”);
pst.executeUpdate();
catch(SQLException se){
se.printStackTrace();
}
catch(Exception e){
}
finally{
try{
if(conn!=null)
conn.close();
}
catch(SQLException se){
se.printStackTrace();
System.out.println(“Goodbye!”);
}
}
Output:
Connecting to database…
Goodbye!
Process completed.
// Database credentials
static final String USER = “root”;
Class.forName(“com.mysql.jdbc.Driver”);
System.out.println(“Connecting to database…”);
while(rs.next()){
System.out.println(rs.getInt(1)+” “+rs.getString(2));
catch(SQLException se){
se.printStackTrace();
}
catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}
finally{
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
Go to Administrative tools
Assumed that you have created a student table with sid and name column name in
access database.
import java.sql.*;
class TestAccessDB
try{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Connection con = DriverManager.getConnection(“jdbc:odbc:Test”, ””, ””);
while(rs.next()){
System.out.println(rs.getInt(1)+” “+rs.getString(2));
}
con.close(); //closing connection
}catch(Exception e)
e.printStackTrace();
}
}
To connect a Java application with Oracle database using Thin Driver. You need to
follow the following steps
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.
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.
Connection Management
Auto loading of Driver Interface.
Better exception handling
Support for large object
Annotation in SQL query.
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.
JDBC should not allow untrusted applets access to local database data
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 doesn’t 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.
However as with applets, if for some reason an untrusted sun.sql.Driver class is loaded
from a remote source, then that Driver should only be used with code loaded from that
same source.
These rules all apply at connection open time. This is the point when the driver and the
virtual machine should check that the current caller is really allowed to connect to a given
database. After connection open, no additional checks are necessary.
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.
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, that’s 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.
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.
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.
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 statment’s current ResultSet object if an open one exists.
Explain how to use JDBC statement to execute SQL queries. Show in an example
Example:
Statement stmt = conn.createStatement();
ResultSet rslSet = stmt.executeQuery(“SELECT LastName FROM Employees
WHERE empId = 548521”);
// Displaying the details of the result set
while (rslSet.next()) {
String lastName = rslSet.getString(“LastName”);
System.out.println(lastName + “\n”);
}
Example:
Statement execute(String query) is used to execute any SQL query and it returns
TRUE if the result is an ResultSet such as running Select queries. The output is FALSE
when there is no ResultSet object such as running Insert or Update queries. We can use
getResultSet() to get the ResultSet and getUpdateCount() method to retrieve the update
count.
Statement executeQuery(String query) is used to execute Select queries and returns the
ResultSet. ResultSet returned is never null even if there are no records matching the query.
When executing select queries we should use executeQuery method so that if someone
tries to execute insert/update statement it will throw java.sql.SQLException with message
“executeQuery method can not be used for update”.
Statement executeUpdate(String query) is used to execute Insert/Update/Delete
(DML) statements or DDL statements that returns nothing. The output is int and equals to
the row count for SQL Data Manipulation Language (DML) statements. For DDL
statements, the output is 0.
You should use execute() method only when you are not sure about the type of
statement else use executeQuery or executeUpdate method.
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.
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.
How many JDBC driver types does Sun define?
A. One B. Two
C. Three D. Four
A. In the MySQL database metadata
Which JDBC driver Type(s) can be used in either applet or servlet code?
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 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
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
their own Web Containers.
Most popular Open Source Web Containers are: Apache Tomcat, Jetty and
Glassfish.
We must import javax.servlet.*; javax.servlet.http.*; packages in order to create
a servlet.
Functions of Servlets
This data may be in a form on a Web page, from a Java applet or a custom HTTP
client program.
Look up any other information about the request that is embedded in the
HTTP request.
This information includes details about browser capabilities, cookies, the host
name of the requesting client etc…
This process may require database operations, executing an RMI or CORBA call
or direct response.
In most cases, this involves embedding the information inside an HTML page.
This means informing the browser about the type of document being returned
(e.g., HTML), setting cookies and caching parameters, and other such tasks.
This document may be sent in text format (HTML), binary format (GIF images),
or even in a compressed format like gzip that is layered on top of some other
underlying format.
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 can’t 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 servlets are written in java, servlets inherit the strong type safety of java
language. Java’s 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 Java’s exception handling mechanism. If any
exception occurs then it will throw an exception.
Integration
Servlets are tightly integrated with the server. Servlet can use the server to
translate the file paths, perform logging, check authorization, and MIME type
mapping etc.
Extensibility
The servlet API is designed in such a way that it can be easily extensible. As it
stands today, the servlet API support Http Servlets, but in later date it can be
extended for another type of servlets.
Inexpensive
There are number of free web servers available for personal use or for
commercial purpose. Web servers are relatively expensive. So by using the free
available web servers you can add servlet support to it.
Servlet Vs Applet
Servlet Applet
A Java servlet executes on the Web A Java Applet executes on the Web
server in response to requests from a Web browser.
browser.
Servlet are more powerful than Applet Java Applets are limited to certain
operations on the browser.
Servlets can be used for server side Applets can be used for client side
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.
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.
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 servlet’s service() method. The service() method reads the
request and produces the response message from its two parameters:
The service() method’s job is conceptually simple—it 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.
With POST, you can request something and at same time send form data to server.
It should be handled by doPost() method.
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 IDE’s (like Eclipse, NetBeans etc) and
promotes ease of development.
Web container is responsible for managing execution of servlet. The life cycle of
event is controlled by the web container in which the servlet has been deployed. When a
request is mapped to a servlet, the container performs the following steps:
1. If an instance of the servlet does not exist, the web container loads the servlet
class, creates an instance of the servlet class and initializes the servlet instance
by calling the init method.
2. Invokes the service method, passing request and response objects.
3. If the container needs to remove the servlet, it finalizes the servlet by calling
the servlet’s destroy method.
The container creates multiple threads to process multiple requests to a single servlet.
Servlet don’t have a main() method. Web Container manages the life cycle of a servlet
instance.
a. HttpServletRequest
b. HttpServletResponse
1. The container creates or allocates a thread for that request and calls the
servlet’s 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
servlet’s 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
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 JSDK’s
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
Once you have written your servlet, you can run it in many web servers, or in
the servletrunner.
The servletrunner is a small, multithreaded process that handles requests for servlets.
Because servletrunner is multi-threaded, it can be used to run multiple servlets
simultaneously, or to test one servlet that calls other servlets to satisfy client requests.
Unlike some web servers, servletrunner does not automatically reload updated
servlets. However you can stop and restart servletrunner with very little overhead to run a
new version of a servlet.
Properties
Properties are key-value pairs, used for the configuration, creation, and initialization of
a servlet.
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
backlog = 50
max handlers = 100
timeout = 5000
servletdir = ./examples
document dir = ./examples
servlet propfile = ./examples/servlet.properties
Invoking servletrunner with the -help flag shows a usage message without running it:
>servletrunner -help
Syntax:
servletrunner [options]
Options:
-v verbose output
To see the default values of these options, call servletrunner with the -v option:
>servletrunner -v
Server settings:
port = 8080
backlog = 50
//HelloServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
HttpServletRequest request,
HttpServletResponse response
response.setContentType(“text/html”);
try
{
out.println(“<HTML><HEAD><TITLE>”);
out.println(title);
out.println(“</TITLE></HEAD><BODY>”);
}
finally
{
out.close();
}
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.
Servlets can be called directly by typing their URL into a browser’s location
window. This is how you access the main page of example.
Once the servletrunner is executing, you run servlets by calling them directly in your
browser, or by using a form that calls a servlet to process its data. The URL for a servlet
has the following general form:
http://machine-name:port/servlet/servlet-name
where servlet-name corresponds to the name you have given your servlet.
Use the following URL. (It assumes that servletrunner is running on machine
(localhost), at port 8080, and that the HelloServlet servlet is located in the servlet
directory provided to servletrunner at startup:
http://localhost: 8080/servlet/HelloServlet
Output:
Creating Servlet using Apache
Creating a servlet
When a request comes in for the servlet, the Web Container calls the
servlet’s service() method and depending on the type of request the service() method calls
either the doGet() or doPost() method.
Steps to create servlet using tomcat server
To create a servlet application you need to follow some steps. These steps are common
for the entire Web server. In our example we are using Apache Tomcat server. Apache
Tomcat is an open source web server for testing servlets and JSP technology. Download
latest version of Tomcat Server and install it on your machine.
After installing Tomcat Server on your machine follow the following steps.
Click OK->OK->OK
1. Configure Tomcat Server
Locate the following lines that define the HTTP connector, and change
port=“8080” to port=“9999”.
redirectPort=“8443” />
Locate the following lines that define the “default” servlet; and change
the “listings” from “false” to “true”.
a. Enable Automatic Reload
The Java defines a unique directory structure that must be followed to create
a servlet application.
i. Create root directory “hello” inside Tomcat’s webapps directory.
a. Restart your Tomcat server to pick up the hello webapp. Check the
Tomcat’s console to confirm that “hello” application has been properly
deployed.
a. You can issue the following URL to access the web application “hello
ii. Check and Set path environment variable to point to JDK’s bin
directory
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.*;
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType(“text/html”);
out.println(docType +
“<HTML>\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
Method Description
public void destroy() Called when the servlet is unloaded (being taken out of
service method). Happens during web-container shut down.
The javax.servlet package contains many interfaces and classes that are used by the
servlet or web container. These are not specific to any protocol. All servlets must
implement the Servlet interface, which defines life-cycle methods.
1. GenericServlet
2. ServletInputStream
3. ServletOutputStream
4. ServletRequestWrapper
5. ServletResponseWrapper
6. ServletRequestEvent
7. ServletContextEvent
8. ServletRequestAttributeEvent
9. ServletContextAttributeEvent
10. ServletException
11. UnavailableException
Interface Description/Use
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
HttpServlet Class
doGet()
doPost()
doHead()
doPut()
doDelete()
doOptions()
doTrace()
The HttpServlet class reads the HTTP request, and determines if the request is an
HTTP GET, POST, PUT, DELETE, HEAD etc. and calls one of the corresponding
method. To respond to e.g. HTTP GET requests only, you will extend
the HttpServlet class, and override the doGet() method only. Here is an example:
response.getWriter().write(“<html><body>GET response</body></html>”);
}
}
If you want to handle both GET and POST request from a given servlet, you can
override both methods, and have one call the other. Here is how:
HttpServletResponse response)
throws ServletException, IOException {
response.getWriter().write(“GET/POST response”);
<input type=submit>
</form>
http://www.testsite.com/login?username=jbpatel
Instead of adding request parameters to the end of the URL, it is also possible
to POST them as actual data.
To the Servlet, it makes no difference which request method (GET or POST) was used
to send the parameters. In either case, we read the parameter using
the getParameter() method of HttpServletRequest:
If the given parameter was not set, then null was returned.
In this example I’ll show you how to read the parameter to process user action in a
very simple login servlet.
Directory Structure:
<head>
<title>Login Page</title>
</head>
<body>
<label>Username</label>
<input type=“text” name=“username” />
<label>Password</label>
</form>
</body>
</html>
In this form you’ll have to input box for username and password. You also have a
submit button for executing the login procces. Now we have the form, let’s 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);
// Reading the parameters from servlet request
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/).
<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:
If you enter invalid information you get following output:
In order to get all Request Parameters in Servlet, one should take the following steps:
//GetAllParams.java
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
handleRequest(req, res);
}
public void doPost(HttpServletRequest req, HttpServletResponse res) throws
IOException {
handleRequest(req, res);
res.setContentType(“text/plain”);
Enumeration<String> parameterNames = req.getParameterNames();
while (parameterNames.hasMoreElements()) {
out.write(paramName);
out.write(“n”);
out.write(“\t” + paramValue);
out.write(“\n”);
}
}
out.close();
<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:
After submitting username and password when you press login button you are
redirected to servlet processing:
HTTP parameters are generally used to pass user-supplied data. They should not be
confused with HTTP request headers, which are generally used to carry “meta”
information, such as the character encoding, referring page, type of browser etc.
Method Description
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 are available to any servlet or JSP that are part
of the current web app.
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 servlet’sServletConfig object.
Here is how you configure them in the web.xml file:
<servlet>
<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{
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
<html>
<head>
</head>
<body>
</form>
</body>
</html>
Output:
After pressing login button initialization parameters are read from web.xml file and
used by servlet:
You can also set some context parameters which can be read from all servlets in your
application.
Servlet Context
A servlet lives and dies within the bounds of the server process. To understand its
operating environment, a servlet can get information about its environment at different
times. Servlet initialization information is available during servlet start-up; information
about the hosting server is available at any time; and each service request can contain
specific contextual information.
<head>
<body>
<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.*;
public void init(ServletConfig config)throws ServletException {
this.config = config;
super.init(config);
try {
response.setContentType(“text/plain”);
out.println(“Welcome:”+email );
}
catch (Exception e) {
System.out.println(e.getMessage());
web.xml
<web-app version=“3.0”
xmlns=“http://java.sun.com/xml/ns/javaee”
xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”
xsi:schemaLocation=“http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd”>
<servlet>
<servlet-name>ContextParam</servlet-name>
<servlet-class>ContextParam</servlet-class>
</servlet>
<servlet-mapping>
<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:
The ServletContext object is contained within the ServletConfig object. That is, the
ServletContext can be accessed using the ServletConfig object within a servlet. You can
specify param-value pairs for ServletContext object in <context-param> tags in web.xml
file.
Method Description
The GET and POST requests are commonly used when handling form input.
doDelete()
doGet()
doHead()
doOptions()
doPost()
doPut()
doTrace()
We should select one of doGet or doPost methods for overriding. This choice depends
on what type of http request (GET request or POST request) we are expecting. GET
request is generally only used to retrieve data from the web server, however POST request
are used for more complex requests like storing data.
Some important methods of ServletRequest:
Methods Description
int getServerPort() returns the port number to which the request was
sent
HttpServletRequest interface
HttpServletRequest interface adds the methods that relates to the HTTP protocol.
Methods Description
String returns the portion of the request URI that indicates the
getContextPath() context of the request
String returns the query string that is contained in the request URL
getQueryString() after the path
HttpSession returns the current HttpSession associated with this request
getSession() or, if there is no current session and create is true, returns a new
session
String Returns the name of the HTTP method with which this
getMethod() request was made, for example, GET, POST, or PUT.
String returns any extra path information associated with the URL
getPathInfo() the client sent when it made this request.
String returns the part of this request’s URL that calls the servlet
getServletPath()
Servlet Response
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 Description
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.
void sets the locale of the response, if the response has not
setLocale(Locale loc) been committed yet.
HttpServletResponse interface
HttpServletResponse interface adds the methods that relates to the HTTP response.
String gets the value of the response header with the given
getHeader(String name.
name)
void sets a response header with the given name and value
setHeader(String
name, String value)
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
<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”
“http://www.w3.org/TR/html4/loose.dtd”>
<html>
<head>
</head>
<body>
<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>
</form>
</body>
</html>
ColorGetServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType(“text/html”);
PrintWriter pw = response.getWriter();
pw.println(“<B>The selected color is: ”);
pw.println(color);
pw.close();
}
}
The doGet( )method is overridden to process any HTTP GET 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.
web.xml
<servlet>
<display-name>ColorGetServlet</display-name>
<servlet-name>ColorGetServlet</servlet-name>
<servlet-class>ColorGetServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ColorGetServlet</servlet-name>
<url-pattern>/ColorGetServlet</url-pattern>
</servlet-mapping>
</web-app>
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.
ColorPOST.html
<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”
“http://www.w3.org/TR/html4/loose.dtd”>
<html>
<head>
</head>
<body>
<form id=“ContextParam” action=”/PostDemo/ColorPostServlet” method=“POST”>
<B>Color:</B>
<option value=“Green”>Green</option>
<option value=“Blue”>Blue</option>
</select>
<br><br>
</body>
</html>
ColorPostServlet .html
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
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” version=“2.4”
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>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>
Output
The service() method of the HttpServlet identifies HEAD requests and treats them
specially. It constructs a modified HttpServletResponse object and passes it, along with an
unchanged request, to the doGet()method. The doGet() method proceeds as normal, but
only the headers it sets are returned to the client. The special response object effectively
suppresses all body output.
Index.htm
</head>
<body>
<br><br>
</body>
</html>
HeadRequestServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
res.setContentType(“text/html”);
if (req.getMethod().equals(“HEAD”))
return;
// Proceed otherwise
PrintWriter out = res.getWriter();
out.println(“Hello, ” + name);
out.println(“</BODY></HTML>”);
}
web.xml
<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:
When you press submit button:
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.
2. Cookies
3. Hidden Form Field
Java Servlet API provides an interface called HttpSession that can be used to keep
track of sessions in the Current servlet context.
Method Description
boolean b=s.IsNew(); Returns the Value true If the new Session ID has been
created and has not been sent the client.
long This function returns the time when the session was
l=s.getCreationTime(); created in miliseconds.
You don’t have to use them to get rid of stale (inactive) sessions. The container can do
it for you.
1. It times out.
Or
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>
<meta http-equiv=“Content-Type” content=“text/html; charset=UTF-8”>
<title>Handling Session</title>
</head>
<body>
<form id=“SessionDemo” action=”/SessionDemo/SessionServlet” method=“GET”>
<label>Username</label>
<br><br>
<input type=submit value=“Submit”>
</form>
</body>
</html>
SessionServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
try{
response.setContentType(“text/html”);
String n=request.getParameter(“name”);
out.print(“Welcome: “+n);
HttpSession session=request.getSession();
session.setAttribute(“uname”,n);
}catch(Exception e){System.out.println(e);}
SessionTrack.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
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”?>
<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>
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.
They are created by the server and sent to the client with the HTTP response
headers.
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.
Cookie c[]=request.getCookies();
Now, let’s 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
GetCookiesServlet.java
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
<head>
<meta http-equiv=“Content-Type” content=“text/html; charset=UTF-8”>
</form>
</body>
</html>
AddCookieServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
HttpServletResponse response)
response.addCookie(cookie);
// Write output to browser.
response.setContentType(“text/html”);
PrintWriter pw = response.getWriter();
pw.close();
}
Above code gets the value of the parameter named “data”. It then creates
a Cookie object that has the name “MyCookie” and contains the value of
the “data” parameter. The cookie is then added to the header of the HTTP
response via the addCookie( ) method. A feedback message is then written to the browser.
GetCookiesServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType(“text/html”);
PrintWriter pw = response.getWriter();
pw.println(“<B>”);
for(int i = 0; i < cookies.length; i++) {
String name = cookies[i].getName();
}
pw.close();
}
After completing these steps, you will observe that a feedback message is displayed by
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”);
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.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.
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:
URL-Rewritting
If web browser at Client side has disabled Cookie then Session API fails. If client
won’t take cookies, you can use URL rewriting as a back up. URL rewriting is a better
way to maintain sessions when the browsers don’t support cookie. So URL rewriting is a
better way to maintain sessions.
Create Table
Now create table inside the databse in MySQL as:
CREATE TABLE ‘STUDENTS’.`studentinfo` (
);
Insert Records in the table
Here is an example which shows how to access Students database using Servlet.
DatabaseAccess.java
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
// Database credentials
final String USER = “root”;
final String PASS = ””;
response.setContentType(“text/html”);
String docType =
“transitional//en”>\n”;
out.println(docType +
“<html>\n” +
“<body bgcolor=”#f0f0f0”>\n” +
“<h1 align=“center”>” + title + “</h1>\n”);
try{
// Register JDBC driver
Class.forName(JDBC_DRIVER);
System.out.println(“Connecting to database…”);
// Open a connection
try{
conn = DriverManager.getConnection(DB_URL,USER,PASS);
out.println(“Connected Successfully… Please Wait!<br>”);
}
catch(SQLException se){
se.printStackTrace();
String sql;
while(rs.next()){
//Display values
out.println(“Student’s Roll No: ” + rno + ” “);
out.println(“, Name: ” + sname + “<br>”);
}
out.println(“</body></html>”);
// Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
index.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”>
</head>
<body>
<form id=“ContextParam” action=”/DatabaseServlet/LoadRecords”
method=“GET”>
</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:
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 that’s why
we mostly extend HttpServlet class. Servlet API hierarchy is shown in below image.
Servlet containers are also known as web container, for example Tomcat. Some of the
important tasks of servlet container are:
• Lifecycle management - Managing the lifecycle events of a servlet lik class
loading, instantiation, initialization, service, and making servlet instances
eligible for garbage collection.
• Communication support: Handling the communication between servlet and
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.
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.
Although the init method of the servlet initializes it, a constructor instantiates it. A
developer might never explicitly call the servlet’s constructor but a container uses it to
create an instance of the servlet.
What is difference between PrintWriter and ServletOutputStream?
GET is preferred over POST in most of the situations except for the following:
• When the data is sensitive.
• When the data is greater than 1024 characters
GenericServlet is an abstract class which implements the Servlet interface and the
ServletConfig interface. Other than the methods included in above two interfaces, it also
provides simple versions of the lifecycle methods init and destroy, and implements the log
method declared in the ServletContext interface. Since this class is not specific to any
protocol, it is known as generic servlet.
URL rewriting: In this method of session tracking, some extra data is appended
at the end of the URL, which identifies the session. This method is used for
those browsers which do not support cookies or when the cookies are disabled
by the user.
Hidden Form Fields: This method is similar to URL rewriting. New hidden
fields are embedded by the server in every dynamically generated form page
for the client. When the form is submitted to the server the hidden fields
identify the client.
Cookies: Cookie refers to the small amount of information sent by a servlet to a
Web browser. Browser saves this information and sends it back to the server
when requested next. Its value helps in uniquely identifying a client.
Using session Tracking API
Exercise
What is servlet?
What is difference between Applet and Servlet?
Explain the life cycle of Servlet.
What are the uses of Servlets?
What’s 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?
Unit V Java Server Pages: (JSP)
JSP technology
JavaServer Pages is server side component in a web application, used to dynamically
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.
Java Server Page is a standard Java extension that is defined on top of the servlet
Extensions. The goal of JSP is the simplified creation and management of dynamic Web
pages. JSPs are secure, platform-independent, and best of all; make use of Java as a
server-side scripting language.
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.
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.
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.
They have certain advantages and disadvantages in relation to the others. Applets are
better suited for high functionality applications, where download times are not a
factor. Servlets and JSP pages are more appropriate for applications where the users may
access a host site through a slow Internet connection.
Applets
Applets are small programs that are downloaded into a Java Enabled Web
Browser. The browser will execute the applet on the client’s machine. The downloaded
applet has very limited access to the client machine’s file system and network capabilities.
These limitations ensure that the applet can’t perform any malicious activity on the client’s
machine, such as deleting files or installing viruses. By default, a downloaded applet
cannot read or write files from the file system, and may use the network only to
communicate back to the server of origin.
Servlets
A servlet is a Java program that runs in conjunction with a Web Server. A servlet is
executed in response to an HTTP request from a client browser. The servlet executes and
then returns an HTML page back to the browser.
Servlets do not run on the client, all execution takes place on the server. While,
they provide the advantages of generating dynamic content, they do not levy
the same download time requirement as applets.
Since they deliver HTML pages to their clients, the user interface available
through a servlet is limited by what the HTML specification supports.
JSPs are text documents that describe how a server should handle specific requests. A
JSP is run by a JSP Server, which interprets the JSP and performs the actions the page
describes. The JSP server compiles the JSP into a servlet to enhance performance. The
server would then periodically check the JSP for changes. If the JSP changes the server
will recompile it into a servlet.
JSP Servlet
JSP can be compiled into Servlet Servlets are Java programs that
when accessed are already compiled
JSP are generally not preferred Servlet are preferred when there is
when there is much processing of much processing of data required.
data required.
We can build custom tags using We can not build custom tags
JSP. using JSP.
Comments in JSP
Following syntax is sued to put comment in JSP Page.
<%— JSP Comment —%>
<!— HTML Comment —>
Java is known for its characteristic of “write once, run anywhere.” JSP pages are
platform independent. Your port your .jsp pages to any platform.
Step 3: Create simple HelloWorld.jsp program using any editor like notepad:
<%—
Document : HelloJSP.jsp
Author : J.B.Patel
—%>
<html>
<head>
</head>
<body>
</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 CLASSPATH=.;D:\apache-tomcat-8.0.15\lib\servlet-api.jar;D:\apache-tomcat-
8.0.15\lib\jsp-api.jar;D:\apache-tomcat-8.0.15\lib\el-api.jar; D:\apache-tomcat-
8.0.15\webapps\JSPDemo; %classpath%
Step 7:Start or Restart (if already running) Apache Tomcat Server
http://localhost:9999/JSPDemo/HelloWorld.jsp
Or (if you have renamed HelloWorld.jsp to index.jsp)
http://localhost:9999/JSPDemo/
Stpe 9: Observe the output:
How JSP and JSP Container functions?
A JSP page is executed in a JSP container or a JSP engine, which is installed in a web
server or in a application server. When a client asks for a JSP page the engine wraps up the
request and delivers it to the JSP page along with a response object. The JSP page
processes the request and modifies the response object to incorporate the communication
with the client. The container or the engine, on getting the response, wraps up the
responses from the JSP page and delivers it to the client. The underlying layer for a JSP is
actually a servlet implementation. The abstractions of the request and response are the
same as the ServletRequest and ServletResponse respectively. If the protocol used is
HTTP, then the corresponding objects are HttpServletRequest and HttpServletResponse.
The first time the engine intercepts a request for a JSP, it compiles this translation unit
(the JSP page and other dependent files) into a class file that implements the servlet
protocol. If the dependent files are other JSPs they are compiled into their own classes.
The servlet class generated at the end of the translation process must extend a superclass
that is either
Specified by the JSP author through the use of the extends attribute in the
page directive or
Is a JSP container specific implementation class that implements
javax.servlet.jsp.JspPage interface and provides some basic page specific
behavior.
Since most JSP pages use HTTP, their implementation classes must actually
implement the javax.servlet.jsp.HttpJspPage interface, which is a sub interface of
javax.servlet.jsp.JspPage.
The javax.servlet.jsp.JspPage interface contains two methods:
public void jspInit() - This method is invoked when the JSP is initialized
and the page authors are free to provide initialization of the JSP by
implementing this method in their JSPs.
public void jspDestroy() - This method is invoked when the JSP is about
to be destroyed by the container. Similar to above, page authors can
provide their own implementation.
This method generated by the JSP container is invoked, every time a request comes to
the JSP. The request is processed and the JSP generates appropriate response. This
response is taken by the container and passed back to the client.
1. Expressions of the form <%= expression %> that are evaluated and inserted
into the output,
2. Scriptlets of the form <% code %> that are inserted into the servlet’s service
method, and
3. Declarations of the form <%! code %> that are inserted into the body of the
servlet class, outside of any existing methods.
When Are the Scripting Elements Executed?
Request processing time occurs when your user clicks in the JSP page to make a
request. The request is sent from the client to the server by way of the request object. The
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:
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:
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.
Here’s an example:
<%—
Document : ExpressionDemo.jsp
Author : J.B.Patel
—%>
<%@page contentType=“text/html” pageEncoding=“UTF-8”%>
“http://www.w3.org/TR/html4/loose.dtd”>
<html>
<head>
</head>
<body>
</body>
</html>
Output:
<jsp:expression>
Java Expression
</jsp:expression>
Remember that XML elements are case sensitive. So be sure to use lowercase.
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:
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
—%>
“http://www.w3.org/TR/html4/loose.dtd”>
<html>
<head>
</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.
<%—
Document : ScripletDemo2.jsp
Author : J.B.Patel
—%>
“http://www.w3.org/TR/html4/loose.dtd”>
<html>
<head>
</head>
<body>
<% } %>
</p>
</body>
</html>
Output:
Code
</jsp:scriptlet>
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:
Since declarations do not generate any output, they are normally used in conjunction
with JSP expressions or scriptlets.
<%—
Document : DeclarationDemo.jsp
Author : J.B.Patel
—%>
“http://www.w3.org/TR/html4/loose.dtd”>
<html>
<head>
</head>
<body>
</body>
</html>
Output:
<jsp:declaration>
Code
</jsp:declaration>
JSP Directives
A JSP directive affects the overall structure of the servlet class. It usually has the
following syntax:
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.
The page directive lets you define one or more of the following case-sensitive
attributes:
isThreadSafe=“true|false”
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 server-
specific, 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 indicates the superclass of servlet that will be generated.
info=“message”.
* 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”.
Variable Description
out This is the PrintWriter object used to send output to the client.
You can adjust the buffer size through use of the buffer attribute of the
page directive. Also note that out is used almost exclusively in
scriptlets, since JSP expressions automatically get placed in the output
stream, and thus rarely need to refer to out explicitly.
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>
<body>
<form action=“ImplicitObjectDemo.jsp”>
<P> Enter Your Name: <input type=“text” name=“uid”> </p>
<p> Enter email: <input type=“text” name=“email”> </p>
</form>
</body>
</html>
</html>
ImplicitObjectDemo.jsp
<%—
Document : ImplicitObjectDemo.jsp
Author : J.B.Patel
—%>
“http://www.w3.org/TR/html4/loose.dtd”>
<html>
<head>
</head>
<body>
<%
String name=request.getParameter(“username”);
String email=request.getParameter(“email”);
out.print(“Welcome “+username);
out.print(“<br/>Your email is: “+email);
%>
</body>
</html>
Output:
Create Table
Now create table inside the databse in MySQL as:
);
Insert Records in the table
Create few records in Student table as follows:
Here is an example which shows how to access Students database using JSP.
DatabaseAccess.jsp
<body>
<center>
<% String DRIVER = “com.mysql.jdbc.Driver”;
Class.forName(DRIVER).newInstance();
Connection con=null;
ResultSet rst=null;
Statement stmt=null;
try{
String url=“jdbc:mysql://localhost/students”;
int i=1;
con=DriverManager.getConnection(url,“root”,””);
stmt=con.createStatement();
if (rst.next()) {
%>
</TR>
%>
</TR>
<% }
%>
</TABLE>
<% }
else {
%>
<P> Sorry, the query returned no rows! </P>
<%
}
rst.close();
stmt.close();
} catch (SQLException e) {
%>
</table>
</center>
</body>
Output:
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-tomcat-
8.0.15\lib\jsp-api.jar;D:\apache-tomcat-8.0.15\lib\el-api.jar; D:\apache-tomcat-
8.0.15\webapps\JSPDemo; %classpath%
Syntax Summary
contentType=“MIME-Type”
isThreadSafe=“true|false”
session=“true|false”
buffer=“sizekb|none”
autoflush=“true|false”
extends=“package.class”
info=“message”
errorPage=“url”
isErrorPage=“true|false”
language=“java”
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 it’s 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
don’t 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 it’s more
work that JSP pages.
What are the JSP lifecycle phases?
If you will look into JSP page code, it looks like HTML and doesn’t 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
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.
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 can’t override this method. All the JSP code goes inside this
method and it’s overridden by default. We should not try to override it using
JSP declaration scripting element. This method is defined in HttpJspPage
interface.
JSPs are compiled into JavaServlets by the JSP container. A JSP compiler may
generate a servlet in java code that is compiled by the java compiler or the bytecode may
be generated directly for the servlet. JSP directives control the compilation process of a
JSP that generates a servlet. Tomcat web server provides the JSP compilation as a task of
ANT tool. The JSP compiled servlets are stored by ANT in work folder of
CATALINA_HOME
Directives
The directive tags are used for simple java programming calls like importing
packages, specifying the error handling pages or to handle session in a JSP
page.
The directive tags are:
Page: To provide information about the type of page.
Include: To include another JSP.
Taglib: To specify / utilizes the custom tags [user defined tags] in the JSP.
Scripting Elements:
A scriplet tag is used to place a valid java code. This code is placed in the
jspService() method by the JSP engine.
Actions:
Actions are the core part of a JSP. An action can be printing an expression from
the scriplet or even creating and persisting a bean. Scriplets, declarations,
expressions, forwarding a page, handling bean properties, creating a bean for
the page comprises all the actions that are part of the JSP.
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 doesn’t sent to client. For any code level or debugging information
comments we should use JSP comments.
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;
<%
%>
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 doesn’t 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; %>.
We can use scriptlets and JSP expressions to retrieve attributes and parameters in JSP
with java code and use it for view purpose.
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 can’t 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
JSP exception implicit object is not available in normal JSP pages and it’s used in JSP
error pages only to catch the exception thrown by the JSP pages and provide useful
message to the client.
Most part of the JSP page contains HTML code and to help web designers to easily
understand JSP page and develop them, JSP technology provides action elements, JSP EL,
JSP Standard Tag Library and custom tags that we should use rather than scripting
elements to bridge the gap between JSP HTML part and JSP java part.
Exercise
1. What is JSP technology?
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