CS506 Final Term Lec 19 To 45
CS506 Final Term Lec 19 To 45
CS506 Final Term Lec 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
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
3
CS506 Final term preparation | Lecture 19 to 45
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.
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
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
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
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.
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
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
15
CS506 Final term preparation | Lecture 19 to 45
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
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.
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.
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.
21
CS506 Final term preparation | Lecture 19 to 45
22
CS506 Final term preparation | Lecture 19 to 45
23
CS506 Final term preparation | Lecture 19 to 45
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.
25
CS506 Final term preparation | Lecture 19 to 45
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
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.
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
29
CS506 Final term preparation | Lecture 19 to 45
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
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” />
31
CS506 Final term preparation | Lecture 19 to 45
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.
33
CS506 Final term preparation | Lecture 19 to 45
EL Accessors
The dot (.) and bracket ([ ]) operator let you access identifies and their properties.
34
CS506 Final term preparation | Lecture 19 to 45
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.
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.
38
CS506 Final term preparation | Lecture 19 to 45
39