You are on page 1of 62

Education and Research

We enable you to leverage knowledge anytime, anywhere!

Presentation Tier using JSP and JSF


Day 1

ER/CORP/CRS/ED113/003

Ver. No.: 1.3

Confidential

Copyright 2008, Infosys Technologies Ltd.

General Guideline
(2008) Infosys Technologies Ltd.
This document contains valuable confidential and proprietary information of Infosys. Such
confidential and proprietary information includes, amongst others, proprietary intellectual
property which can be legally protected and commercialized. Such information is furnished
herein for training purposes only. Except with the express prior written permission of Infosys,
this document and the information contained herein may not be published, disclosed, or used
for any other purpose.

Copyright 2008, Infosys Technologies Ltd.

Confidential

Confidential Information

This Document is confidential to Infosys Technologies Limited. This document contains


information and data that Infosys considers confidential and proprietary (Confidential
Information).
Confidential Information includes, but is not limited to, the following:
Corporate and Infrastructure information about Infosys
Infosys project management and quality processes
Project experiences provided included as illustrative case studies

Any disclosure of Confidential Information to, or use of it by a third party, will be


damaging to Infosys.
Ownership of all Infosys Confidential Information, no matter in what media it resides,
remains with Infosys.
Confidential information in this document shall not be disclosed, duplicated or used in
whole or in part for any purpose other than reading without specific written permission
of an authorized representative of Infosys.
This document also contains third party confidential and proprietary information. Such
third party information has been included by Infosys after receiving due written
permissions and authorizations from the party/ies. Such third party confidential and
proprietary information shall not be disclosed, duplicated or used in whole or in part
for any purpose other than reading without specific written permission of an authorized
representative of Infosys.
Copyright 2008, Infosys Technologies Ltd.

Confidential

Learning approach
The following are strongly suggested for a better learning and
understanding of this course:
Noting down the key concepts in the class, explained by the educator
Analyze all the examples / code snippets provided
Study and understand the self study topics
Completion and submission of all the assignments, on time
Completion of the self review questions in the lab guide
Study and understand all the artifacts including the reference materials / elearning / supplementary materials specified
Completion of the project (if applicable for this course) on time inclusive
of individual and group activities
Taking part in the self assessment activities
Participation in the doubt clearing sessions

Copyright 2008, Infosys Technologies Ltd.

Confidential

Course Objectives
To illustrate the development of presentation tier of
an enterprise application
Through Servlet, JSP and JSF

To illustrate deployment of web application on


Application Server
To illustrate role and usage of web container in web
application deployment
To share the best practices in web application
development

Copyright 2008, Infosys Technologies Ltd.

Confidential

Course Pre-requisites
Knowledge of
HTML Forms development
HTTP Methods
HTTP Request and Response model
Core Java concepts such as packaged class, interfaces
and API
Advanced Java concepts such as multithreading,
connecting to database

Copyright 2008, Infosys Technologies Ltd.

Confidential

What is Presentation tier using JSP and


JSF and where it is being used?
Every big business application is divided in various tiers
Code logic which takes care of generating the user interface
for accepting input or displaying output is called Presentation
logic
This course has relevance as, it helps you build presentation
logic for web applications using Java technologies like JSP
and Servlet

Copyright 2008, Infosys Technologies Ltd.

Confidential

Expectations
At the end of this course, the participant should be
able to Design and develop a web application using Servlet and
JSP
Design and develop a web application using JSF
framework
Develop the web application using Eclipse IDE
Develop web application that supports i18n using JSF
Deploy the developed web application in an application
server such as JBoss 5.0
Test and Debug the web application
Copyright 2008, Infosys Technologies Ltd.

Confidential

Course Agenda
Day 1

Recap of Enterprise Application development


Application Server concepts
Servlet Model and lifecycle
Deployment of Servlets

Day 2

Introduction to JSP
Basic tags in JSP
Lifecycle and lifecycle methods of JSP
Implicit objects in JSP
Tags in JSP
Directive Elements in JSP
Copyright 2008, Infosys Technologies Ltd.

Confidential

Course Agenda
Day 3

Action Elements in JSP


JSTL and Expression Language
Model 1 and Model 2 architecture
Developing web application using MVC architecture
Introduction to frameworks

Day 4

Introduction to JSF
Developing and deploying web application using JSF
Page Navigation
Managed Bean Facility
UI Components and Core tags in JSF
Copyright 2008, Infosys Technologies Ltd.

10

Confidential

Course Agenda
Day 5
Event Handling
Validators
Converters
Dynamic Data Table Creation

Day 6
Internationalization and localization of JSF web application
JSF Request Processing Lifecycle

Day 6 AN & Day 7-8


Project
Copyright 2008, Infosys Technologies Ltd.

11

Confidential

Session Plan Day 1


What is an Enterprise Application and various tiers in
Enterprise Application development?
Presentation tier technologies offered in Java EE
What is an Application Server and its
responsibilities?
Introduction to Servlet
Servlet model and its lifecycle

Copyright 2008, Infosys Technologies Ltd.

12

Confidential

Where Server-side presentation


technologies fit in Java EE?

Copyright 2008, Infosys Technologies Ltd.

13

Confidential

Education and Research


We enable you to leverage knowledge anytime, anywhere!

Enterprise Application-Quick Review

Copyright 2008, Infosys Technologies Ltd.

ER/CORP/CRS/ED113/003

Ver. No.: 1.2

Confidential
Confidential

Copyright 2008, Infosys Technologies Ltd.

Enterprise Application Software


It is an application software, that performs
business functions such as accounting, production
scheduling, customer information management,
bank account maintenance, etc.
It is hosted on servers and could simultaneously
provide services to a large number of users, over
the network
Typically it has n-tier architecture
Copyright 2008, Infosys Technologies Ltd.

15

Confidential

Enterprise Application Requirements


(Self Study)
The business components should be more looselycoupled which will enable off-the-shelf business logic
reusable components
Partition the application as per the presentation and
business logic for modularity, manage-ability and
maintainability
Deployable application across multiple platforms
(hardware / software) independent of the underlying
database technology
Capable of handling huge data and complex business
rules
Copyright 2008, Infosys Technologies Ltd.

16

Confidential

Enterprise Application Requirements


(Self Study)
Business processes and/or applications that need to
be accessed from corporate network, intranet as well
as over internet
Needs to be reliable, robust, and grow with business
Follow stringent security requirements of corporate /
business
Application that needs to change its look
frequently
Provide user-friendly functionalities and user interface

Copyright 2008, Infosys Technologies Ltd.

17

Confidential

Education and Research


We enable you to leverage knowledge anytime, anywhere!

Recap- Web Technologies

Copyright 2008, Infosys Technologies Ltd.

ER/CORP/CRS/ED113/003

Ver. No.: 1.2

Confidential
Confidential

Copyright 2008, Infosys Technologies Ltd.

Working of Web Application: static content

Copyright 2008, Infosys Technologies Ltd.

23

Confidential

Generation of Dynamic Page

Copyright 2008, Infosys Technologies Ltd.

29

Confidential

Static v/s dynamic pages


The response from the server for the request could be a static or
a dynamic page
Static Pages

Dynamic Pages

Can be created and stored in web


server in advance as HTML file

Can NOT be created and stored in web


server in advance as HTML file

Static pages do not change with


user or time

Dynamic page changes as per the user


and/or time.

For delivery of static page, all we


For delivery of dynamic page, apart
require is web server and, already- from Web Server, we require helper
stored HTML files in it
program to generate dynamic content

The program / software component that executes the serverside program to generate the dynamic content is known as the
Web Container
Copyright 2008, Infosys Technologies Ltd.

30

Confidential

Technologies used to generate dynamic


content
CGI, PHP, perl
Sun Microsystems Servlets, JSP
Microsoft -ASP

Copyright 2008, Infosys Technologies Ltd.

