WP - I Unit-IV IT
WP - I Unit-IV IT
APPLETS
Java applets- Life cycle of an applet – Adding images to an applet – Adding sound to an
applet. Passing parameters to an applet. Event Handling. Introducing AWT: Working with
Windows Graphics and Text. Using AWT Controls, Layout Managers and Menus. Servlet –
life cycle of a servlet. The Servlet API, Handling HTTP Request and Response, using
Cookies, Session Tracking. Introduction to JSP.
Java Applets:
An applet is a Java program that runs in a Web browser. An applet can be a fully functional
Java application because it has the entire Java API at its disposal.
There are some important differences between an applet and a standalone Java application,
including the following −
• An applet is a Java class that extends the java.applet.Applet class.
• A main() method is not invoked on an applet, and an applet class will not define
main().
• Applets are designed to be embedded within an HTML page.
• When a user views an HTML page that contains an applet, the code for the applet is
downloaded to the user's machine.
• A JVM is required to view an applet. The JVM can be either a plug-in of the Web
browser or a separate runtime environment.
• The JVM on the user's machine creates an instance of the applet class and invokes
various methods during the applet's lifetime.
• Applets have strict security rules that are enforced by the Web browser. The security
of an applet is often referred to as sandbox security, comparing the applet to a child
playing in a sandbox with various rules that must be followed.
• Other classes that the applet needs can be downloaded in a single Java Archive (JAR)
file.
Life Cycle of an Applet
Four methods in the Applet class gives you the framework on which you build any serious
applet −
• init − This method is intended for whatever initialization is needed for your applet. It
is called after the param tags inside the applet tag have been processed.
• start − This method is automatically called after the browser calls the init method. It
is also called whenever the user returns to the page containing the applet after having
gone off to other pages.
• stop − This method is automatically called when the user moves off the page on
which the applet sits. It can, therefore, be called repeatedly in the same applet.
• destroy − This method is only called when the browser shuts down normally.
Because applets are meant to live on an HTML page, you should not normally leave
resources behind after a user leaves the page that contains the applet.
• paint − Invoked immediately after the start() method, and also any time the applet
needs to repaint itself in the browser. The paint() method is actually inherited from
the java.awt.
A "Hello, World" Applet
Following is a simple applet named HelloWorldApplet.java −
import java.applet.*;
import java.awt.*;
setBackground (Color.black);
setForeground (fg);
}
In this article we will learn about applet life cycle and various life cycle methods of an applet
along with example program.
init(): The init() method is the first method to execute when the applet is executed. Variable
declaration and initialization operations are performed in this method.
start(): The start() method contains the actual code of the applet that should run. The start()
method executes immediately after the init() method. It also executes whenever the applet is
restored, maximized or moving from one tab to another tab in the browser.
stop(): The stop() method stops the execution of the applet. The stop() method executes when
the applet is minimized or when moving from one tab to another in the browser.
destroy(): The destroy() method executes when the applet window is closed or when the tab
containing the webpage is closed. stop() method executes just before when destroy() method
is invoked. The destroy() method removes the applet object from memory.
paint(): The paint() method is used to redraw the output on the applet display area. The
paint() method executes after the execution of start() method and whenever the applet or
browser is resized.
• import java.awt.*;
• import java.applet.*;
• public class MyApplet extends Applet
• {
• public void init()
• {
• System.out.println("Applet initialized");
• }
• public void start()
• {
• System.out.println("Applet execution started");
• }
• public void stop()
• {
• System.out.println("Applet execution stopped");
• }
• public void paint(Graphics g)
• {
• System.out.println("Painting...");
• }
• public void destroy()
• {
• System.out.println("Applet destroyed");
• }
• }
• Output of the above applet program when run using appletviewer tool is:
• Applet initialized
Applet execution started
Painting…
Painting…
Applet execution stopped
Applet destroyed
1. import java.awt.*;
2. import java.applet.*;
3.
4.
5. public class DisplayImage extends Applet {
6.
7. Image picture;
8.
9. public void init() {
10. picture = getImage(getDocumentBase(),"sonoo.jpg");
11. }
12.
13. public void paint(Graphics g) {
14. g.drawImage(picture, 30,30, this);
15. }
16.
17. }
In the above example, drawImage() method of Graphics class is used to display the image.
The 4th argument of drawImage() method of is ImageObserver object. The Component class
implements ImageObserver interface. So current class object would also be treated as
ImageObserver because Applet class indirectly extends the Component class.
myapplet.html
1. <html>
2. <body>
3. <applet code="DisplayImage.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>
Problem Description
How to play sound using Applet?
Solution
Following example demonstrates how to play a sound using an applet image using
getAudioClip(), play() & stop() methods of AudioClip() class.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
We can get any information from the HTML file as a parameter. For this purpose, Applet
class provides a method named getParameter(). Syntax:
1. public String getParameter(String parameterName)
Example of using parameter in Applet:
1. import java.applet.Applet;
2. import java.awt.Graphics;
3.
4. public class UseParam extends Applet{
5.
6. public void paint(Graphics g){
7. String str=getParameter("msg");
8. g.drawString(str,50, 50);
9. }
10.
11. }
myapplet.html
1. <html>
2. <body>
3. <applet code="UseParam.class" width="300" height="300">
4. <param name="msg" value="Welcome to applet">
5. </applet>
6. </body>
7. </html>
Event handling:
EventHandling in Applet
As we perform event handling in AWT or Swing, we can perform it in applet also. Let's see the simple
in applet that prints a message by click on the button.
Example of EventHandling in applet:
1. import java.applet.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. public class EventApplet extends Applet implements ActionListener{
5. Button b;
6. TextField tf;
7.
8. public void init(){
9. tf=new TextField();
10. tf.setBounds(30,40,150,20);
11.
12. b=new Button("Click");
13. b.setBounds(80,150,60,50);
14.
15. add(b);add(tf);
16. b.addActionListener(this);
17.
18. setLayout(null);
19. }
20.
21. public void actionPerformed(ActionEvent e){
22. tf.setText("Welcome");
23. }
24. }
In the above example, we have created all the controls in init() method because
it is invoked only once.
myapplet.html
1. <html>
2. <body>
3. <applet code="EventApplet.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>
Introducing AWT:
Container
The Container is a component in AWT that can contain another components like buttons,
textfields, labels etc. The classes that extends Container class are known as container such as
Frame, Dialog and Panel.
Window
The window is the container that have no borders and menu bars. You must use frame, dialog
or another window for creating a window.
Panel
The Panel is the container that doesn't contain title bar and menu bars. It can have other
components like button, textfield etc.
Frame
The Frame is the container that contain title bar and can have menu bars. It can have other
components like button, textfield etc.
Introduction
The Graphics class is the abstract super class for all graphics contexts which allow an
application to draw onto components that can be realized on various devices, or onto off-
screen images as well.
A Graphics object encapsulates all state information required for the basic rendering
operations that Java supports. State information includes the following properties.
• The Component object on which to draw.
• A translation origin for rendering and clipping coordinates.
• The current clip.
• The current color.
• The current font.
• The current logical pixel operation function.
• The current XOR alternation color
Class declaration
Following is the declaration for java.awt.Graphics class:
public abstract class Graphics
extends Object
Class constructors
S.N. Constructor & Description
1 Graphics() ()
Constructs a new Graphics object.
Class methods
S.N. Method & Description
3 abstract void copyArea(int x, int y, int width, int height, int dx, int dy)
Copies an area of the component by a distance specified by dx and dy.
8 abstract void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle)
Draws the outline of a circular or elliptical arc covering the specified rectangle.
13 abstract boolean drawImage(Image img, int x, int y, int width, int height, Color
bgcolor, ImageObserver observer)
Draws as much of the specified image as has already been scaled to fit inside the specified
rectangle.
14 abstract boolean drawImage(Image img, int x, int y, int width, int height,
ImageObserver observer)
Draws as much of the specified image as has already been scaled to fit inside the specified
rectangle.
15 abstract boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int
sy1, int sx2, int sy2, Color bgcolor, ImageObserver observer)
Draws as much of the specified area of the specified image as is currently available, scaling
it on the fly to fit inside the specified area of the destination drawable surface.
16 abstract boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int
sy1, int sx2, int sy2, ImageObserver observer)
Draws as much of the specified area of the specified image as is currently available, scaling
it on the fly to fit inside the specified area of the destination drawable surface.
17 abstract void drawLine(int x1, int y1, int x2, int y2)
Draws a line, using the current color, between the points (x1, y1) and (x2, y2) in this
graphics context's coordinate system.
20 void drawPolygon(Polygon p)
Draws the outline of a polygon defined by the specified Polygon object.
23 abstract void drawRoundRect(int x, int y, int width, int height, int arcWidth, int
arcHeight)
Draws an outlined round-cornered rectangle using this graphics context's current color.
27 abstract void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle)
Fills a circular or elliptical arc covering the specified rectangle.
28 abstract void fillOval(int x, int y, int width, int height)
Fills an oval bounded by the specified rectangle with the current color.
30 void fillPolygon(Polygon p)
Fills the polygon defined by the specified Polygon object with the graphics context's current
color.
32 abstract void fillRoundRect(int x, int y, int width, int height, int arcWidth, int
arcHeight)
Fills the specified rounded corner rectangle with the current color.
33 void finalize()
Disposes of this graphics context once it is no longer referenced.
36 Rectangle getClipBounds(Rectangle r)
Returns the bounding rectangle of the current clipping area.
37 Rectangle getClipRect()
Deprecated. As of JDK version 1.1, replaced by getClipBounds().
40 FontMetrics getFontMetrics()
Gets the font metrics of the current font.
49 String toString()
Returns a String object representing this Graphics object's value.
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
public AWTGraphicsDemo(){
super("Java AWT Examples");
prepareGUI();
}
@Override
public void paint(Graphics g) {
g.setColor(Color.GRAY);
Font font = new Font("Serif", Font.PLAIN, 24);
g.setFont(font);
g.drawString("Welcome to TutorialsPoint", 50, 150);
}
}
Compile the program using command prompt. Go to D:/ > AWT and type the following
command.
D:\AWT>javac com\tutorialspoint\gui\AWTGraphicsDemo.java
If no error comes that means compilation is successful. Run the program using following
command.
D:\AWT>java com.tutorialspoint.gui.AWTGraphicsDemo
Verify the following output
1 Component
A Component is an abstract super class for GUI controls and it represents an object with
graphical representation.
AWT UI Elements:
Following is the list of commonly used controls while designed GUI using AWT.
Sr. Control & Description
No.
1 Label
A Label object is a component for placing text in a container.
2 Button
This class creates a labeled button.
3 Check Box
A check box is a graphical component that can be in either an on (true) or off (false) state.
5 List
The List component presents the user with a scrolling list of text items.
6 Text Field
A TextField object is a text component that allows for the editing of a single line of text.
7 Text Area
A TextArea object is a text component that allows for the editing of a multiple lines of
text.
8 Choice
A Choice control is used to show pop up menu of choices. Selected choice is shown on the
top of the menu.
9 Canvas
A Canvas control represents a rectangular area where application can draw something or
can receive inputs created by user.
10 Image
An Image control is superclass for all image classes representing graphical images.
11 Scroll Bar
A Scrollbar control represents a scroll bar component in order to enable user to select from
range of values.
12 Dialog
A Dialog control represents a top-level window with a title and a border used to take some
form of input from the user.
13 File Dialog
A FileDialog control represents a dialog window from which the user can select a file.
1 LayoutManager
The LayoutManager interface declares those methods which need to be implemented by the
class whose object will act as a layout manager.
2 LayoutManager2
The LayoutManager2 is the sub-interface of the LayoutManager.This interface is for those
classes that know how to layout containers based on layout constraint object.
AWT Layout Manager Classes:
Following is the list of commonly used controls while designed GUI using AWT.
Sr. LayoutManager & Description
No.
1 BorderLayout
The borderlayout arranges the components to fit in the five regions: east, west, north, south
and center.
2 CardLayout
The CardLayout object treats each component in the container as a card. Only one card is
visible at a time.
3 FlowLayout
The FlowLayout is the default layout.It layouts the components in a directional flow.
4 GridLayout
The GridLayout manages the components in form of a rectangular grid.
5 GridBagLayout
This is the most flexible layout manager class.The object of GridBagLayout aligns the
component vertically,horizontally or along their baseline without requiring the components
of same size.
Servlet:
Servlet technology is used to create a web application (resides at server side and generates a
dynamic web page).
Servlet technology is robust and scalable because of java language. Before Servlet, CGI
(Common Gateway Interface) scripting language was common as a server-side programming
language. However, there were many disadvantages to this technology. We have discussed
these disadvantages below.
There are many interfaces and classes in the Servlet API such as Servlet, GenericServlet,
HttpServlet, ServletRequest, ServletResponse, etc.
What is a Servlet?
Servlet can be described in many ways, depending on the context.
o Servlet is a technology which is used to create a web application.
o Servlet is an API that provides many interfaces and classes including documentation.
o Servlet is an interface that must be implemented for creating any Servlet.
o Servlet is a class that extends the capabilities of the servers and responds to the
incoming requests. It can respond to any requests.
o Servlet is a web component that is deployed on the server to create a dynamic web
page.
Disadvantages of CGI
There are many problems in CGI technology:
1. If the number of clients increases, it takes more time for sending the response.
2. For each request, it starts a process, and the web server is limited to start processes.
3. It uses platform dependent language e.g. C, C++, perl.
Advantages of Servlet
There are many advantages of Servlet over CGI. The web container creates threads for
handling the multiple requests to the Servlet. Threads have many benefits over the Processes
such as they share a common memory area, lightweight, cost of communication between the
threads are low. The advantages of Servlet are as follows:
1. Better performance: because it creates a thread for each request, not process.
2. Portability: because it uses Java language.
3. Robust: JVM manages Servlets, so we don't need to worry about the memory
leak, garbage collection, etc.
4. Secure: because it uses java language.
The web container maintains the life cycle of a servlet instance. Let's see the life cycle of the
servlet:
1. Servlet class is loaded.
2. Servlet instance is created.
3. init method is invoked.
4. service method is invoked.
5. destroy method is invoked.
As displayed in the above diagram, there are three states of a servlet: new, ready and end. The
servlet is in new state if servlet instance is created. After invoking the init() method, Servlet
comes in the ready state. In the ready state, servlet performs all the tasks. When the web
container invokes the destroy() method, it shifts to the end state.
1) Servlet class is loaded
The classloader is responsible to load the servlet class. The servlet class is loaded when the
first request for the servlet is received by the web container.
2) Servlet instance is created
The web container creates the instance of a servlet after loading the servlet class. The servlet
instance is created only once in the servlet life cycle.
The javax.servlet and javax.servlet.http packages represent interfaces and classes for servlet
api. 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.
The javax.servlet.http package contains interfaces and classes that are responsible for http
requests only.
Interfaces in javax.servlet package
There are many interfaces in javax.servlet package. They are as follows:
1. Servlet
2. ServletRequest
3. ServletResponse
4. RequestDispatcher
5. ServletConfig
6. ServletContext
7. SingleThreadModel
8. Filter
9. FilterConfig
10. FilterChain
11. ServletRequestListener
12. ServletRequestAttributeListener
13. ServletContextListener
14. ServletContextAttributeListener
Interfaces in javax.servlet.http package
There are many interfaces in javax.servlet.http package. They are as follows:
1. HttpServletRequest
2. HttpServletResponse
3. HttpSession
4. HttpSessionListener
5. HttpSessionAttributeListener
6. HttpSessionBindingListener
7. HttpSessionActivationListener
8. HttpSessionContext (deprecated now)
Classes in javax.servlet.http package
There are many classes in javax.servlet.http package. They are as follows:
1. HttpServlet
2. Cookie
3. HttpServletRequestWrapper
4. HttpServletResponseWrapper
5. HttpSessionEvent
6. HttpSessionBindingEvent
7. HttpUtils (deprecated now)
Handling HTTP Request and Response:
An HTTP client sends an HTTP request to a server in the form of a request message which
includes following format:
• A Request-line
• Optionally a message-body
The following sections explain each of the entities used in an HTTP request message.
Request-Line
The Request-Line begins with a method token, followed by the Request-URI and the
protocol version, and ending with CRLF. The elements are separated by space SP characters.
Request-Line = Method SP Request-URI SP HTTP-Version CRLF
Let's discuss each of the parts mentioned in the Request-Line.
Request Method
The request method indicates the method to be performed on the resource identified by the
given Request-URI. The method is case-sensitive and should always be mentioned in
uppercase. The following table lists all the supported methods in HTTP/1.1.
S.N. Method and Description
1 GET
The GET method is used to retrieve information from the given server using a given URI.
Requests using GET should only retrieve data and should have no other effect on the data.
2 HEAD
Same as GET, but it transfers the status line and the header section only.
3 POST
A POST request is used to send data to the server, for example, customer information, file
upload, etc. using HTML forms.
4 PUT
Replaces all the current representations of the target resource with the uploaded content.
5 DELETE
Removes all the current representations of the target resource given by URI.
6 CONNECT
Establishes a tunnel to the server identified by a given URI.
7 OPTIONS
Describe the communication options for the target resource.
8 TRACE
Performs a message loop back test along with the path to the target resource.
Request-URI
The Request-URI is a Uniform Resource Identifier and identifies the resource upon which to
apply the request. Following are the most commonly used forms to specify an URI:
Request-URI = "*" | absoluteURI | abs_path | authority
1 The asterisk * is used when an HTTP request does not apply to a particular resource, but to
the server itself, and is only allowed when the method used does not necessarily apply to a
resource. For example:
OPTIONS * HTTP/1.1
2 The absoluteURI is used when an HTTP request is being made to a proxy. The proxy is
requested to forward the request or service from a valid cache, and return the response. For
example:
GET http://www.w3.org/pub/WWW/TheProject.html HTTP/1.1
3 The most common form of Request-URI is that used to identify a resource on an origin server
or gateway. For example, a client wishing to retrieve a resource directly from the origin
server would create a TCP connection to port 80 of the host "www.w3.org" and send the
following lines:
GET /pub/WWW/TheProject.html HTTP/1.1
Host: www.w3.org
Note that the absolute path cannot be empty; if none is present in the original URI, it MUST
be given as "/" (the server root).
Request Header Fields
We will study General-header and Entity-header in a separate chapter when we will learn
HTTP header fields. For now, let's check what Request header fields are.
The request-header fields allow the client to pass additional information about the request,
and about the client itself, to the server. These fields act as request modifiers.Here is a list of
some important Request-header fields that can be used based on the requirement:
• Accept-Charset
• Accept-Encoding
• Accept-Language
• Authorization
• Expect
• From
• Host
• If-Match
• If-Modified-Since
• If-None-Match
• If-Range
• If-Unmodified-Since
• Max-Forwards
• Proxy-Authorization
• Range
• Referer
• TE
• User-Agent
You can introduce your custom fields in case you are going to write your own custom Client
and Web Server.
Examples of Request Message
Now let's put it all together to form an HTTP request to fetch hello.htm page from the web
server running on tutorialspoint.com
GET /hello.htm HTTP/1.1
User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT)
Host: www.tutorialspoint.com
Accept-Language: en-us
Accept-Encoding: gzip, deflate
Connection: Keep-Alive
Here we are not sending any request data to the server because we are fetching a plain
HTML page from the server. Connection is a general-header, and the rest of the headers are
request headers. The following example shows how to send form data to the server using
request message body:
POST /cgi-bin/process.cgi HTTP/1.1
User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT)
Host: www.tutorialspoint.com
Content-Type: application/x-www-form-urlencoded
Content-Length: length
Accept-Language: en-us
Accept-Encoding: gzip, deflate
Connection: Keep-Alive
licenseID=string&content=string&/paramsXML=string
Here the given URL /cgi-bin/process.cgi will be used to process the passed data and
accordingly, a response will be returned. Here content-type tells the server that the passed
data is a simple web form data and length will be the actual length of the data put in the
message body. The following example shows how you can pass plain XML to your web
server:
POST /cgi-bin/process.cgi HTTP/1.1
User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT)
Host: www.tutorialspoint.com
Content-Type: text/xml; charset=utf-8
Content-Length: length
Accept-Language: en-us
Accept-Encoding: gzip, deflate
Connection: Keep-Alive
Using Cookies:
In the last guide, I have covered Sessions in Servlet. Here we will discuss Cookies which is
also used for session management. Let’s recall few things here from last tutorial so that we
can relate sessions and cookies. When a user visits web application first time, the servlet
container crates new HttpSession object by calling request.getSession(). A unique Id is
assigned to the session. The Servlet container also sets a Cookie in the header of the
HTTP response with cookie name and the unique session ID as its value.
The cookie is stored in the user browser, the client (user’s browser) sends this cookie back to
the server for all the subsequent requests until the cookie is valid. The Servlet container
checks the request header for cookies and get the session information from the cookie
and use the associated session from the server memory.
The session remains active for the time specified in tag in web.xml. If tag in not set in
web.xml then the session remains active for 30 minutes. Cookie remains active as long as
the user’s browser is running, as soon as the browser is closed, the cookie and associated
session info is destroyed. So when the user opens the browser again and sends request to web
server, the new session is being created.
Types of Cookies
We can classify the cookie based on their expiry time:
1. Session
2. Persistent
1) SessionCookies:
Session cookies do not have expiration time. It lives in the browser memory. As soon as the
web browser is closed this cookie gets destroyed.
2) Persistent Cookies:
Unlike Session cookies they have expiration time, they are stored in the user hard drive and
gets destroyed based on the expiry time.
How to send Cookies to the Client
Here are steps for sending cookie to the client:
1. Create a Cookie object.
2. Set the maximum Age.
3. Place the Cookie in HTTP response header.
1) Create a Cookie object:
Cookie c = new Cookie("userName","Chaitanya");
2) Set the maximum Age:
By using setMaxAge () method we can set the maximum age for the particular cookie in
seconds.
c.setMaxAge(1800);
3) Place the Cookie in HTTP response header:
We can send the cookie to the client browser through response.addCookie() method.
response.addCookie(c);
How to read cookies
Cookie c[]=request.getCookies();
//c.length gives the cookie count
for(int i=0;i<c.length;i++){
out.print("Name: "+c[i].getName()+" & Value: "+c[i].getValue());
}
Example of Cookies in java servlet
index.html
<form action="login">
User Name:<input type="text" name="userName"/><br/>
Password:<input type="password" name="userPassword"/><br/>
<input type="submit" value="submit"/>
</form>
MyServlet1.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet1 extends HttpServlet
{
public void doGet(HttpServletRequest request,
HttpServletResponse response) {
try{
response.setContentType("text/html");
PrintWriter pwriter = response.getWriter();
//Reading cookies
Cookie c[]=request.getCookies();
//Displaying User name value from cookie
pwriter.print("Name: "+c[1].getValue());
//Displaying user password value from cookie
pwriter.print("Password: "+c[2].getValue());
pwriter.close();
}catch(Exception exp){
System.out.println(exp);
}
}
}
web.xml
<web-app>
<display-name>BeginnersBookDemo</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Servlet1</servlet-name>
<servlet-class>MyServlet1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Servlet2</servlet-name>
<servlet-class>MyServlet2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Servlet2</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>
Output:
Welcome Screen: