2. ADDING IMAGES TO AN APPLET
• An applet can display images of the format GIF, JPEG, BMP, and others. To display an image within the applet,
you use the drawlmage() method found in the java.awt.Graphics class.
• Following is the example showing all the steps to show images:
import java.applet. *;
Import java.awt. *;
import java.net.*;
public class ImageDemo extends Applet
{
private Image image;
private AppletContext context;
public void init()
{
context = this.getAppletContext();
String imageURL = this.getParameter("image");
if(imageURL == null)
{
imageURL = "java.jpg";
}
3. try
{
URL url = new URL(this.getDocumentBase(), imageURL);
image = context.getImage(url);
}
catch(MalformedURLException e)
{
e.printStackTrace();
//Display in browser status bar
context.showStatus("Could not load image!");
}}
public void paint(Graphics g)
{
context.showStatus("Displaying image");
g.drawImage(image, 0, 0, 200, 84, null);
g.drawString("www.java2s.com", 10, 20);
}}
Now,let us call this applet as follows:
<html>
<title>The ImageDemo applet</title>
<hr>
<applet code="ImageDemo.class" width="300" height="200">
<param name="image" value="java.jpg">
</appIet><hr></html>
4. • MalformedURLException is a checked
exception. It is inherited from IOException.
MalformedURLException is raised by JVM in
two occasions.
1. The protocol given in the address as URL may
not be a correct (valid) one for the job.
2. The address given in the URL constructor
may not be evaluated successfully (due to
wrong format etc) by the networking software.
5. Life cycle of a servlet
• A servlet life cycle can be defined as the entire process from its creation
till the destruction.
The following are the paths followed by a servlet.
• The servlet is initialized by calling the init() method.
• The servlet calls service() method to process a client's request.
• The servlet is terminated by calling the destroy() method.
• Finally, servlet is garbage collected by the garbage collector of the JVM.
6. The init() Method
• The init method is called only once.
• It is called only when the servlet is created, and not called for any
user requests afterwards. So, it is used for one-time initializations,
just as with the init method of applets.
• The servlet is normally created when a user first invokes a URL
corresponding to the servlet, but you can also specify that the
servlet be loaded when the server is first started.
• When a user invokes a servlet, a single instance of each servlet gets
created, with each user request resulting in a new thread that is
handed off to doGet or doPost as appropriate.
• The init() method simply creates or loads some data that will be
used throughout the life of the servlet.
• The init method definition looks like this −
public void init() throws ServletException
{ // Initialization code... }
7. The service() Method
• The service() method is the main method to perform the actual task.
• The servlet container (i.e. web server) calls the service() method to handle
requests coming from the client( browsers) and to write the formatted
response back to the client.
• Each time the server receives a request for a servlet, the server spawns a
new thread and calls service.
• The service() method checks the HTTP request type (GET, POST, PUT,
DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as
appropriate.
• Here is the signature of this method −
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException { }
• The service () method is called by the container and service method
invokes doGet, doPost, doPut, doDelete, etc. methods as appropriate.
• So you have nothing to do with service() method but you override either
doGet() or doPost() depending on what type of request you receive from
the client.
• The doGet() and doPost() are most frequently used methods with in each
service request. Here is the signature of these two methods.
8. The service() Method
The doGet() Method
• A GET request results from a normal request for a URL or from an HTML form that
has no METHOD specified and it should be handled by doGet() method.
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// Servlet code
}
The doPost() Method
• A POST request results from an HTML form that specifically lists POST as the
METHOD and it should be handled by doPost() method.
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}
10. The destroy() Method
• The destroy() method is called only once at the end of
the life cycle of a servlet.
• This method gives your servlet a chance to close
database connections, halt background threads, write
cookie lists or hit counts to disk, and perform other
such cleanup activities.
• After the destroy() method is called, the servlet object
is marked for garbage collection.
• The destroy method definition looks like this −
public void destroy() { // Finalization code... }
11. Architectural Diagram
• The following figure depicts a typical servlet life-cycle scenario.
• First the HTTP requests coming to the server are delegated to the servlet container.
• The servlet container loads the servlet before invoking the service() method.
• Then the servlet container handles multiple requests by spawning multiple threads, each thread
executing the service() method of a single instance of the servlet.
• Servlets are Java classes which service HTTP requests and implement the javax.servlet.Servlet
interface.
12. Sample Code
Following is the sample source code structure
of a servlet example to show Hello World
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class HelloWorld extends HttpServlet
{
private String message;
public void init() throws ServletException
{
// Do required initialization
message = "Hello World";
}
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws
ServletException, IOException
{
// Set response content type
response.setContentType("text/html");
// Actual logic goes here.
PrintWriter out = response.getWriter();
out.println("<h1>" + message + "</h1>");
}
public void destroy()
{
// do nothing.
} }
13. Passing Parameter to Applets with example
• Java applet has the feature of retrieving the parameter
values passed from the html page. So, you can pass the
parameters from your html page to the applet
embedded in your page.
• The param tag(<parma name="" value=""></param>)
is used to pass the parameters to an applet.
• There are three methods commonly used by applets:
– String getParameter(String name)-Returns the value for the
specified parameter string
– URL getCodeBase()-Returns the URL of the applet
– URL getDocumentBase()-Returns the URL of the document
containing the applet
14. Example( hai.java)
import java.applet.*;
import java.awt.*;
/*<APPLET code="hai" width="300" height="250">
<PARAM name="Message" value="Hai friend how are you ..?">
</APPLET>*/
public class hai extends Applet
{
private String defaultMessage = "Hello!“;
public void paint(Graphics g)
{
String inputFromPage = this.getParameter("Message");
if (inputFromPage == null)
inputFromPage = defaultMessage;
g.drawString(inputFromPage, 50, 55);
}}
16. • You only need to change the HTML, not the Java source code. PARAMs let you
customize applets without changing or recompiling the code.
• This applet is very similar to the HelloWorldApplet.
• You pass getParameter() a string that names the parameter you want. This string
should match the name of a PARAM element in the HTML page.
• getParameter() returns the value of the parameter. All values are passed as strings.
• If you want to get another type like an integer, then you'll need to pass it as a string
and convert it to the type you really want.
• The PARAM element is also straightforward. It occurs between <APPLET> and
</APPLET>.
• It has two attributes of its own, NAME and VALUE.
• NAME identifies which PARAM this is. VALUE is the string value of the PARAM.
• Both should be enclosed in double quote marks if they contain white space.
An applet is not limited to one PARAM.
• You can pass as many named PARAMs to an applet as you like. An applet does not
necessarily need to use all the PARAMs that are in the HTML. Additional PARAMs can
be safely ignored.
17. Displaying Graphics in Applet
• java.awt.Graphics class provides many methods for graphics programming.
Commonly used methods of Graphics class:
• public abstract void drawString(String str, int x, int y): is used to draw the specified string.
• public void drawRect(int x, int y, int width, int height): draws a rectangle with the specified width and height.
• public abstract void fillRect(int x, int y, int width, int height): is used to fill rectangle with the default color and
specified width and height.
• public abstract void drawOval(int x, int y, int width, int height): is used to draw oval with the specified width and
height.
• public abstract void fillOval(int x, int y, int width, int height): is used to fill oval with the default color and specified
width and height.
• public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line between the points(x1, y1) and (x2, y2).
• public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer): is used draw the specified image.
• public abstract void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle): is used draw a circular or
elliptical arc.
• public abstract void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle): is used to fill a circular or
elliptical arc.
• public abstract void setColor(Color c): is used to set the graphics current color to the specified color.
• public abstract void setFont(Font font): is used to set the graphics current font to the specified font.
18. Example of Graphics in applet:
import java.applet.Applet;
import java.awt.*;
public class GraphicsDemo extends Applet{
public void paint(Graphics g){
g.setColor(Color.red);
g.drawString("Welcome",50, 50);
g.drawLine(20,30,20,300);
g.drawRect(70,100,30,30);
g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);
g.setColor(Color.pink);
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);
} }
myapplet.html
<html>
<body>
<applet code="GraphicsDemo.class" width="300" height="300">
</applet>
</body>
</html>
19. AWT Layouts
• The LayoutManagers are used to arrange components in a particular
manner.
• LayoutManager is an interface that is implemented by all the classes of
layout managers. When you add a component to an applet or a container,
the container uses its layout manager to decide where to put the
component.
• Different LayoutManager classes use different rules to place components.
java.awt.LayoutManager is an interface. Five classes in the java packages
implement it:
– FlowLayout
– BorderLayout
– CardLayout
– GridLayout
– GridBagLayout
20. FlowLayout
Java FlowLayout
• The FlowLayout is used to arrange the components in a line, one after another (in a flow). It is the default
layout of applet or panel.
Fields of FlowLayout class
– public static final int LEFT
– public static final int RIGHT
– public static final int CENTER
– public static final int LEADING
– public static final int TRAILING
Constructors of FlowLayout class
• FlowLayout(): creates a flow layout with centered alignment and a default 5 unit horizontal and vertical gap.
• FlowLayout(int align): creates a flow layout with the given alignment and a default 5 unit horizontal and
vertical gap.
• FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given alignment and the given
horizontal and vertical gap.
Example of FlowLayout class
21. import java.awt.*;
import javax.swing.*;
public class MyFlowLayout{
JFrame f;
MyFlowLayout(){
f=new JFrame();
JButton b1=new JButton("1");
JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4");
JButton b5=new JButton("5");
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
f.setLayout(new FlowLayout(FlowLayout.RIGHT));
//setting flow layout of right alignment
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new MyFlowLayout();
}
}
22. BorderLayout
• The BorderLayout is used to arrange the components in five regions: north, south,
east, west and center.
• Each region (area) may contain one component only. It is the default layout of frame
or window. The BorderLayout provides five constants for each region:
– public static final int NORTH
– public static final int SOUTH
– public static final int EAST
– public static final int WEST
– public static final int CENTER
Constructors of BorderLayout class:
• BorderLayout(): creates a border layout but with no gaps between the components.
• JBorderLayout(int hgap, int vgap): creates a border layout with the given horizontal
and vertical gaps between the components.
25. Java Card Layout
• The CardLayout class manages the components in such a manner that only one component
is visible at a time. It treats each component as a card that is why it is known as CardLayout.
Constructors of CardLayout class
• CardLayout(): creates a card layout with zero horizontal and vertical gap.
• CardLayout(int hgap, int vgap): creates a card layout with the given horizontal and vertical
gap.
Commonly used methods of CardLayout class
• public void next(Container parent): is used to flip to the next card of the given container.
• public void previous(Container parent): is used to flip to the previous card of the given
container.
• public void first(Container parent): is used to flip to the first card of the given container.
• public void last(Container parent): is used to flip to the last card of the given container.
• public void show(Container parent, String name): is used to flip to the specified card with
the given name.
27. import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CardLayoutExample extends JFrame implements ActionListener{
CardLayout card;
JButton b1,b2,b3;
Container c;
CardLayoutExample(){
c=getContentPane();
card=new CardLayout(40,30);
//create CardLayout object with 40 hor space and 30 ver space
c.setLayout(card);
b1=new JButton("Apple");
b2=new JButton("Boy");
b3=new JButton("Cat");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
c.add("a",b1);c.add("b",b2);c.add("c",b3); }
public void actionPerformed(ActionEvent e) {
card.next(c); }
public static void main(String[] args) {
CardLayoutExample cl=new CardLayoutExample();
cl.setSize(400,400);
cl.setVisible(true);
cl.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
28. GridLayout
• The GridLayout is used to arrange the components in rectangular grid. One component
is displayed in each rectangle.
Constructors of GridLayout class
• GridLayout(): creates a grid layout with one column per component in a row.
• GridLayout(int rows, int columns): creates a grid layout with the given rows and
columns but no gaps between the components.
• GridLayout(int rows, int columns, int hgap, int vgap):creates a grid layout with the
given rows and columns along with given horizontal and vertical gaps.
• Example of GridLayout class
30. Java GridBagLayout
• The Java GridBagLayout class is used to align components vertically,
horizontally or along their baseline.
• The components may not be of same size.
• Each GridBagLayout object maintains a dynamic, rectangular grid of
cells.
• Each component occupies one or more cells known as its display
area.
• Each component associates an instance of GridBagConstraints.
• With the help of constraints object we arrange component's display
area on the grid.
• The GridBagLayout manages each component's minimum and
preferred sizes in order to determine component's size.
35. import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class calc extends Applet implements
ActionListener{
Label l1,l2;
TextField t1,t2,t3;
Button addition,subtraction,multiplication,division;
public void init(){
l1=new Label("enter first no");
add(l1);
l2=new Label("enter second no");
add(l2);
t1=new TextField(10);
add(t1);
t2=new TextField(10);
add(t2);
t3=new TextField(10);
add(t3);
addition=new Button("+");
add(addition);
addition.addActionListener(this);
subtraction=new Button("-");
add(subtraction);
subtraction.addActionListener(this);
multiplication=new Button("*");
add(multiplication);
multiplication.addActionListener(this);
division=new Button("/");
add(division);
division.addActionListener(this);}
public void actionPerformed(ActionEvent ae){
if(ae.getSource()==addition){
int sum=Integer.parseInt(t1.getText()) +
Integer.parseInt(t2.getText());
t3.setText(String.valueOf(sum));
}
if(ae.getSource()==subtraction)
{
int sub=Integer.parseInt(t1.getText()) +
Integer.parseInt(t2.getText());
t3.setText(String.valueOf(sub));
}
if(ae.getSource()==multiplication)
{
int mul=Integer.parseInt(t1.getText()) +
Integer.parseInt(t2.getText());
t3.setText(String.valueOf(mul));
}
if(ae.getSource()==division)
{
int div=Integer.parseInt(t1.getText()) +
Integer.parseInt(t2.getText());
t3.setText(String.valueOf(div));
}}}
/*
<applet code="calc" width=200 height=200>
</applet>
*/
36. JSP
What is JavaServer Pages?
• JavaServer Pages (JSP) is a technology for developing Webpages that
supports dynamic content. This helps developers insert java code in HTML
pages by making use of special JSP tags, most of which start with <% and
end with %>.
• A JavaServer Pages component is a type of Java servlet that is designed to
fulfill the role of a user interface for a Java web application.
• Web developers write JSPs as text files that combine HTML or XHTML code,
XML elements, and embedded JSP actions and commands.
• Using JSP, you can collect input from users through Webpage forms, present
records from a database or another source, and create Webpages
dynamically.
• JSP tags can be used for a variety of purposes, such as retrieving information
from a database or registering user preferences, accessing JavaBeans
components, passing control between pages, and sharing information
between requests, pages etc.
37. • JavaServer Pages often serve the same purpose as programs
implemented using the Common Gateway Interface (CGI).
• But JSP offers several advantages in comparison with the CGI.
– Performance is significantly better because JSP allows
embedding Dynamic Elements in HTML Pages itself instead of
having separate CGI files.
– JSP are always compiled before they are processed by the server
unlike CGI/Perl which requires the server to load an interpreter
and the target script each time the page is requested.
– JavaServer Pages are built on top of the Java Servlets API, so like
Servlets, JSP also has access to all the powerful Enterprise Java
APIs, including JDBC, JNDI, EJB, JAXP, etc.
– JSP pages can be used in combination with servlets that handle
the business logic, the model supported by Java servlet template
engines.
38. Advantages of JSP
• Following table lists out the other advantages of using JSP over other technologies −
• vs. Active Server Pages (ASP)
• The advantages of JSP are twofold. First, the dynamic part is written in Java, not Visual Basic or other MS
specific language, so it is more powerful and easier to use. Second, it is portable to other operating
systems and non-Microsoft Web servers.
• vs. Pure Servlets
• It is more convenient to write (and to modify!) regular HTML than to have plenty of println statements
that generate the HTML.
• vs. Server-Side Includes (SSI)
• SSI is really only intended for simple inclusions, not for "real" programs that use form data, make
database connections, and the like.
• vs. JavaScript
• JavaScript can generate HTML dynamically on the client but can hardly interact with the web server to
perform complex tasks like database access and image processing etc.
• vs. Static HTML
• Regular HTML, of course, cannot contain dynamic information.
39. Event Handling
Event:
• Change in the state of an object is known as event i.e. event describes the change in state
of source.
• Events are generated as result of user interaction with the graphical user interface
components. For example, clicking on a button, moving the mouse, entering a character
through keyboard, selecting an item from list, scrolling the page are the activities that
causes an event to happen.
Types of Event
• The events can be broadly classified into two categories:
Foreground Events - Those events which require the direct interaction of user. They are
generated as consequences of a person interacting with the graphical components in
Graphical User Interface. For example, clicking on a button, moving the mouse, entering a
character through keyboard, selecting an item from list, scrolling the page etc.
Background Events - Those events that require the interaction of end user are known as
background events. Operating system interrupts, hardware or software failure, timer
expires, an operation completion are the example of background events.
40. Event Handling:
• Event Handling is the mechanism that controls the event and decides what should happen if
an event occurs.
• These mechanisms have the code which is known as event handler that is executed when an
event occurs.
• Java Uses the Delegation EventModel to handle the events. This model defines the standard
mechanism to generate and handle the events.
The Delegation Event Model has the following key participants namely:
• Source - The source is an object on which event occurs. Source is responsible for providing
information of the occurred event to it's handler. Java provide as with classes for source
object.
• Listener - It is also known as event handler. Listener is responsible for generating response to
an event. From java implementation point of view the listener is also an object. Listener
waits until it receives an event. Once the event is received, the listener processes the event a
then returns.
41. Steps involved in event handling
• The User clicks the button and the event is
generated.
• Now the object of concerned event class is
created automatically and information about
the source and the event get populated with in
same object.
• Event object is forwarded to the method of
registered listener class.
• The method is now get executed and returns.
42. import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class EventApplet extends Applet implements ActionListener{
Button b;
TextField tf;
public void init(){
tf=new TextField();
tf.setBounds(30,40,150,20);
b=new Button("Click");
b.setBounds(80,150,60,50);
add(b);add(tf);
b.addActionListener(this);
setLayout(null);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
}