31

Confidential

Education and Research


We enable you to leverage knowledge anytime, anywhere!

Application Server

Copyright 2008, Infosys Technologies Ltd.

ER/CORP/CRS/ED113/003

Ver. No.: 1.2

Confidential
Confidential

Copyright 2008, Infosys Technologies Ltd.

Application Server
Application Servers are specialized Web Server +
Web Container + EJB Container
Application Servers provide all the system services to
address non-functional requirements :

Scalability through resource pooling


Security
Transaction management
Performance- connection pooling

Application developers can concentrate on functional


requirements by coding required business logic
Copyright 2008, Infosys Technologies Ltd.

33

Confidential

Application Server : JBoss


Java EE App Servers

Proprietary App Servers

Provide system services in well defined,


open, industry standard manner

Provide system services in well


defined, proprietary manner

Application development according to


Java EE specification

Application development according


to Application Server specification

Vendor independent

Vendor dependent

Ex: JBoss, Weblogic, Websphere

Ex: MS IIS

JBoss is open source, under LGPL


Full-fledged App Server built on J2EE 1.4 spec
JBoss has Tomcat embedded in it as default Web
Container
Copyright 2008, Infosys Technologies Ltd.

34

Confidential

Education and Research


We enable you to leverage knowledge anytime, anywhere!

Servlets Dynamic Page Generation


The JAVA Way!

Copyright 2008, Infosys Technologies Ltd.

ER/CORP/CRS/ED113/003

Ver. No.: 1.2

Confidential
Confidential

Copyright 2008, Infosys Technologies Ltd.

Server Side Java - Servlet


It is a Java class that resides and gets executed on the
server (to generate dynamic content)
Output of Servlet could be HTML/XML (or any MIME
type)
Servlet Container (also termed in more generic way
as, web container) executes (and manages) servlet,
when requested (through URL)

Copyright 2008, Infosys Technologies Ltd.

36

Confidential

What can a Servlet do?


Process and/or store data submitted by an HTML form
Read form data sent by client (user) in the request
Read request headers

Generate / construct the response for the request


Provide dynamic content

Manage state information for clients


As HTTP is stateless protocol, some applications would
need to store information about the client until they logout
e.g. online shopping cart

Copyright 2008, Infosys Technologies Ltd.

37

Confidential

Servlets
Any container should be able to execute any Servlet
This requirement calls for a standard interface for all
the Servlets

In order to become a servlet, the class should


implement the interface called Servlet in the
package javax.servlet
Servlets are managed by Servlet container
Each Servlet will be associated and invoked through
a URL

Copyright 2008, Infosys Technologies Ltd.

38

Confidential

Servlet API
Servlet Interface
Present in package javax.servlet
Has the following methods
init() called once for initialization of instance
variables of instantiated servlet object
service()- called each time, servlet is requested
Referred as Request Handling method
destroy() - called once after servlet object is removed
2 implementing Servlet classes
GenericServlet
HttpServlet
Copyright 2008, Infosys Technologies Ltd.

39

Confidential

GenericServlet and HttpServlet classes in API


GenericServlet (protocol independent)
Is an abstract class
Implements only init() and destroy() &
service() method is abstract
HttpServlet (Designed for HTTP protocol)
Concrete class with specific request
handling methods like doGet, doPostetc,
to handle HTTP requests based on the
HTTP method
Need not implement service() as it is
already implemented to invoke the
corresponding doXXX method
Copyright 2008, Infosys Technologies Ltd.

40

Confidential

<<interface>>

Servlet
(present in javax.servlet)

GenericServlet
(present in javax.servlet)

HttpServlet
(present in
javax.servlet.http)

Deployment Descriptor
web.xml the Deployment Descriptor
There should be on deployment descriptor per web
application
Should be placed within the WEB-INF subfolder of
Application root folder
Mapping between the URL and the corresponding
servlet class is defined within

Copyright 2008, Infosys Technologies Ltd.

41

Confidential

Simple Servlet : Problem


