CS506 Final Term Lec 19 To 45

Download as pdf or txt
Download as pdf or txt
You are on page 1of 39

CS506 Final term preparation | Lecture 19 to 45

Lecture #19:
If we want to animate something like ball, moving from one place to another, we constantly
need to call paintComponent( ) method and to draw the shape (ball etc.) at new place means at
new coordinates.
Painting is managed by system, so calling paintComponent() directly is not recommended at all.
Similarly calling paint( ) method is also not recommended. Why? Because such code may be
invoked at times when it is not appropriate to paint -- for instance, before the component is
visible or has access to a valid Graphics object.
Java gives us a solution in the form of repaint( ) method. Whenever we need to repaint, we call
this method that in fact makes a call to paint( ) method at appropriate time.
 Hard-coding the position of co-ordinates uses some variables. For example mx , my
we draw a rectangle by passing hard-coded values like 20
g.drawRect(20,20,20,20);
we’ll use variables so that change in a variable value causes to display a rectangle at a
new location.
g.drawRect(mx,my,20,20);
// declaring Reference of MyPanel class
MyPanel p;
// parameter less constructor
public Test(){
f = new JFrame();
Container c = f.getContentPane();
c.setLayout(new BorderLayout());
// instantiating reference
p = new MyPanel();
// adding MyPanel into container
c.add(p);
f.setSize(400,400);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// creating inner class object
Handler h = new Handler();
// registering MyPanel to handle events
p.addMouseMotionListener(h);
} // end constructor
// inner class used for handling events
public class Handler extends MouseMotionAdapter{
// capturing mouse dagged events
public void mouseDragged(MouseEvent me){
// getting the X-Position of mouse and assigning

1
CS506 Final term preparation | Lecture 19 to 45

// value to instance variable mX of MyPanel class


p.mX = me.getX();
// getting the Y-Position of mouse and assigning
// value to instance variable mX of MyPanel class
p.mY = me.getY();
// call to repaint causes rectangle to be drawn on
// new location
p.repaint() ;
} // end mouseDragged
} // end Handler class
// main method
public static void main(String args[ ]){
Test t = new Test();
}
} // end MyPanel class

Lecture #20:
Applets Basic Definition
• A small program written in Java and included in a HTML page.
• It is independent of the operating system on which it runs
• An applet is a Panel that allows interaction with a Java program
• A applet is typically embedded in a Web page and can be run from a browser
• You need special HTML in the Web page to tell the browser about the applet
• For security reasons, applets run in a sandbox: they have no access to the client’s file
System
Applets Support
• Most modern browsers support Java 1.4 if they have the appropriate plugin
• Sun provides an application appletviewer to view applets without using browser.
• In general you should try to write applets that can be run with any browser
What an Applet is?
• You write an applet by extending the class Applet or JApplet
• Applet is just a class like any other; you can even use it in applications if you want
• When you write an applet, you are only writing part of a program
• The browser supplies the main method

2
CS506 Final term preparation | Lecture 19 to 45

Inheritance hierarchy of the JApplet class.

Writing a Simple Applet:


Below is the source code for an applet called HelloApplet. This displays a “Hello World” string.
// File HelloApplet.java
//step 1: importing required packages
import java.awt.*;
import javax.swing.*;
// extending class from JApplet so that our class also becomes an
//applet
public class HelloApplet extends JApplet {
// overriding paint method
public void paint(Graphics g) {
// write code here u want to display & draw by using
// Graphics object
g.drawString(“Hello World”, 30 , 30);
}
} // end class
After defining the HelloApplet.java, the next step is to write .html file.
Compile & Execute
The applet viewer is invoked from the command line by the command
appletviewer htmlfile
Where htmlfile is the name of the file that contains the html document. For our example, the
command looks like this:
appletviewer Test.html
Applet Life Cycle Methods
When an applet is loaded, an instance of the applet's controlling class (an Applet subclass) is
created. After that an applet passes through some stages or methods, each of them are build
for specific purpose.
An applet can react to major events in the following ways:
• It can initialize itself.
• It can start running.

3
CS506 Final term preparation | Lecture 19 to 45

• It can stop running.


• It can perform a final cleanup, in preparation for being unloaded
The applet’s life cycle methods are called in the specific order shown below.

init( ): • Is called only once.• The purpose of init( ) is to initialize the applet each time it's loaded (or
reloaded).• You can think of it as a constructor.
start( ): • To start the applet's execution• For example, when the applet's loaded or when the user
revisits a page that contains the applet • start( ) is also called whenever the browser is maximized.
paint( ): • paint( ) is called for the first time when the applet becomes visible• Whenever applet needs
to be repainted, paint( ) is called again• Do all your painting in paint( ), or in a method that is called from
paint( ).
stop( ):• To stop the applet's execution, such as when the user leaves the applet's page or quits the
browser.• stop( ) is also called whenever the browser is minimized.
destroy( ):• Is called only once.• To perform a final cleanup in preparation for unloading.

Generating Random Numbers


• Use static method random of Math class
Math.random() ;
• Returns positive double value greater than or equal to 0.0 or less than 1.0.
• Multiply the number with appropriate scaling factor to increase the range and type cast it, if needed.
int i = (int)( Math.random() * 5 ); // will generate random numbers between 0 & 4.
Program’s Modules: The program is build using many custom methods.
1.drawJava( ): As name indicates, this method will be used to write String “java” on random locations.
2. chooseColor( ): This method will choose color randomly out of 256 * 256 * 256 possible colors. The
code.
3.chooseFont( ): This method will choose a Font for text (java) to be displayed out of 4 available fonts.
4.paint( ):The last method to be discussed here is paint(). By overriding this method, we will print string
“java” on 40 random locations.

Lecture #21:
Socket Programming: • A socket is one endpoint of a two-way communication link between two
programs running generally on a network. • A socket is a bi-directional communication channel between
hosts. A computer on a network often termed as host.
What is Port?
• It is a transport address to which processes can listen for connections request.

4
CS506 Final term preparation | Lecture 19 to 45

• There are different protocols available to communicate such as TCP and UDP. We
will use TCP for programming in this handout
• There are 64k ports available for TCP sockets and 64k ports available for UDP, so at
least theoretically we can open 128k simultaneous connections.
• There are well-known ports which are
o below 1024
o provides standard services
o Some well-known ports are:
FTP works on port 21
HTTP works on port 80
TELNET works on port 23 etc.
How Client - Server Communicate
• Normally, a server runs on a specific computer and has a socket that is bound to a specific port
number.
• The server just waits, listening to the socket for a client to make a connection request.
• On the client side: The client knows the hostname of the machine on which the server is running and
the port number to which the server is connected.
•As soon as client creates a socket that socket attempts to connect to the specified server.
• The server listens through a special kind of socket, which is named as server socket.
• The sole purpose of the server socket is to listen for incoming request; it is not used for
communication.
Steps - To Make a Simple Client To make a client, process can be split into 5 steps. These are:
1 Import required package: You have to import two packages • java.net.*; • java.io.*;
2 Connect / Open a Socket with Server: Create a client socket (communication socket)
serverName: Name or address of the server you wanted to connect such as
http://www.google.com or 172.2.4.98 etc. and serverPort : Port number you want to connect to.
3 Get I/O Streams of Socket: Get input & output streams connected to your socket
• For reading data from socket: As stated above, a socket has input stream attached to it.
InputStream is = s.getInputStream();
InputStreamReader isr= new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
• For writing data to socket: A socket has also output stream attached to it. Therefore,
OutputStream os = s.getOutputStream();
PrintWriter pw = new PrintWriter(os, true);
4 Send / Receive Message:
• To send messages
pw.println(“hello world”);
• To read messages
String recMsg = br.readLine();
5 Close Socket
Don’t forget to close the socket, when you finished your work
s.close();

5
CS506 Final term preparation | Lecture 19 to 45

Steps - To Make a Simple Server: To make a server, process can be split into 7 steps.
1 Import required package: You need the similar set of packages you have used in making of client
• java.net.*;
• java.io.*;
2 Create a Server Socket: In order to create a server socket, you will need to specify port no eventually
on which server will listen for client requests.
ServerSocket ss = new ServerSocket(serverPort) ;
• serverPort: port local to the server i.e. a free port on the server machine.
3 Wait for Incoming Connections: The job of the server socket is to listen for the incoming connections.
This listening part is done through the accept method. Socket s = ss.accept();
4 Get I/O Streams of Socket
• For reading data from socket
InputStream is = s.getInputStream();
InputStreamReader isr= new
InputStreamReader(is); BufferedReader
br = new BufferedReader(isr);
• For writing data to socket
OutputStream os = s.getOutputStream();
PrintWriter pw = new PrintWriter(os, true);
5 Send / Receive Message: • To send messages: pw.println(“hello world”); • To read messages: String
recMsg = br.readLine();
6 Close Socket: s.close();

Lecture #22:
Serialization: 1 Problem
1.1 What? • You want to send an object to a stream.
1.2 Motivation: • A lot of code involves boring conversion from a file to memory
o As you might recall that AddressBook program reads data from file and then parses it
• This is a common problem
1.3 Revisiting AddressBook: We read record from a text file named persons.txt.
Serialization in Java
• Java provides an extensive support for serialization
• Object knows how to read or write themselves to streams
Serializable Interface: • By implementing this interface a class declares that it is willing to be
read/written by automatic serialization machinery • Found in java.io package.
Automatic Writing:• System knows how to recursively write out the state of an object to stream
• If an object has the reference of another object, the java serialization mechanism takes care of it and
writes it too.
Serialization: How it works?:
• To write an object of PersonInfo, ObejctOutputStream and its method writeObject( ) will be used
PersonInfo p = new PersonInfo( );
ObejctOutputStream out;
// writing PersonInfo’s object p
out.writeObject(p);

6
CS506 Final term preparation | Lecture 19 to 45

Object Serialization & Network


• You can read / write to a network using sockets.
• All you need to do is attach your stream with socket rather than file.
• The class version should be same on both sides (client & network) of the network.
Preventing Serialization
• Often there is no need to serialize sockets, streams & DB connections etc because they do
not represent the state of object, rather connections to external resources
• To do so, transient keyword is used to mark a field that should not be serialized
• So we can mark them as,
o transient Socket s;
o transient OutputStream os;
o transient Connection con;
• Transient fields are returned as null on reading

Lecture #23:
Multithreading: Multithreading is the ability to do multiple things at once within the same application. It
provides finer granularity of concurrency. A thread — sometimes called an execution context or a
lightweight process — is a single sequential flow of control within a program.
Threads are light weight as compared to processes because they take fewer resources then a process.
A thread is easy to create and destroy. Threads share the same address space i.e. multiple threads can
share the memory variables directly, and therefore may require more complex synchronization logic to
avoid deadlocks and starvation.
Sequential Execution vs. Multithreading:
Every program has atleast one thread. Programs without multithreading executes sequentially. That is,
after executing one instruction the next instruction in sequence is executed. If a function is called then
until the completion of the function the next instruction is not executed. Similarly if there is a loop then
instructions after loop only gets executed when the loop gets completed.
 Each loop has 5 iterations in the ThreeLoopTest program.
 Each loop has 10 iterations in the ThreadTest program.
Java Threads
Java includes built-in support for threading. While other languages have threads bolted on to an existing
structure.
All well known operating systems these days support multithreading. JVM transparently maps Java
Threads to their counter-parts in the operating system i.e. OS Threads. JVM allows threads in
Java to take advantage of hardware and operating system level advancements.
Creating Threads in Java: There are two approaches to create threads in Java.
• Using Interface • Using Inheritance
Threads Creation Steps Using Interface:
Step 1 - Implement the Runnable Interface: “class Worker implements Runnable”
Step 2 - Provide an Implementation of run() method
public void run( ){ // write thread behavior
// code that will be executed by the thread
Step 3 - Instantiate Thread class object by passing Runnable object in the constructor
Worker w = new Worker (“first”);

7
CS506 Final term preparation | Lecture 19 to 45

Thread t = new Thread (w);


Step 4 - Start thread by calling start() method: t.start();
Threads Creation Steps Using Inheritance
Step 1 - Inherit from Thread Class: “class Worker extends Thread”
• Step 2 - Override run() method
public void run( ){ // write thread behavior
// code that will execute by thread
• Step 3 - Instantiate subclass object: Worker w = new Worker(“first”);
• Step 4 - Start thread by calling start() method: w.start();
Three Loops: Multi-Threaded Execution: So far we have explored:
• What is multithreading? • What are Java Threads? • Two ways to write multithreaded Java programs
Thread Priorities: Threads provide a way to write concurrent programs. But on a single CPU, all the
threads do not run simultaneously. JVM assigns threads to the CPU based on thread priorities. Threads
with higher priority are executed in preference to threads with lower priority. A thread’s default priority
is same as that of the creating thread i.e. parent thread.
A Thread’s priority can be any integer between 1 and 10. We can also use the following predefined
constants to assign priorities.
Thread.MAX_PRIORITY (typically 10) Thread.NORM_PRIORITY (typically 5)
Thread.MIN_PRIORITY (typically 1)
To change the priority of a thread, we can use the following method
setPriority(int priority).
Thread Priority Scheduling
The Java runtime environment supports a very simple, deterministic scheduling algorithm called fixed-
priority scheduling. This algorithm schedules threads on the basis of their priority relative to other
Runnable threads.
If two threads of the same priority are waiting for the CPU, the scheduler arbitrarily chooses one of
them to run. The chosen thread runs until one of the following conditions becomes true:
• A higher priority thread becomes Runnable. • It yields, or its run() method exits.
• On systems that support time-slicing, its time allotment has expired.

Lecture #24:
Useful Thread Methods: Now let’s discuss some useful thread class methods.
sleep(int time) method
• Causes the currently executing thread to wait for the time (milliseconds) specified
• Waiting is efficient equivalent to non-busy. The waiting thread will not occupy the processor
yield( ) method
• Allows any other threads of the same priority to execute (moves itself to the end of the priority queue)
• If all waiting threads have a lower priority, then the yielding thread resumes execution on the CPU
• Generally used in cooperative scheduling schemes.
Thread States: Life Cycle of a Thread: A thread can be in different states during its lifecycle.
1 New state: • When a thread is just created
2 Ready state: • Thread’s start() method invoked • Thread can now execute • Put it into the Ready
Queue of the scheduler
3 Running state: • Thread is assigned a processor and now is running.

8
CS506 Final term preparation | Lecture 19 to 45

4 Dead state: • Thread has completed or exited • Eventually disposed of by system.


Thread’s Joining: Calling join method can throw InterruptedException, so you must use try-catch block
to handle it.

Lecture #25:
Web Applications:In general a web application is a piece of code running at the server which facilitates a
remote user connected to web server through HTTP protocol. HTTP protocol follows stateless Request-
Response communication model. Client (usually a web-browser) sends a request to Server, which sends
back appropriate response or error message.
A web server is software which provides users, access to the services that are present on the internet.
These servers can provide support for many protocols used over internet or intranet like HTTP, FTP,
telnet etc.
HTTP Basics
A protocol defines the method and way of communication between two parties.
Parts of an HTTP request
• Request Method: It tells the server the type of action that a client wants to perform
• URI: Uniform Resource Indicator specifies the address of required document or resource
• Header Fields: Optional headers can be used by client to tell server extra information about request
e.g. client software and content type that it understands.
•Body: Contains data sent by client to the server
• Other request headers like FROM (email of the person responsible for request) and VIA
(used by gateways and proxies to show intermediate sites the request passes) can also be used.
• Request Parameters
o Request can also contain addition information in form of request parameters
In URL as query string e.g.
http://www.gmail.com/register?name=ali&state=punjab
Parts of HTTP response
• Result Code: A numeric status code and its description.
• Header Fields: Servers use these fields to tell client about server information like configurations and
software etc.
• Body: Data sent by server as part of response that is finally seen by the user.
HTTP Response Codes
• An HTTP Response code tell the client about the state of the response i.e. whether it’s a valid response
or some error has occurred etc. HTTP Response codes fall into five general categories
o 100-199
ƒ Codes in the 100s are informational, indicating that the client should respond with some other action.
ƒ 100: Continue with partial request.
o 200-299
ƒ Values in the 200s signify that the request was successful.
ƒ 200: Means everything is fine.
o 300-399
ƒ Values in the 300s are used for files that have moved and usually include a Location header indicating
the new address.
ƒ 300: Document requested can be found several places; they'll be listed in the returned document.

9
CS506 Final term preparation | Lecture 19 to 45

o 400-499
ƒ Values in the 400s indicate an error by the client.
ƒ 404: Indicates that the requested resource is not available.
ƒ 401: Indicates that the request requires HTTP authentication.
ƒ 403: Indicates that access to the requested resource has been denied.
o 500-599
ƒ Codes in the 500s signify an error by the server.
ƒ 503: Indicates that the HTTP server is temporarily overloaded and unable to handle the request.
Server Side Programming
Web server pages can be either static pages or dynamic pages. A static web page is a simple
HTML (Hyper Text Transfer Language) file. When a client requests an HTML page the server simple sends
back response with the required page.
While in case of dynamic web page s server executes an application which generates HTML web pages
according to specific requests coming from client. These dynamically generated web pages are sent back
to client with the response.
Why build Pages Dynamically?
We need to create dynamic web pages when the content of site changes frequently and client specific
response is required. Some of the scenarios are listed below
• The web page is based on data submitted by the user e.g. results page from search engines and order
confirmation pages at on line stores.
• The Web page is derived from data that changes frequently e.g. a weather report or news headlines
page.
• The Web page uses information from databases or other server-side resources e.g. an e- commerce
site could use a servlet to build a Web page that lists the current price and availability of each item that
is for sale.
Server side programming involves
• Using technologies for developing web pages that include dynamic content.
• Developing web based applications which can produce web pages that contain information that is
connection-dependent or time-dependent.
Dynamic Web Content Technologies Evolution
Dynamic web content development technologies have evolved through time in speed, security, ease of
use and complexity. Initially C based CGI programs were on the server. Then template based
technologies like ASP and PHP were then introduced which allowed ease of use for designing complex
web pages. Sun Java introduced Servlets and JSP that provided more speed and security as well as better
tools for web page creation.
Layers & Web Application
Normally web applications are partitioned into logical layers. Each layer performs a specific functionality
which should not be mixed with other layers. Layers are isolated from each other to reduce coupling
between them but they provide interfaces to communicate with each other.
1 Presentation Layer:
• Provides a user interface for client to interact with application. This is the only part of application
visible to client.

10
CS506 Final term preparation | Lecture 19 to 45

2 Business Layer
• The business or service layer implements the actual business logic or functionality of the application.
For example in case of online shopping systems this layer handles transaction management.
3 Data Layer
• This layer consists of objects that represent real-world business objects such as an Order,
OrderLineItem, Product, and so on.
Java - Web Application Technologies
There are several Java technologies available for web application development which includes Java
Servlets, JavaServer Pages, and JavaServer Faces etc.

Lecture #26:
Java Servlets:Servlets are java technology’s answer to CGI programming. CGI was widely used for
generating dynamic content before Servlets arrived. They were programs written mostly in C, C++ that
run on a web server and used to build web pages.

What Servlets can do?


• Servlets can do anything that a java class can do. For example, connecting with database,
reading/writing data to/from file etc.
• Handles requests sent by the user (clients) and generates response dynamically (normally HTML
pages).
• The dynamically generated content is send back to the user through a webserver (client)
Servlets vs. other SSP technologies: The java’s servlet technology has following advantage over their
counter parts:
1 Convenient: Servlets can use the whole java API e.g. JDBC. So if you already know java, why learn
Perl or C. Servlets have an extensive infrastructure for automatically parsing and decoding HTML form
data, reading and sending HTTP headers, handling cookies and tracking session etc and many more
utilities.
2 Efficient: With traditional CGI, a new process is started for each request while with servlets each
request is handled by a lightweight java thread, not a heavy weight operating system process.
3 Powerful: Java servlets let you easily do several things that are difficult or impossible with regular CGI.
For example, servlets can also share data among each other
4 Portable: Since java is portable and servlets is a java based technology therefore they are generally
portable across web servers
5 Inexpensive: There are numbers of free or inexpensive web servers available that are good for
personal use or low volume web sites. For example Apache is a commercial grade webserver that is
absolutely free. However some very high end web and application servers are quite expensive e.g. BEA
weblogic.
Software Requirements:To use java servlets will be needed

11
CS506 Final term preparation | Lecture 19 to 45

• J2SE
• Additional J2EE based libraries for servlets such as servlet-api.jar and jsp- api.jar. Since these libraries
are not part of J2SE, you can download these APIs separately. However these APIs are also available
with the web server you’ll be using.
• A capable servlet web engine (webserver)
Jakarta Servlet Engine (Tomcat)
Jakarta is an Apache project and tomcat is one of its subprojects. Apache Tomcat is an open source web
server, which is used as an official reference implementation of Java Servlets and Java Server Pages
technologies. Tomcat is developed in an open and participatory environment and released under the
Apache software license.
1 Environment Setup: To work with servlets and JSP technologies, you first need to set up the
environment. Tomcat installation can be performed in two different ways (a) using .zip file (b) using .exe
file.
This setup process is broken down into the following steps: 1. Download the Apache Tomcat Server 2.
Install Tomcat 3. Set the JAVA_HOME variable 4. Set the CATALINA_HOME variable 5. Set the
CLASSPATH variable 6. Test the Server.
Set the CATALINA_HOME variable
CATALINA_HOME is used to tell the system about the root directory of the TOMCAT.
 To run Tomcat (web server) you need to set only the two environment variables and these are
JAVA_HOME & CATALINA_HOME.
Installing Tomcat using .exe file
Set the JAVA_HOME variable
Choosing .exe mode does not require completing this step.
Set the CATALINA_HOME variable
Choosing .exe mode does not require completing this step.

Lecture #27:
Standard Directory Structure of a J2EE Web Application
A web application is defined as a hierarchy of directories and files in a standard layout. Such
hierarchies can be used in two forms
• Unpack
o Where each directory & file exists in the file system separately
o Used mostly during development
• Pack
o Known as Web Archive (WAR) file
o Mostly used to deploy web applications
The webapps folder is the top-level Tomcat directory that contains all the web applications
deployed on the server. Each application is deployed in a separate folder often referred as
“context”.
 To make a new application e.g myapp in tomcat you need a specific folder hierarchy.
• Create a folder named myapp in C:\jakarta-tomcat-5.5.9\webapps folder. This name will also
appear in the URL for your application. For example http://localhost:8080/myapp/index.html

12
CS506 Final term preparation | Lecture 19 to 45

• All JSP and html files will be kept in main application folder (C:\jakarta-
tomcat-5.5.9\webapps\myapp).
Writing Servlets
1 Servlet Types
• Servlet related classes are included in two main packages javax.servlet and javax.servlet.http.
• Every servlet must implement the javax.servlet.Servlet interface, it contains the servlet’s life
cycle methods etc. (Life cycle methods will be discussed in next handout)
• In order to write your own servlet, you can subclass from GernericServlet or HttpServlet.
1.1 GenericServlet class
• Available in javax.servlet package
• Implements javax.servlet.Servlet
Extend your class from this class if you are interested in writing protocol independent
1.2 HttpServlet class
• Available in javax.servlet.http package
• Extends from GenericServlet class
• Adds functionality for writing HTTP specific servlets as compared to GernericServlet
• Extend your class from HttpServlet, if you want to write HTTP based servletsservlets.
Servlet Class Hierarchy

Types of HTTP requests


HTTP supports different types of request to be sent over to server. Each request has some
specific purpose. The most important ones are get & post. Given below a brief overview of each
request type is given. You can refer to RFC of HTTP for further details.
• GET: Requests a page from the server. This is the normal request used when browsing web
pages.
• POST: This request is used to pass information to the server. Its most common use is with
HTML forms.
• PUT: Used to put a new web page on a server.
• DELETE: Used to delete a web page from the server.
• OPTIONS: Intended for use with the web server, listing the supported options.
• TRACE: Used to trace servers
GET & POST, HTTP request types
Some details on GET and POST HTTP request types are given below.

13
CS506 Final term preparation | Lecture 19 to 45

• GET
o Attribute-Value pair is attached with requested URL after ‘?’.
o For example if attribute is ‘name’ and value is ‘ali’ then the request will be
http://www.gmail.com/register?name=ali
o For HTTP based servlet, override doGet () methods of HttpServlet class to handle
these type of requests.
• POST
o Attribute-Value pair attached within the request body. For your reference HTTP
request diagram is given below again:
HelloWorldServlet.java
//File HelloWorldServlet.java
// importing required packages
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// extending class from HttpServelt
public class HelloWorldServlet extends HttpServlet {
/* overriding doGet() method because writing a URL in the browser
by default generate request of GET type As you can see,
HttpServletRequest and HttpServletResponse are passed to this
method. These objects will help in processing of HTTP request and
generating response for HTTP This method can throw
ServletException or IOException, so we mention these exception
types after method signature
*/
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
/* getting output stream i.e PrintWriter from response object by
calling getWriter method on it As mentioned, for generating
response, we will use HttpServletResponse object
*/
PrintWriter out = response.getWriter();
/* printing Hello World in the browser using PrintWriter
object. You can also write HTML like
out.println(“<h1> Hello World </h1>”)
*/
out.println(“Hello World! ”);
} // end doGet()

14
CS506 Final term preparation | Lecture 19 to 45

} // end HelloWorldServlet
 Save this web.xml file by placing double quotes(“web.xml”) around it as you did to save .java
files.

Lecture #28:
Servlets Lifecycle: 1 Stages of Servlet Lifecycle
A servlet passes through the following stages in its life.
• Initialize: he webserver invokes he init() method of the servlet in this stage.
• Service: The service() method is the engine of the servlet, which actually processes the client’s request.
• Destroy: servlet container shuts down or the servlet is idle for a long time, or may be the server is
overloaded. Before it does, however it calls the servlets destroy() method

Reading HTML Form Data Using Servlets


1 HTML & Servlets: Generally HTML is used as a Graphics User Interface for a Servlet.
2 Types of Data send to Web Server
When a user submits a browser request to a web server, it sends two categories of data:
• Form Data: Data that the user explicitly type into an HTML form. For example: registration
information provided for creating a new email account.
• HTTP Request Header Data: Data, which is automatically, appended to the HTTP Request from the
client for example, cookies, browser type, and browser IP address.
Reading HTML Form Data from Servlet: Now let see how we can read data from “HTML form” using
Servlet. The HttpServletRequest object contains three main methods for extractingform data submitted
by the user:
• getParameter(String name)
o Used to retrieve a single form parameter and returns String corresponding to name specified.
o Empty String is returned in the case when user does not enter any thing in the specified form
field.
o If the name specified to retrieve the value does not exist, it returns null.
Note: You should only use this method when you are sure that the parameter has only one
value. If the parameter might have more than one value, use getParamterValues().
• getParameterValues(String name)
o Returns an array of Strings objects containing all of the given values of the given request
parameter.
o If the name specified does not exist, null is returned
• getParameterNames()
o If you are unsure about the parameter names, this method will be helpful
o It returns Enumeration of String objects containing the names of the parameters that come
with the request.

15
CS506 Final term preparation | Lecture 19 to 45

o If the request has no parameters, the method returns an empty Enumeration.


Lecture #29: More on Servlets
1 Initialization Parameters:Some times at the time of starting up the application we need to provide
some initial information e,g, name of the file where server can store logging information, DSN for
database etc. Initial configuration can be defined for a Servlet by defining some string parameters in
web.xml. This allows a Servlet to have initial parameters from outside. This is similar to providing
command line parameters to a standard console based application.
Example: setting init parameters in web.xml
<init-param> //defining param 1
<param-name> param1 </param-name>
<param-value> value1 </param-value>
</init-param>
<init-param> //defining param 2
<param-name> param2 </param-name>
<param-value> value2 </param-value> </init-param>

1.1 ServletConfig
Every Servlet has an object called ServletConfig associated with it. It contains relevant information about
the Servlet like initialization parameters defined in web.xml
1.2 Reading Initialization Parameters The method getInitParameter()of ServletConfig is usually used to
access init parameters. It takes a String as parameter, matches it with <param-name> tag under all
<init-param> tags and returns <param-value> from the web.xml.
 Another way to read initialization parameters out side the init () method is • Call
getServletConfig() to obtain the ServletConfig object • Use getInitParameter() of ServletConfig
to read initialization parameters
1.3 Response Redirection: There are two forms of response redirection that can be possible:
• Sending a standard redirect
• Sending a redirect to an error page
1.4 Sending a standard Redirect
• Using response.sendRedirect(“myHtml.html”) method, a new request is generated which redirects the
user to the specified URL.
1.5 Sending a redirect to an error page: Instead of using response.sendRedirect (), wecan
useresponse.sendEorror () to show user an error page. This method takes two parameters, first the
error number that is a predefined constant of the response class (listed below) and seconds the
appropriate error message.
The error numbers are predefined constants of the HttpServletResponse class.
For example: o SC_NOT_FOUND (404) o SC_NO_CONTENT (204) o SC_REQUEST_TIMEOUT (408)
2 ServletContext
ServletContext belongs to one web application. Therefore it can be used for sharing resources among
servlets in the same web application.
 There is a single ServletContext per web application.
 Different Sevlets will get the same ServletContext object, when calling getServletContext()
during different sessions.

16
CS506 Final term preparation | Lecture 19 to 45

3 Request Dispatcher: RequestDispatcher provides a way to forward or include data from another
source. The method getRequestDispatcher(String path) of ServletContext returns a RequestDispatcher
object associated with the resource at the given path passed as a parameter.
Two important methods of RequestDispatcher are:
• forward(ServletRequest req, ServletResponse resp)
• include(ServletRequest req, ServletResponse resp)

4 RequestDispatcher: forward
It allows a Servlet to forward the request to another resource (Servlet, JSP or HTML file) in the same
Servlet context.
5 RequestDispatcher: include: It allows a Servlet to include the results of another resource in its
response. The two major differences from forward are:
• Data can be written to the response before an include
• The first Servlet which receive the request, is the one which finishes the response

Lecture #30: Dispatching Requests


HttpServletRequest Methods
Let’s discuss some methods of HttpServletRequest class
1 setAttribute(String, Object): We can put any object to the context using setAttribute() method in the
key-value pair form. These attributes are also set or reset between requests.
2 getAttribute(String): The objects set by the setAttribute() method can be accessed using getAttribute()
method. Passing the key in the form of string as a parameter to this method will return the object
associated with that particular key in the context.
3 getMethod(): This method returns the name of HTTP method which was used to send the request. The
two possible returning values could be, get or post.
4 getRequestURL(): It can be used to track the source of Request. It returns the part of the request’s URL
without query string.
5 getProtocol(): It returns the name and version of the protocol used.
6 getHeaderNames(): It returns the enumeration of all available header names that are contained in the
request.
7 getHearderName(): It takes a String parameter that represents the header name and returns that
appropriate header. Null value is returned if there is no header exists with the specified name.
HttpServletResponse Methods
Let’s discuss some methods of HttpServletResponse class
1 setContentType(): Almost every Servlet uses this header. It is used before getting the PrintWriter
Stream. It is used to set the Content Type that the PrintWriter is going to use.
2 setContentLength(): This method is used to set the content length. It takes length as an integer
parameter.
3 addCookie(): This method is used to add a value to the Set-Cookie header. It takes a Cookie object as a
parameter and adds it to the Cookie-header.
4 sendRedirect(): This method redirects the user to the specific URL. This method also accepts the
relative URL. It takes URL string as parameter and redirects the user to that resource.

17
CS506 Final term preparation | Lecture 19 to 45

Session Tracking
Many applications require a series of requests from the same client to be associated withone another.
For example, any online shopping application saves the state of a user's shopping cart across multiple
requests. Web-based applications are responsible for maintaining such state, because HTTP protocol is
stateless. To support applications that need to maintain state, Java Servlet technology provides an API
for managing sessions and allows several mechanisms for implementing sessions.
1 Continuity problem- user’s point of view: Suppose a user logs on to the online bookshop, selects some
books and adds them to his cart. He enters his billing address and finally submits the order. HTTP cannot
track session as it is stateless in nature and user thinks that the choices made on page1 are remembered
on page3.
2 Continuity problem- Server’s point of view: The server has a very different point of view. It considers
each request independent from other even if the requests are made by the same client.
Lecture #31: Session Tracking
Cookies can be used to put small information on the client’s machine and can be used for various other
purposes besides session tracking. An example of simple “Online Book Store”, using cookies, will also be
surveyed.
1 Store State Somewhere:To maintain the conversational state, the straightforward approach is to store
the state. But where? These states either can be stored on server or on client. However, both options
have their merits and demerits.
Storing state on server side makes server really complicated as states needed to be stored for each
client.
2 Post-Notes: In order to maintain the conversational state, server puts little notes (some text, values
etc.) on the client slide. When client submits the next form, it also unknowingly submits these little
notes. Server reads these notes and able to recall who the client is.
3 Three Typical Solutions: Three typical solutions come across to accomplish session tracking. These are:
3.1. Cookies: a cookie is a piece of text that a web server can store on a client’s (user)hard disk.
3.2. URL Rewriting:
3.3. Hidden Fields
3.1.1 What a cookie is? Cookies allow the web sites to store information on a client machine and later
retrieve it. The pieces of information are stored as name-value pair on the client. Later while
reconnecting to the same site (or same domain depending upon the cookie settings), client returns the
same name-value pair to the server.
3.1.2 Cookie’s Voyage: let’s take an example.
• If you type URL of a Web site into your browser, your browser sends a request for that web
page
• Before sending a request, browser looks for cookie files that amazon has set
• Amazon web server receives the request and examines the request for cookiesIf cookies are received,
amazon can use them
3.2 Potential Uses of Cookies: Whether cookies have more pros or cons is arguable. However, cookies
are helpful in the following situations.
• identifying a user during an e-commerce session. For example, this book is added into shopping cart by
this client.
• Avoiding username and password as cookies are saved on your machine
• customizing a site.

18
CS506 Final term preparation | Lecture 19 to 45

• Focused Advertising.
3.3 Sending Cookies to Browser: Following are some basic steps to send a cookie to a browser (client).
1 Create a Cookie Object: A cookie object can be created by calling the Cookie constructor, which takes
two strings: the cookie name and the cookie value. Cookie c = new Cookie (“name”, “value”);
2. Setting Cookie Attributes: Before adding the cookie to outgoing headers (response), various
characteristics of the cookie can be set. For example, whether a cookie persists on the disk or not. If yes
then how long. Using setMaxAge(int lifetime) method indicates how much time (in seconds) should
elapse before the cookie expires. “c.setMaxAge(60);” // expired after one hour.
3. Place the Cookie into HTTP response: After making changes to cookie attributes, the most important
and unforgettable step is to add this currently created cookie into response. If you forget this step, no
cookie will be sent to the browser. “response.addCookie(c);”
4 Reading Cookies from the Client: To read the cookies that come back from the client, following steps
are generally followed.
4.1. Reading incoming cookies:
To read incoming cookies, get them from the request object of the HttpServeltRequest by calling
following method: “Cookie cookies[] = request.getCookies();”
4.2. Looping down Cookies Array:
Once you have an array of cookies, you can iterate over it. Two important methods of Cookie class are
getName() & getValue(). These are used to retrieve cookie name and value respectively.

Lecture 32: Session Tracking 2


1 URL Rewriting: URL rewriting provides another way for session tracking. With URL rewriting, the
parameter that we want to pass back and forth between the server and client is appended to the URL.
This appended information can be retrieve by parsing the URL. This information can be in the form of:
• Extra path information,
• Added parameters, or
• Some custom, server-specific URL change
 Due to limited space available in rewriting a URL, the extra information is usually limited to a
unique session ID.
The following URLs have been rewritten to pass the session ID 123
• Original -http://server: port/servlet /rewrite
• Extra path information -http://server: port/servlet/rewrite/123
• Added parameters -http://server: port/servlet/rewrite?id=123
• Custom change -http://server: port/servlet/rewrite;$id$123
1.1 Disadvantages of URL rewriting
The following Disadvantages of URL rewriting, are considerable: -
• What if the user bookmarks the page and the problem get worse if server is not assigning a unique
session id.
• Every URL on a page, which needs the session information, must be rewritten each time page is
served, which can cause
o Computationally expensive
o Can increase communication overhead
• Unlike cookies, state information stored in the URL is not persistent
• This mechanism limits the client interaction with the server to HTTP GET request.

19
CS506 Final term preparation | Lecture 19 to 45

How to make Query String? if you want to pass some attribute and values along with URL, you can use
the technique of query string. Attribute names and values are written in pair form after the ?.
Original URL: http://server:port/servletex /register
After adding parameters: http://server:port/servletex/register ?name=ali
If you want to add more than one parameter, all subsequent parameters are separated by & sign.
Adding two parameters: http://server:port/servletex/register ?name=ali&address=gulberg.

2 Hidden Form Fields


HTML forms can have an element that looks like the following:
<INPUT TYPE="HIDDEN" NAME="sessionid" VALUE="123" />
Hidden Forms Fields do not affect the appearance of HTML page. They actually contain the information
that is needed to send to the server. Thus, hidden fields can also be used to store information (like
sessionid) in order to maintain session.
3 Java Solution for Session Tracking
Java provides an excellent solution to all the problems that occurred in tracking a session. The
Servlet API provides several methods and classes specifically designed to handle session tracking. In
other words, servlets have built in session tracking.
Sessions are represented by an HttpSession object. HttpSession tacking API built on top of URL rewriting
and cookies.
4 Working with HttpSession: Let’s have a look on HttpSession working step by step
1. Getting the user’s session object: To get the user’s session object, we call the getSession() method of
HttpServeltRequest that returns the object of HttpSession
HttpSession sess = request.getSession(true);
If true is passed to the getSession() method, this method returns the current session associated with this
request.
2. Storing information in a Session: To store information in Session object (sess), we use setAttribute()
method of HttpSession class. Session object works like a HashMap, so it is able to store any java object
against key. So you can store number of keys and their values in pair form. For example,
sess.setAttribute(“sessionid”, ”123”);
3 Looking up information associated with a Session: To retrieve back the stored information from
session object, getAttribute()method of HttpSession class is used. For example,
String sid=(String)sess.getAttribute(“sessionid”);

 getAttribute() method returns Object type, so typecast is required


4. Terminating a Session: After the amount of time, session gets terminated automatically. We can see
its maximum activation time by using getMaxInactiveInterval() method of HttpSession class.
sess.invalidate()

5 HttpSession – Behind the scenes


When we call getSession() method, there is a lot going on behind the scenes. For every user, a unique
session ID is assigned automatically. As the server deals with lot of users at a time, this ID is used to
distinguish one user from another. Now here is the question, how this ID sends to the user? Answer is,
there are two options

20
CS506 Final term preparation | Lecture 19 to 45

Option 1: If the browser supports cookies, the Servlet will automatically creates a session cookie and
store the session ID within that cookie.
Option 2: If the first option fails because of browser that does not support cookies then the Servlet will
try to extract the session ID from the URL.
6 Encoding URLs sent to Client
Servlet will automatically switch to URL rewriting when cookies are not supported or disabled by the
client. When Session Tracking is based on URL rewriting, it requires additional help from the Servlets.
For a Servlet to support session tracking via URL rewriting, it has to rewrite (encode) every local URL
before sending it to the client. Now see how this encoding works
HttpServletResponse provides two methods to perform encoding
• String encodeURL(String URL)
• String encodeRedirectURL(String URL).
7 Difference between encodeURL() and encodeRedirectURL()
encodeURL() is used for URLs that are embedded in the webpage, that the servlet generates. For
example,
String URL = ”/servlet/sessiontracker”;
String eURL = response.encodeURL(URL);
out.println(“<A HREF=\” ” + eURL + ”\ ”> …… </A>”);
Whereas encodeRedirectURL() is used for URLs that refers yours site is in sendRedirect() call. For
example,
String URL = ”/servlet/sessiontracker”;
String eURL = response.encodeRedirectURL(URL);
Response.sendRedirect(eURL);
8 Some Methods of HttpSession: Now let’s explore some methods of HttpSession class
• setAttribute(String, Object)
o This method associates a value with a name.
• getAttribute(String)
o Extracts previously stored value from a session object. It returns null if no value is associated
with the given name
• removeAttribute(String)
o This method removes values associated with the name
• getId( )
o This method returns the unique identifier of this session
• getCreationTime( )
o This method returns time at which session was first created
• getMaxInactiveInterval( ) , setMaxInactiveInterval(int)
o To get or set the amount of time session should go without access before being invalidated.

Lecture 33: Address Book Case Study Using Servlets


1 Design Process
In this handout, we will discuss the design process of a simple address book. A step by step procedure of
creating a simple address book is given below.

21
CS506 Final term preparation | Lecture 19 to 45

2 Layers & Web Application:


• Presentation Layer:
o Provides a user interface for client to interact with application. This is the only
o Part of application visible to client.
• Business Layer:
o The business or service layer implements the actual business logic or functionality of the
application. For example in case of online shopping systems this layer Handles transaction management.
• Data Layer:
o This layer consists of objects that represent real-world business objects such as an Order,
OrderLineItem, Product, and so on. It also encapsulates classes which are used to interact with
the data providing services such as databases, other web services etc.
 presentation and business logic will be merged into servlets
 Layers depends upon the size of the application and some other factors such as scalability,
portability etc.
3 Package
Many times when we get a chance to work on a small project, one thing we intend to do is to put all java
files into one single directory (folder). It is quick, easy and harmless.
3.1 What is a package?: In simple terms, a set of Java classes organized for convenience in the same
directory to avoid the name collisions. Packages are nothing more than the way we organize files into
different directories according to their functionality, usability as well as category they should belong to.
3.2 How to create a package: Suppose we have a file called HelloWorld.java, and we want to put this file
in a package world. First thing we have to do is to specify the keyword package with the name of the
package we want to use (world in our case) on top of our source file, before the code that defines the
real classes in the package
3.3 How to use package: By using "import" keyword, all class files reside only in that package can be
imported. For example,
// we can use any public classes inside world package
import world.*;
// import all public classes from java.util package
import java.util.*;
// import only ArrayList class (not all classes in
// java.util package)
import java.util.ArrayList;
4 JavaServer Pages (JSP)
Like Servlets, JSP is also a specification. JSP technology enables Web developers and designers to rapidly
develop and easily maintain, information-rich, dynamic Web pages that leverage existing business
systems. As part of the Java technology family, JSP technology enables rapid development of Web-based
applications that are platform independent. JSP technology separates the user interface from content
generation, enabling designers to change the overall page layout without altering the underlying
dynamic content.
4.1 The Need for JSP: With servlets, it is easy to
• Read form data
• Read HTTP request headers
• Set HTTP status codes and response headers

22
CS506 Final term preparation | Lecture 19 to 45

• Use cookies and session tracking


• Share data among servlets
• Remember data between requests
• Get fun, high-paying jobs
But, it sure is a pain to
• Use those println() statements to generate HTML
• Maintain that HTML
4.2 The JSP Framework:
• Use regular HTML for most of the pages
• Mark servlet code with special tags
• Entire JSP page gets translated into a servlet (once), and servlet is what actually
 The Java Server Pages technology combine with Java code and HTML tags in the same document
to produce a JSP file.

4.3 Advantages of JSP over Competing Technologies:


• Versus ASP or ColdFusion
o JSPs offer better language for dynamic part i.e. java
o JSPs are portable to multiple servers and operating systems
• Versus PHP
o JSPs offer better language for dynamic part
o JSPs offer better tool support
• Versus pure servlets
o JSPs provide more convenient way to create HTML
o JSPs can use standard front end tools (e.g., UltraDev)
o JSPs divide and conquer the problem of presentation and business logic
4.4 Setting Up Your Environment
In order to create a web-application that entirely consists of JSP pages and Html based pages, the setup
is fairly simple as compared to a servlet based web application.
• Set your CLASSPATH. No.
• Compile your code. No.
• Use packages to avoid name conflicts. No.
• Put JSP page in special directory, like WEB-INF for servlets No.
o tomcat_install_dir/webapps/ROOT
o jrun_install_dir/servers/default/default-app
• Use special URL to invoke JSP page. No

Lecture 34: Java Server Pages


JSP is a text based document capable of returning either static or dynamic content to a client’s browser.
Static content and dynamic content can be intermixed. The examples of static content are HTML, XML &
Text etc. Java code, displaying properties of JavaBeans and invoking business logic defined in custom
tags are all examples of dynamic content.
1 First run of a JSP:

23
CS506 Final term preparation | Lecture 19 to 45

1.1 Benefits of JSP


• Convenient
o we already know java and HTML. So nothing new to be learned to work with JSP.
o Like servlets (as seen, ultimately a JSP gets converted into a servlet), provides an extensive
infrastructure for
ƒ Tracking sessions
ƒ Reading and sending HTML headers
ƒ Parsing and decoding HTML form data
• Efficient
o Every request for a JSP is handled by a simple JSP java thread as JSP gets converted into a
servlet. Hence, the time to execute a JSP document is not dominated by starting a process.
• Portable
o Like Servlets, JSP is also a specification and follows a well standardized API.The JVM which is
used to execute a JSP file is supported on many architectures and operating systems.
• Inexpensive
o There are number of free or inexpensive Web Servers that are good for commercial quality
websites.
2 JSP Ingredients: Besides HTML, a JSP may contain the following elements.
• Directive Elements
o Provides global control of JSP ……..……………..<%@%>
• Scripting Elements
o JSP comments ……………………………………...<%----%>
o declarations ……………………………………...<%! %>
o Used to declare instance variables & methods
ƒ expressions……………………………………...<%=%>
o A java code fragment which returns String
ƒ scriptlets……………………………………...<%%>
o Blocks of java code
• Action Elements
o Special JSP tags ……..……………………………..<jsp: .…./>

3 Scripting Elements:
1 Comments: Comments are ignored by JSP-to-servlet translator. Two types of comments are possibly
used in JSP.

24
CS506 Final term preparation | Lecture 19 to 45

• HTML comment: These comments are shown in browser, means on taking view source of the web
page; these sorts of comments can be read. Format of HTML comments is like to:
<!-- comment text-->
• JSP comment:
These comments are not displayed in browser and have format like:
<%-- comment text --%>
2 Expressions: The format of writing a Java expression is:
<%= Java expression %>
These expressions are evaluated, after converted to strings placed into HTML page at the place it
occurred in JSP page.
3.3 Scriptlets: The format of writing a scriptlet is: <% Java code %>
After opening up the scriptlet tag, any kind of java code can be written inside it. This code is inserted
verbatim into corresponding servlet.
3.4 Declarations: The format of writing a declaration tag is: <%! Java code %>
This tag is used to declare variables and methods at class level. The code written inside this tag is
inserted verbatim into servlet’s class definition.

4 Writing JSP scripting Elements in XML


writing JSP pages in old style is still heavily used as we had shown you in the last example. Equivalent
XML tags for writing scripting elements are given below:
Comments: No equivalent tag is defined
Declaration:<jsp:declartion> </jsp:declaration>
Expression:<jsp:expression> </jsp:expression>
Scriptlet:<jsp:scriptlet> </jsp:scriptlet>
It’s important to note that every opening tag also have a closing tag too.

Lecture 35: JavaServer Pages


We start our discussion from implicit objects. Let’s find out what these are?
1 Implicit Objects: To simplify code in JSP expressions and scriptlets, you are supplied with eight
automatically defined variables, sometimes called implicit objects. The three most important variables
are request, response & out.
• request: This variable is of type HttpServletRequest, associated with the request. It gives you access to
the request parameters, the request type (e.g. GET or POST), and the incoming HTTP request headers
(e.g. cookies etc).
• response: This variable is of type HttpServletResponse, associated with the response to client. By using
it, you can set HTTP status codes, content type and response headers etc.
• out: This is the object of JspWriter used to send output to the client.
 The flow of the example is shown below in the pictorial form.

25
CS506 Final term preparation | Lecture 19 to 45

5 implicit objects are given below:


• session: This variable is of type HttpSession, used to work with session object.
• application: This variable is of type ServletContext. Allows to store values in key-value pair form that
are shared by all servlets in same web application/
• config: This variable is of type ServletConfig. Represents the JSP configuration options e.g. init-
parameters etc.
• pageContext: This variable is of type javax.servlet.jsp.PageContext, to give a single point of access to
many of the page attributes. This object is used to stores the object values associated with this object.
• exception: This variable is of type java.lang.Throwable. Represents the exception that is passed to JSP
error page.
• page: This variable is of type java.lang.Object. It is synonym for this.
2 JSP Directives
JSP directives are used to convey special processing information about the page to JSP container. It
affects the overall structure of the servlet that results from the JSP page. It enables programmer to:
• Specify page settings
• To include content from other resources
• To specify custom-tag libraries
2.1 Format: <%@ directive {attribute=”val”}* %>
In JSP, there are three types of directives: page, include & taglib. The formats of using these are:
• page:<%@ page{attribute=”val”}*%>
• include:<%@ include{attribute=”val”}*%>
• taglib:<%@ taglib{attribute=”val”}*%>

2.2 JSP page Directive: Give high level information about servlet that will result from JSP page. It can be
used anywhere in the document. It can control
• Which classes are imported
• What class the servlet extends
• What MIME type is generated
• How multithreading is handled
• If the participates in session
• Which page handles unexpected errors etc.
The lists of attributes that can be used with page directive are:
• language = “java”
• extends = “package.class”
• import = “package.*,package.class”
• session = “true | false”
• info= “text”
• contentType = “mimeType”
• isThreadSafe = “true | false”
• errorPage= “relativeURL”
• isErrorPage = “true | false”
 • To import package like java.util
<%@page import=“java.util.*” info=“using util package” %>
 • To declare this page as an error page

26
CS506 Final term preparation | Lecture 19 to 45

<%@ page isErrorPage = “true” %>


 • To generate the excel spread sheet
<%@ page contentType = “application/vnd.ms-excel” %>
2.3 JSP include Directive: Lets you include (reuse) navigation bars, tables and other elements in JSP page.
You can include files at
• Translation Time (by using include directive)
• Request Time (by using Action elements, discussed in next handouts)
Format:<%@include file=“relativeURL”%>
Purpose:To include a file in a JSP document at the time document is translated into a servlet.
3 JSP Life Cycle Methods: The life cycle methods of JSP are jspInit(), _jspService() and
jspDesroy(). On receiving each request, _jspService() method is invoked that generates the response as
well.

Lecture #36:
1 JavaBeans
• A java class that can be easily reused and composed together in an application.
• Any java class that follows certain design conventions can be a JavaBean.
1.1 JavaBeans Design Conventions: These conventions are:
• A bean class must have a zero argument constructor
• A bean class should not have any public instance variables/attributes (fields)
• Private values should be accessed through setters/getters
o For boolean data types, use boolean isXXX( ) & setXXX(boolean)
• A bean class must be serializable.

Lecture 37: JSP Action Elements and Scope


1 JSP Action Elements: JSP action elements allow us to work with JavaBeans, to include pages at request
time and to forward requests to other resources etc.
Format:Expressed using XML syntax
• Opening tag<jsp:actionElement attribute=”value” ….. >
• Body body
• Closing tag</jsp:actionElement>
Empty tags (without body) can also be used like
<jsp:actionElement attribute=”value” ….. >

Some JSP Action Elements


• To work with JavaBeans
-<jsp:useBean />
-<jsp:setProperty />
-<jsp:getProperty />
• To include resources at request time
-<jsp:include />
• To forward request to another JSP or Servlet
-<jsp:forward />
• To work with applets

27
CS506 Final term preparation | Lecture 19 to 45

-<jsp:plugin />
2 Working with JavaBeans using JSP Action Elements:
The three action elements are used to work with JavaBeans.
2.1 JSP useBean Action Element: It is used to obtain a reference to an existing JavaBean object by
specifying id(name of object) and scope in which bean is stored. If a reference is not found, the bean is
instantiated.
The format of this action element is:
<jsp:useBean id = “name”
scope = “page|request|session|application” class=“package.Class ”
/>
2.2 JSP setProperty Action Element: To set or change the property value of the specified bean. String
values are converted to types of properties by using the related conversion methods.
The format of this action element is:
<jsp:setProperty name = “beanName or id” property = “name” value
=“value”/>
2.3 JSP getProperty Action Element: Use to retrieves the value of property, converts it to String and
writes it to output stream.
The format of this action element is:
<jsp:getProperty name = “beanName or id”property = “name”/>
 The SumBean has following attributes • firstNumber• secondNumber • sum
3 Sharing Beans & Object Scopes: Let’s discover what impact these scopes can produce on JavaBeans
objects which are stored in one of these scopes.
3.1 page: This is the default value of scope attribute, if omitted. It indicates, in addition to being bound
to local variable, the bean object should be placed in the pageContext object. The bean’s values are only
available and persist on JSP in which bean is created.
3.2 request: This value signifies that, in addition to being bound to local variable, the bean object should
be placed in ServletRequest object for the duration of the current request.
3.3 session: This value means that, in addition to being bound to local variable, the bean object will be
stored in the HttpSession object associated with the current request.
3.4 Application: This very useful value means that, in addition to being bound to local variable, the bean
object will be stored in ServletContext. The bean objects stored in ServletContext is shared by all
JSPs/servlets in the same web application.
4 Summary of Object’s Scopes

28
CS506 Final term preparation | Lecture 19 to 45

5 More JSP Action Elements


Let’s talk about two important action elements. These are include & forward.
5.1 JSP include action Element: It is used to include files at request time. The jsp:include action element
requires two attributes: page & flush.
• page: a relative URL of the file to be included.
• flush: must have the value “true”
<jsp:include page = “relative URL” flush = “true” />
5.2 JSP forward action Element:
It is used to forward request to another resource. The format of jsp:forward action is:
<jsp:forward page = “one.jsp” />

Lecture 38: JSP Custom Tags


“<%
CourseDAO courseDAO = new CourseDAO(); ………………
// iterating over ArrayList
for (…………………… ) {
……………………
…………………… //displaying courseoutline
}
………………
%>”
Can we replace all the above code with one single line? Yes, by using custom tag we can write like this:
<mytag:coursetag pageName=“java” />
What is a Custom Tag?
• In simplistic terms, “a user defined component that is used to perform certain action”. This action
could be as simple as displaying “hello world” or it can be as complex as displaying course outline of
selected course after reading it from database.
• It provides mechanism for encapsulating complex functionality for use in JSPs.
• We already seen & used many built in tags like:
o < jsp:useBean …… />
o < jsp:include …… />
o < jsp:forward …… /> etc.
Why Build Custom Tag?
With Custom tags, it is possible for web page designers to use complex functionality without knowing
any java.
Advantages of using Custom Tags
• Provides cleaner separation of processing logic and presentation, than JavaBeans.
• Have access to all JSP implicit objects like out, request etc.
• Can be customized by specifying attributes.
Types of Tags: Three types of can be constructed. These are:
1. Simple Tag
2. Tag with Attribute
3. Tag with Body

29
CS506 Final term preparation | Lecture 19 to 45

1 Simple Tag: A simple tag has the following characteristics:


• Start and End of tag
• No body is specified within tag
• No attributes

2 Tag with Attributes:A tag with attributes has the following characteristics:
• Start and End of tag
• Attributes within tag
• No body enclosed
• For example
< mytag:hello attribute = “value” />
3 Tag with Body: A tag with body has the following characteristics:
• Start and End of tag
• May be attributes
• Body enclosed within tag
• For example
< mytag:hello optional_attributes ………… >
some body
</ mytag:hello >
Building Custom Tags:
1 Steps for Building Custom Tags: The following steps are used in order to develop your own custom tag.
These are: 1. Develop the Tag Handler class 2. Write Tag library Descriptor (.tld) file 3. Deployment
2 Develop the Tag Handler class:
• Tag Handler is also a java class that is implicitly called when the associated tag is encountered in the
JSP.
• Must implement SimpleTag interface
• Usually extend from SimpleTagSupport class that has already implemented SimpleTag interface.
• For example,
public class MyTagHandler extends SimpelTagSupport {
………………………
………………………
}
• doTag() method
o By default does nothing
o Need to implement / override to code/write functionality of tag
o Invoked when the end element of the tag encountered.
• JSP implicit objects (e.g. out etc) are available to tag handler class through pageContext object.
• pageContext object can be obtained using getJspContext() method.
• For example to get the reference of implicit out object, we write.
o PageContext pc = (PageContext) getJspContext();

30
CS506 Final term preparation | Lecture 19 to 45

o JspWriter out = pc.getOut();


3 Write Tag Library Discriptor (.tld) file:
• It is a XML based document.
• Specifies information required by the JSP container such as:
o Tag library version
o JSP version
o Tag name
o Tag Handler class name
o Attribute names etc.
4 Deployment:
• Place Tag Handler class in myapp/WEB-INF/classes folder of web application.
• Place .tld file in myapp/WEB-INF/tlds folder of web application.

Using Custom Tags:Use taglib directive in JSP to refer to the tag library. For example
<%@ taglib uri=”TLD file name” prefix=“mytag” %>
Building tags with attributes:
If you want to build a tag that can also take attributes, for example
<mytag:hello attribute=”value” />

Lecture 39: MVC + Case Study


Most widely used/popular architecture: Model View Controller (MVC).
1 Error Page: Error Pages enables you to customize error messages.
1.1 Defining and Using Error Pages: isErrorPage attribute of a page directive is used to declare a JSP as
an error page.
2 Case Study – Address Book:
2.1 Ingredients of Address Book:Java Beans, Java Server Pages and Error Page that are being used in this
Address Book Example are: -
Java Beans
• PersonInfo – Has following attributes:
o name
o address
o phoneNum
• PersonDAO
o Encapsulates database logic.
o Therefore, it will be used to save and retrieve PersonInfo data.
Java Server Pages
• addperson.jsp
o Used to collect new person info that will be saved in database.
• saveperson.jsp
o Receives person info from addperson.jsp
o Saves it to database
• searchperson.jsp
o Used to provide search criteria to search Person’s info by providing name
• showperson.jsp

31
CS506 Final term preparation | Lecture 19 to 45

o This page receive person’s name from searchperson.jsp to search in


o database
o Retrieves and displays person record found against person name
Error Page
• addbookerror.jsp
o This page is declared as an error page and used to identify the type of exception.
o In addition to that, it also displays the message associated with the received exception
to the user.
3 Model View Controller (MVC):
3.1 Participants and Responsibilities: The individual’s responsibility of three participants (model, view &
controller) is given below:
• Model
The model represents the state of the component (i.e. its data and the methods required to manipulate
it) independent of how the component is viewed or rendered.
• View
The view renders the contents of a model and specifies how that data should be presented.
• Controller
The controller translates interactions with the view into actions to be performed by the model.
3.2 Evolution of MVC Architecture: In the beginning, we used no MVC. Then we had MVC Model 1 and
MVC Model 2 architectures.
• 3.2.1 MVC Model 1
A Model 1 architecture consists of a Web browser directly accessing Web-tier JSP pages.The JSP pages
access JavaBeans that represent the application model. And the next view to display (JSP page, servlet,
HTML page, and so on) is determined either by hyperlinks selected in the source document or by
request parameters.

Lecture 40: MVC Model 2 Architecture


1 Page-Centric Approach: A web application that is collection of JSPs
1.1 Page-with-Bean Approach (MVC Model1): This approach is different from page-centric approach in a
way that all the business logic goes into JavaBeans. Therefore, the web application is a collection of JSPs
and JavaBeans.
2 MVC Model 2 Architecture: This architecture introduces a controller. This controller can be
implemented using JSP or servlet. Introducing a controller gives the following advantages:
It centralizes the logic for dispatching requests to the next view based on:
• The Request URL
• Input Parameters
• Application state
It gives the single point of control to perform security checks and to record logging information. It also
encapsulates the incoming data into a form that is usable by the back-end MVC model.

The client (browser) sends all the requests to the controller. Servlet/JSP acts as the Controller and is in
charge of the request processing and creation of any beans or objects (Models) used by the JSP.

32
CS506 Final term preparation | Lecture 19 to 45

JSP is working as View and there is not much processing logic within the JSP page itself, it is simply
responsible for retrieving objects and/or beans, created by the Servlet, extracting dynamic content from
them and put them into the static templates.
3 Case Study: Address Book using MVC Model 2
The address book example that is built using page-with-bean approach will be modified to incorporate
controller. We’ll show you how to implement controller using JSP as well as with servlet. Let’s first
incorporate controller using JSP.
3.1 Introducing a JSP as Controller: Add another JSP (controller.jsp) that
• Acts as a controller Recieves requests from addperson.jsp & searchperson.jsp
• Identifies the page which initiates the request
• Uses JavaBeans to save or search persons to/from database
• Forwards or redirects the request to appropriate (saveperson.jsp or showperson.jsp) page.
3.2 How controller differentiates between requests? The simplest solution lies in using the consistent
Name (e.g. action) of the submit button across all the pages but with different and unique values.
The same rule applies to hyperlinks that send the action parameter along with value by using query
string technique.

Lecture 41: Layers and Tiers


Layers – represents the logical view of application
Tiers – represents physical view of application
Layers: The partitioning of a system into layers such that each layer performs a specific type of
functionality and communicates with the layer that adjoins it.
Layered architecture based on three layers. These are
• Presentation Layer
• Business Layer
• Data Layer
Tiers: Tiers are physically separated from each other. Layers are spread across tiers to build up an
application. Two or more layers can reside on one tier.
J2EE Multi-Tiered Applications:
In a typical J2EE Multi-Tiered application, a client can either be a swing based application or a web
based.

Lecture 42: Expression Language


Sun Microsystems introduced the Servlet API, in the later half of 1997.
The Expression Language, not a programming or scripting language, provides a way to simplify
expressions in JSP. It is a simple language that is geared towards looking up objects, their properties and
performing simple operations on them.
JSP Before and After EL
To add in motivational factor so that you start learning EL with renewed zeal and zest.
Expression Language Nuggets
We’ll discuss the following important pieces of EL. These are:
• Syntax of EL: $ { validExpression }

33
CS506 Final term preparation | Lecture 19 to 45

EL Accessors
The dot (.) and bracket ([ ]) operator let you access identifies and their properties.

• Expressions & identifiers:


• Arithmetic, logical & relational operators
• Automatic type conversion
• Access to beans, arrays, lists & maps
• Access to set of implicit objects

Lecture 43: JavaServer Pages Standard Tag Library (JSTL)


The JSP Standard Tag Library (JSTL) is a collection of custom tag libraries that implement general-
purpose functionality common to Web applications, including iteration and conditionalization, data
management formatting, manipulation of XML, and database access. The development theme of JSTL is
“scriptlet free JSP”.

34
CS506 Final term preparation | Lecture 19 to 45

JSTL & EL:


JSTL includes supports for Expression Language thus EL can be used to specify dynamic attribute values
for JSTL actions without using full-blown programming language.
EL now becomes a standard part of JSP 2.0. This allows the use of EL anywhere in the document.
Functional Overview
As mentioned, JSTL encapsulates common functionality that a typical JSP author would encounter. This
set of common functionality has come about through the input of the various members of the expert
group. it is actually composed of four separate tag libraries:
Core−>contains tags for conditions, control flow and to access variables etc.
XML manipulation−>contains tags for XML parsing and processing
SQL−>contains tags for accessing and working with database.
Internationalization and formatting−>contains tags to support locale messages, text, numbers and date
formation.
Twin Tag Libraries
JSTL comes in two flavors to support various skill set personal
• Expression Language (EL) version
• Request Time (RT) version: <%= expression %>
c:set
Provides a tag based mechanism for creating and setting scope based variables. Its syntax is as follows:
<c:set var=“name” scope = “scope” value = “expression” />
c:out
A developer will often want to simply display the value of an expression, rather than store it.
This can be done by using c:out core tag, the syntax of which appears below:
<c:out value = “expression” default = “expression” />
c:remove
As its name suggests, the c:remove action is used to delete a scoped variable, and takes two attributes.
The var attribute names the variable to be removed, and the optional scope attribute indicates the
scope from which it should be removed and defaults to page.
For example, to remove a variable named square from page scope, we’ll write:
<c:remove var = “square” />
c:forEach
In the context of Web applications, iteration is primarily used to fetch and display collections of data,
typically in the form of a list or sequence of rows in a table. The primary JSTL action for implementing
iterative content is the c:forEach core tag. This tag supports two different styles of iteration:
Iteration over an integer range (like Java language's for statement)
Iteration over a collection (like Java language's Iterator and Enumeration classes).
Iteration over an Integer range
To iterate over a range of integers, the syntax of the c:forEach tag will look like:
<c:forEach var=“name” begin=“expression” end=“expression”
step=“expression” >
Body Content
</c:forEach>
The begin and end attributes should be either constant integer values or expressions evaluating to
integer values.

35
CS506 Final term preparation | Lecture 19 to 45

c:if
Like ordinary Java’s if, used to conditionally process the body content. Syntax
<c:if test= “expression” >
Body Content
</c:if>
c:choose
c:choose the second conditionalization tag, used in cases in which mutually exclusively test are required
to determine what content should be displayed. The syntax is shown below:
<c:choose>
<c:when test= “expression” >
Body content
</c:when>
……………
<c:otherwise >
Body content
</c:otherwise>
</c:choose>
netBeans 4.1 and JSTL
If you are using netBeans 4.1 IDE then you have to add JSTL library to your project manually.
 Remember that the JSTL 1.1 library is only added to current project. You have to repeat this step
for each project in which you want to incorporate JSTL.

Lecture 44: Client Side Validation & JavaServer Faces (JSF)


Client Side Validation
Forms validation on the client-side is essential -- it saves time and bandwidth, and gives you more
options to point out to the user where they've gone wrong in filling out the form. Furthermore, the
browser doesn't have to make a round-trip to the server to perform routine client-side tasks.
 Any scripting language can be used to achieve the said objective. However, JavaScript and
VBScript are t wo popular options.
Why is Client Side Validation Good?
There are two good reasons to use client-side validation:
• It's a fast form of validation: if something's wrong, the alarm is triggered upon submission of the form.
• You can safely display only one error at a time and focus on the wrong field, to help ensure that the
user correctly fills in all the details you need.
JavaServer Faces (JSF)
JSF technology simplifies building the user interface for web applications. It does this by providing a
higher-level framework for working with your web applications.
Different existing frameworks
• Struts: A popular open source JSP-based Web application framework helps in defining a structured
programming model (MVC), also validation framework and reduces tedious coding but…
o Adds complexity and doesn’t provide UI tags
o Very Java programmer centric
• Tapestry: Another popular framework that is extensively used in the industry is Tapestry. It has almost
similar sort of problems as with Struts.

36
CS506 Final term preparation | Lecture 19 to 45

JavaServer Faces
A framework which provides solutions for:
• Representing UI components
• Managing their state
• Handling events
• Input validation
• Data binding
• Automatic conversion
• Defining page navigation
• Supporting internationalization and accessibility.
If you are familiar with Struts and Swing (the standard Java user interface framework for desktop
applications), think of JavaServer Faces as a combination of those two frameworks.
JSF Events Handling
A JSF application works by processing events triggered by the JSF components on the pages. These
events are caused by user actions.
JSF Validators
Validators make input validation simple and save developers hours of programming. JSF provides a set
of validator classes for validating input values entered into input components.
Some built-in validators are:
• DoubleRangeValidator
Any numeric type, between specified maximum and minimum values
• LongRangeValidator
Any numeric type convertible to long, between specified maximum and minimum values
• LengthValidator
Ensures that the length of a component's local value falls into a certain range (between minimum &
maximum). The value must be of String type.
JSF – Managed Bean-Intro
Managed beans represent the data model, and are passed between business logic and pages. Some
other salient features are:
• Use the declarative model
• Entry point into the model and event handlers
• Can have beans with various states
JSF – Value Binding
Value binding expressions can be used inside of JSF components to:
• Automatically instantiate a JavaBean and place it in the request or session scope.
• Override the JavaBean's default values through its accessor methods.
• Quickly retrieve Map, List, and array contents from a JavaBean.
• Synchronize form contents with value objects across a number of requests.
The syntax of binding expressions is based on the JavaServer Pages (JSP) 2.0 Expression Language.
JSF – Method Binding
Unlike a value binding, a method binding does not represent an accessor method. Instead, a method
binding represents an activation method.
For example, binding an event handler to a method
<h:commandButton ……

37
CS506 Final term preparation | Lecture 19 to 45

actionListener=“#{customer.loginActionListener}”
……… />
JSF Navigation
Page navigation determines the control flow of a Web application. JSF provides a default navigational
handler and this behavior can be configured in configuration. However, you can do it visually in most
tools like Sun Studio Creator.

Lecture #45: JavaServer Faces


Web Services: Web services are Web-based enterprise applications that use open, XML-based standards
and transport protocols to exchange data with calling clients.
Web Service is becoming one of those overly overloaded buzzwords these days. Due to their increasing
popularity, Java platform Enterprise Edition (J2EE) provides the APIs and tools you need to create and
deploy interoperable web services and clients.
Web service, Definition by W3C
W3C recently has come up with a decent definition of web services. According to W3C, A Web service is
a software application identified by a URI, whose interfaces and binding are capable of being defined,
described and discovered by XML artifacts and supports direct interactions with other software
applications using XML based messages via internet-based protocols”.
Characteristics of Web services
Web services are XML-based throughout. Pretty much everything in the domain of Web services is
defined in XML.
Web services can be dynamically located and invoked. And typically they will be accessed and invoked
over both internet and intranet.
Why Web services?
Interoperable: Connect across heterogeneous networks using ubiquitous web-based standards
Economical: Recycle components, no installation and tight integration of software
Automatic: No human intervention required even for highly complex transactions
Accessible: Legacy assets & internal apps are exposed and accessible on the web
Available: Services on any device, anywhere, anytime
Scalable: No limits on scope of applications and amount of heterogeneous applications
Types of Web service
Data providers: For example, a service providing stock quotes
Business-to-business process integration: For example, purchase orders
Enterprise application integration: Different applications work together simply by adding a webservice
wrapper
Comparison between Web page & Web service: Just to give you a sense on the difference between a
web page and a web service, consider the following table:

38
CS506 Final term preparation | Lecture 19 to 45

Web service Architectural Components


Following are the core building blocks of web service architecture:
• Service Description-How do clients know how it works (which functions, parameters etc.)?
• Service Registration (Publication) and Discovery
 Universal Description, Discovery & Integration (UDDI)
• Service Invocation

39

You might also like