Problem Definition:
Create a web application with Welcome.html. The
Welcome.html should have a hyperlink which would
invoke the HelloServlet. The HelloServlet should
display Hello World ! Welcome to Servlets !!

Copyright 2008, Infosys Technologies Ltd.

42

Confidential

Simple Servlet : Solution


Solution
Create a dynamic web project
Create HelloServlet.java inheriting from Servlet
Create Welcome.html with a hyperlink to HelloServlet
Define the deployment descriptor (to map the Servlet to
the URL)
Build and deploy the application
Execute the application

Copyright 2008, Infosys Technologies Ltd.

43

Confidential

Simple Servlet : HelloServlet.java


HelloServlet.java

Contd

package edu.infy.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class HelloServlet implements
javax.servlet.Servlet {
public void destroy() {
}
public ServletConfig getServletConfig() {
return null;
}
public String getServletInfo() {
return null;
}
Copyright 2008, Infosys Technologies Ltd.

public void init(ServletConfig arg0) throws


ServletException {
}
public void service(ServletRequest request,
ServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<HTML><HEAD><TITLE>
Welcome to Servlet</TITLE></HEAD>");
These
out.println("<BODY><H2>Hello
World !
methods
are
Welcome to Servlets!</H2></BODY>
not in the
</HTML>");
scope
out.close();
}
}
44

Confidential

Simple servlet : welcome.html &


web.xml

web.xml

welcome.html

<html>
<head>
<title>Example html</title>
</head>
<body>
<h1>

<a href="hello">Click on link to


invoke a HelloServlet</a>
</body>
</html>

<! XML file header tag declarations -->


<servlet>
<servlet-name>myFirstServlet
</servlet-name>
<servlet-class>
edu.infy.servlets.HelloServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>myFirstServlet
</servlet-name>

<url-pattern>/hello</url-pattern>
</servlet-mapping>
<!-- end of root tag -->

Copyright 2008, Infosys Technologies Ltd.

45

Confidential

Simple Servlet : Folder structure


ServletDemos

WEB-INF

welcome.html
src

classes

web.xml

lib

edu
infy

servlets

HelloServlet.java

Copyright 2008, Infosys Technologies Ltd.

46

Confidential

Simple Servlet : Execution


Deploy it on the web container (tomcat)
Start the server
Open Internet Explorer -> Type the URL for the html
resource
http://localhost:8080/ServletDemos/welcome.html
Click on the link given
Watch the URL in the address bar !

Copyright 2008, Infosys Technologies Ltd.

47

Confidential

Simple Servlet: HelloServlet (Result)

Copyright 2008, Infosys Technologies Ltd.

48

Confidential

Servlet Lifecycle New request

request,

If request is
for dynamic Client
content,
invokes Web
Container
Web Server
web.xml

Loads the
Spawn a
HelloServlet
Invokes the
Instantiates
thread for
HelloServlet
class
web.xml
into
the request
memory
Invokes the
HTTP &
Generates
Web Container sends
service
the
method
HTTP
Response

<servlet>
<servlet-name>myFirstServlet</servlet-name>
<servlet-class>com.infy.HelloServlet</servlet-class>
/html");
</servlet>
Writer();
<servlet-mapping>
ITLE>
<servlet-name>myFirstServlet</servlet-name>
</HEAD>"); <url-pattern>/hello</url-pattern>
World !
</servlet-mapping>
Y> </HTML>");
Copyright 2008, Infosys Technologies Ltd.
49
Confidential

Servlet Lifecycle subsequent request


If request is
for dynamic Client
content,
invokes Web
Container

If container
Invokes
stoppedthe
or
web.xml
Spawn
servleta&
determines
thread for
undeployed,
the
request
servlet
invokes
name
destroy()
Web Server
Invokes the&
Generates
Web Container sends
HTTP
the
service
HTTP
public void service(ServletRequest request,
method
Response
ServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<HTML><HEAD><TITLE>
Welcome to Servlet</TITLE></HEAD>");
out.println("<BODY><H2>Hello World !
Welcome to Servlets!</H2></BODY> </HTML>");
out.close();
} 2008, Infosys Technologies Ltd.
Copyright
50
Confidential

Servlets: the Request-ProcessResponse cycle (Self study)


The client program (usually a web browser) makes a
request to the web server either through the GET or
POST method and asks for a service
The web server processes the client request and
hands over the request to the servlet container when
a client is requesting for servlet
The servlet container invokes the appropriate servlet
based on the configuration details and passes the
request object to the servlet for processing
Copyright 2008, Infosys Technologies Ltd.

52

Confidential

Servlets: the Request-ProcessResponse cycle (cont) (Self study)


The request object contains information about the
client (for example: identity of the remote user, form
data)
Status information, server information and the contents
to be displayed on the client browser are sent via the
response object
The servlet container ensures that the response is
properly flushed and returns control back to the host
Web server
Copyright 2008, Infosys Technologies Ltd.

53

Confidential

What is the role of Servlet Container?


Provides easy way for the web server to communicate
with the servlet and vice versa
Controls the entire lifecycle of the servlet:
loading of classes, instantiating it, initializing it, invoking
lifecycle methods on it and afterwards, making it
eligible for garbage collection
Creates and manages a new Java thread for every
servlet request it receives
Copyright 2008, Infosys Technologies Ltd.

54

Confidential

Servlet : Example
Problem Definition:
loginForm.html accepts username and password, and
passes it to Servlet, LoginServlet. LoginServlet has to
verify if it is valid username in a Database.
If valid, display Welcome! Login successful!
If invalid, display Sorry guest ! Login failed!
Note: For Simplicity, we are not connecting to Database,
whereas, we will check the username against a value. If
it is admin, then it is valid.

Copyright 2008, Infosys Technologies Ltd.

55

Confidential

Servlet : Solution
Solution
Create a dynamic web project
Create LoginServlet.java inheriting from HttpServlet
Create loginForm.html with a text field for username, a
password field for password and a submit button to
invoke the LoginServlet URL
Define the deployment descriptor (to map the
HttpServlet to the URL)
Build and deploy the application
Execute the application

Copyright 2008, Infosys Technologies Ltd.

56

Confidential

LoginServlet.java (1/2)
LoginServlet.java

LoginServlet.java

if((username == null) || (username.length()==0))


{
message="Username required field;
}else{
if(username.equals(admin){
message=Welcome! Login successful!;
}else{
message=Sorry guest, Login failed!!!;
}
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<HTML><HEAD><TITLE>Login
Page</TITLE></HEAD><BODY
BGCOLOR=\"#99CCFF\>" +
"<H1> "+ message+" </H1></BODY>
</HTML>");
}

package edu.infy.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
public class LoginServlet extends
HttpServlet{
protected void doPost(HttpServletRequest
request, HttpServletResponse response)
throws
ServletException, IOException {
String message = new String();
String username =
request.getParameter("username");

Copyright 2008, Infosys Technologies Ltd.

57

Confidential

web.xml

Copyright 2008, Infosys Technologies Ltd.

58

Confidential

loginForm.html
loginForm.html

loginForm.html
<html><head>
<title>Login Page</title>
</head>
<body bgcolor="#CCFFCC" >
<form action="Login" method="post">
<h2><center>Enter Login Details </center>
<br>
<table border="4" align="center"
bordercolor="brown" bgcolor="pink">
<tr><td>UserName</td><td>
<input type="text" name="username">
</td></tr>

Copyright 2008, Infosys Technologies Ltd.

<tr><td><input type="submit"
value="Login"/></td>
<td><input type="reset"
value="Reset"/></td></tr>
</table>
</h2>
</form>
</body>
</html>

59

Confidential

Result

Copyright 2008, Infosys Technologies Ltd.

60

Confidential

Server-side validations
What if data for username and password are left blank
and form is submitted?
How will you make sure that user has entered all
mandatory fields on the form before submitting it?
Answer JavaScript
But this is client-side validations, and user can disable
JavaScript from the web browser settings
So, we need to check it at server-side too
Checking whether the data given for the parameter is
zero-length or null are must Server-side validations
Copyright 2008, Infosys Technologies Ltd.

62

Confidential

Scope of Servlets in web application


Servlets are nothing but Java code having bits of HTML
Mixing Java code and HTML in servlet leads to

Tight coupling between presentation and business logic


Difficulty in maintaining, managing code
Any change in the presentation needs a change in servlet
Any change in the dynamic content generation needs
change in the servlet which contains presentation logic

Copyright 2008, Infosys Technologies Ltd.

63

Confidential

Can you answer these Questions?


How will the client invoke any servlet?
Through a URL
In which file do you associate a servlet with the URL?
In web.xml, using <servlet-mapping> element
The web container receives 10 requests for a HelloWorld
servlet. How many instances of HelloWorld servlet will be
created by the Container?

Only One instance


Copyright 2008, Infosys Technologies Ltd.

64

Confidential

Can you Answer these Questions?


If the servlets init method throws an Exception, will
requests to that servlet be serviced by the container?
No. Results in HTTP 500 error. All requests can be
serviced only once the init method returns successfully
Can we have instance variables in servlets? Are they
thread-safe?
Yes, Servlets can have instance variables. No, They
are NOT thread-safe. All requests to a servlet share the
same instance
Servlets are used for coding which layer of the
enterprise application?
Presentation Layer
Copyright 2008, Infosys Technologies Ltd.

65

Confidential

JSP
We need a technology which helps us to
write/maintain server-side presentation logic
easily. JSP!!!

Copyright 2008, Infosys Technologies Ltd.

66

Confidential

Reference Material
For more information about the topics covered today,
refer the supplementary material given in the
following link:
http://myshec123505d/EBook

Copyright 2008, Infosys Technologies Ltd.

67

Confidential

Summary
Java Platform, Enterprise Edition (Java EE) is the
industry, open standard for developing portable,
robust, scalable and secure server-side Java
applications
A Java EE App Server takes care of the nonfunctional requirements of a Java EE application
Java EE provides two technologies Servlet and JSP
to develop the server side presentation logic
As a good programming practice, presentation logic
and business logic need to be separated
Copyright 2008, Infosys Technologies Ltd.

68

Confidential

Summary
Servlets are difficult to maintain by the page authors/
web designers
Web designers would be maintaining the
presentation logic and hence Sun Microsystems
offered JSP technology which is as simple as HTML
and as powerful as Servlets
JSP help us to code server side presentation logic

Copyright 2008, Infosys Technologies Ltd.

69

Confidential

Thank You

The contents of this document are proprietary and confidential to Infosys Technologies Ltd. and may not be
disclosed in whole or in part at any time, to any third party without the prior written consent of
Infosys Technologies Ltd.
2008 Infosys Technologies Ltd. All rights reserved. Copyright in the whole and any part of this document
belongs to Infosys Technologies Ltd. This work may not be used, sold, transferred, adapted, abridged, copied or
reproduced in whole or in part, in any manner or form, or in any media, without the prior written consent of Infosys
Technologies Ltd.

Copyright 2008, Infosys Technologies Ltd.

70

Confidential

Extra reference slides


Folder structure of typical web application

Copyright 2008, Infosys Technologies Ltd.

71

Confidential

Folder Structure of the Web Application

Application
Root

WEB-INF

Html pages
classes

lib

web.xml

External
libraries
Copyright 2008, Infosys Technologies Ltd.

src
Packaged servlets

72

Confidential

Deployment Descriptor: web.xml


<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<servlet-name>myFirstWorld</servlet-name>
<servlet-class>HelloWorldServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>myFirstWorld</servlet-name>
<url-mapping>/hello</url-mapping>
</servlet-mapping>
</web-app>
Copyright 2008, Infosys Technologies Ltd.

73

Confidential

You might also like