0% found this document useful (0 votes)
327 views33 pages

JSP Handout v1.0

Module Objectives. Pre-requisite. What is a JSP page?. When to use Servlet and when JSP. Session 03: Sample JSP. Learning Objectives. Try It Out. Summary. Test your understanding.

Uploaded by

mrjegankumar
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
327 views33 pages

JSP Handout v1.0

Module Objectives. Pre-requisite. What is a JSP page?. When to use Servlet and when JSP. Session 03: Sample JSP. Learning Objectives. Try It Out. Summary. Test your understanding.

Uploaded by

mrjegankumar
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Handout: JSP

Version: JSP/Handout/0408/1.0
Date: 04-04-08

Cognizant
500 Glen Pointe Center West
Teaneck, NJ 07666
Ph: 201-801-0233
[Link]

Handout - JSP

TABLE OF CONTENTS
Introduction ...................................................................................................................................5
About this Module .........................................................................................................................5
Target Audience ...........................................................................................................................5
Module Objectives ........................................................................................................................5
Pre-requisite .................................................................................................................................5
Session 02: Understanding JSP ..................................................................................................6
Learning Objectives ......................................................................................................................6
What is a JSP page? ....................................................................................................................6
When to use Servlet and when JSP .............................................................................................6
Summary ......................................................................................................................................6
Test Your Understanding..............................................................................................................6
Session 03: Sample JSP ................................................................................................................7
Learning Objectives ......................................................................................................................7
Try It Out .......................................................................................................................................7
Summary ......................................................................................................................................7
Test your Understanding ..............................................................................................................7
Session 04: JSP Architecture Model ............................................................................................8
Learning Objectives ......................................................................................................................8
JSP Model 1 Architecture .............................................................................................................8
JSP Model 2 Architecture .............................................................................................................8
Summary ......................................................................................................................................9
Test your Understanding ..............................................................................................................9
Session 05: JSP Syntax elements ..............................................................................................10
Learning Objectives ....................................................................................................................10
JSP Element:

JSP Expression ...............................................................................................10

JSP Element:

JSP Expression ...............................................................................................10

JSP Element:

JSP Scriptlet ....................................................................................................10

JSP Element:

JSP Declaration ..............................................................................................10

JSP Element:

JSP page Directive..........................................................................................10

JSP Element:

JSP include Directive ......................................................................................10

JSP Element:

JSP Comment .................................................................................................10

JSP Element: jsp:include Action .................................................................................................11


Try It Out .....................................................................................................................................11

Page 2
Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected

Handout - JSP
Summary ....................................................................................................................................11
Test your Understanding ............................................................................................................11
Session 07: Understanding JSP Page Directives .....................................................................12
Learning Objectives ....................................................................................................................12
JSP Page Directives ...................................................................................................................12
Try It Out .....................................................................................................................................13
Summary ....................................................................................................................................14
Test your Understanding ............................................................................................................14
Session 10: JSP Page Life Cycle ................................................................................................15
Learning Objectives ....................................................................................................................15
JSP Page Life Cycle ...................................................................................................................15
Summary ....................................................................................................................................15
Test your Understanding ............................................................................................................15
Session 12: JSP Model - Advanced ............................................................................................16
Learning Objectives ....................................................................................................................16
Translation process ....................................................................................................................16
JSP Pages as XML Documents .................................................................................................16
Try It Out .....................................................................................................................................16
Summary ....................................................................................................................................17
Test your Understanding ............................................................................................................17
Session 13: JSP Implicit Variables and Objects .......................................................................18
Learning Objectives ....................................................................................................................18
JSP Implicit Variables and Objects.............................................................................................18
Request ......................................................................................................................................18
Response....................................................................................................................................18
Session .......................................................................................................................................18
Config .........................................................................................................................................19
Application ..................................................................................................................................19
Page ...........................................................................................................................................19
PageContext ...............................................................................................................................19
Try It Out .....................................................................................................................................19
Summary ....................................................................................................................................20
Test your Understanding ............................................................................................................20
Session 16: JSP Page Scopes ....................................................................................................21
Learning Objectives ....................................................................................................................21

Page 3
Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected

Handout - JSP
JSP Page Scopes .......................................................................................................................21
Try It Out .....................................................................................................................................21
Summary ....................................................................................................................................22
Test your Understanding ............................................................................................................23
Session 18: JSP Static and Dynamic Inclusions ......................................................................24
Learning Objectives ....................................................................................................................24
Static Inclusions ..........................................................................................................................24
Dynamic Inclusions .....................................................................................................................24
Try It Out .....................................................................................................................................24
Summary ....................................................................................................................................25
Test your Understanding ............................................................................................................25
Session 21: Java Beans with JSP Scriptlets .............................................................................26
Learning Objectives ....................................................................................................................26
JavaBeans ..................................................................................................................................26
JavaBeans Component Design Conventions: ............................................................................26
JavaBeans Component property: ...............................................................................................26
Syntax: ........................................................................................................................................26
Try It Out .....................................................................................................................................27
Summary ....................................................................................................................................28
Test your Understanding ............................................................................................................28
Session 22: Java Beans with JSP Actions ................................................................................29
Learning Objectives ....................................................................................................................29
Java Beans and JSP ..................................................................................................................29
Creating and Using a JavaBeans Component: ..........................................................................29
Setting JavaBeans Component Properties: ...............................................................................29
Retrieving JavaBeans Component Properties: ..........................................................................29
Try It Out .....................................................................................................................................29
Summary ....................................................................................................................................30
Test your Understanding ............................................................................................................31
References ....................................................................................................................................32
Websites .....................................................................................................................................32
Books ..........................................................................................................................................32
STUDENT NOTES: ........................................................................................................................33

Page 4
Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected

Handout - JSP

Introduction
About this Module
This module provides an overview about following topics:

An introduction to JSP

Basic concepts of JSP

Custom Tags and Libraries

Target Audience
This module is designed for the entry level trainees.

Module Objectives
After completing this module, you will be able to:

Work with JSP

Explain JSP Model: Basics

Describe JSP Model: Advanced

Work with Java Beans

Identify Custom Tags and Libraries

Pre-requisite
This module is designed for the trainees having basic knowledge on java.

Page 5
Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected

Handout - JSP

Session 02: Understanding JSP


Learning Objectives
After completing this session, you will be able to:

Comprehend the JSP Page

Identify the time to use Servlet and JSP

What is a JSP page?


JSP page is a text-based document that contains two types of text:

Static template data: It can be expressed in any text-based format, such as HTML,
SVG, WML, and XML.

JSP elements: It constructs dynamic content.

When to use Servlet and when JSP


1. JSP is used for presentation stuff and servlets are used for control and business logic
stuff. They are good for non-HTML content, such as a file download servlet or a chart
generating servlet, because it is simpler to deal with that content in servlets.
2. In JSP, anything between %> and <% gets written out, so people initially try making a JSP
page that writes out an image or something and wonder why their image is corrupted.
3. JSP is certainly better for HTML output because you can write a lot of the HTML as plain
HTML instead of having to put everything in [Link]() statements and escape all the
quotes.

Summary

JSP is used for presentation stuff.

They are good for non-HTML content, such as a file download servlet or a chart
generating servlet.

JSP is certainly better for HTML output because you can write a lot of the HTML as
plain HTML.

Test Your Understanding


1. What is a JSP page?
2. When should you use Servlet and JSP?

Page 6
Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected

Handout - JSP

Session 03: Sample JSP


Learning Objectives
After completing this session, you will be able to:

Create a simple JSP

Try It Out
Problem Statement:
Write a program to that prints this is an example for template text using html template, this is an
example of expression using JSP expression and this is an example of scriplet
Code:
<html>
<head>
<title>My Title</title>
</head>
<body>
<h1>This is an example for template text</h1>
<%="This is an example of expression"
%>
<br>
<%[Link]("This is an example of
scriplet");%>
</body>
</html>
How It Works:
Based upon the style it will prints

Summary

A JSP page is a text-based document that contains two types of text.

Static template data, which can be expressed in any text-based format, such as
HTML, SVG, WML, and XML.

JSP elements construct dynamic content.

Test your Understanding


1. What is a JSP Page?
2. Differentiate between template text, scriplet, and expression

Page 7
Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected

Handout - JSP

Session 04: JSP Architecture Model


Learning Objectives
After completing this session, you will be able to:

Comprehend a JSP Page

Differentiate between various JSP architectural models

Compare the merits and demerits of different models

JSP Model 1 Architecture


The JSP page alone is responsible for processing the incoming request and replying back to the
client.
Merits:
1. Simple
2. Separation of presentation from content
Demerits:

It may not be desirable for complex implementations.

While this may not seem to be much of a problem for Java developers, it is certainly
an issue if your JSP pages are created and maintained by designers, which is usually
the norm on large projects.

JSP Model 2 Architecture


1. Hybrid approach for serving dynamic content, since it combines the use of both servlets
and JSP.
2. Here, the servlet acts as the controller and is in charge of the request processing and the
creation of any beans or objects used by the JSP, as well as deciding, depending on the
users actions, which JSP page to forward the request to..
3. Note particularly that there is no processing logic within the JSP page itself.
4. It is simply responsible for retrieving any objects or beans that may have been previously
created by the servlet, and extracting the dynamic content from that servlet for insertion
within static templates
Merits:
1. Makes use of the predominant strengths of both technologies, using JSP to generate the
presentation layer and servlets to perform process-intensive tasks. Separation of
presentation from content
2. Cleanest separation of presentation from content, leading to clear delineation of the roles
and responsibilities of the developers and page designers on your programming team.

Page 8
Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected

Handout - JSP

Summary

JSP Model 1 Architecture: The JSP page alone is responsible for processing the
incoming request and replying back to the client. Separation of presentation from
content.

JSP Model 2 Architecture: Makes use of the predominant strengths of both


technologies, using JSP to generate the presentation layer and servlets to perform

Test your Understanding


1. What is a JSP Page?
2. When will you use Servlet and when JSP?

Page 9
Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected

Handout - JSP

Session 05: JSP Syntax elements


Learning Objectives
After completing this session, you will be able to:

Explain the syntax to be followed for different JSP elements

JSP Element: JSP Expression


JSP Element: JSP Expression
Syntax: <%= expression %>
Interpretation: Expression is evaluated and placed in output.

JSP Element: JSP Expression


Syntax: <%= expression %>
Interpretation: Expression is evaluated and placed in output..

JSP Element: JSP Scriptlet


Syntax: <% code %>
Interpretation: Code is inserted in service method.

JSP Element: JSP Declaration


Syntax: <%! code %>
Interpretation: Code is inserted in body of servlet class, outside the service method.

JSP Element: JSP page Directive


Syntax: <%@ page att="val" %>
Interpretation: Directions to the servlet engine about general setup.

JSP Element: JSP include Directive


Syntax: <%@ include file="url %>
Interpretation: A file on the local system to be included when the JSP page is translated into a
servlet.

JSP Element: JSP Comment


Syntax: <%-- comment --%>
Interpretation: Comment is ignored, when JSP page is translated into servlet.

Page 10
Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected

Handout - JSP

JSP Element: jsp:include Action


Syntax: <jsp:include page="relative URL" flush="true"/>
Interpretation: Directions to the servlet engine about general setup.
Example:
<jsp:include page="relative URL" flush="true"/>

Try It Out
Problem Statement:
Create [Link] using all the jsp syntax elemts.t
Code:
<%=WelcomeJsp %>
<% [Link](Welcome JSP): %>
<%! Striing str= (Welcome JSP); %>

How It Works:
Based upon the JSP syntax it will work

Summary

JSP Scriptlet: It is inserted in service method.

JSP Declaration: It is inserted in body of servlet class, outside the service method.

JSP Comment: Comment is ignored, when JSP page is translated into servlet.

JSP Expression: Expression is evaluated and placed in output.

Test your Understanding


1. What are the different JSP elements?

Page 11
Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected

Handout - JSP

Session 07: Understanding JSP Page Directives


Learning Objectives
After completing this session, you will be able to:

Explain JSP Page Directives

JSP Page Directives


The page directive is used to define attributes that apply to an entire JSP page.
There attributes of page directive are, language, extends, import, session, buffer, autoFlush,
isThreadSafe, info, errorPage, contentType, isErrorPage, pageEncoding, isELIgnored
JSP Page Directives : language
Used for specifying other scripting languages to be used in a JSP page.
JSP Page Directives : extends
Used for specifying some other java classes to be used in a JSP page.
JSP Page Directives : import
Used for importing packages or java classes.
JSP Page Directives : session
Used for controlling session management.
JSP Page Directives : buffer
Used by the out object to handle output generated by the JSP page.
JSP Page Directives : autoFlush
Used for controlling buffer flow.
JSP Page Directives : isThreadsafe
Used to control the request handling feature.
JSP Page Directives : info
Used to set some description for the page..
JSP Page Directives : errorPage
Used to set the error page to be called if any error occurs.
JSP Page Directives : contentType
Used to specify the MIME type.

Page 12
Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected

Handout - JSP
JSP Page Directives : isErrorPage
Used to specify if the jsp page is an error page or not
JSP Page Directives : pageEncoding
Used to specify the language that the page uses when the page is sent to the browser.
JSP Page Directives : isELIgnored
Used to control the EL expression evaluation in the JSP page.

Try It Out
Problem Statement:
Create a JSP page containing page directives
Code:
package [Link];
public class Perform {
public String getWord(){
return "hello world";
}
public void createError(){
int i=10/0;
}

<%@ page import="[Link]" errorPage="[Link]" session="true"


%>
<html>
<head>
<title>Page directives demo</title>
</head>
<body>
<% Perform p=new Perform();%>
<h1><%= [Link]()%></h1>
<!-- uncomment the line below to see how the
errorPage attribute of page directive works -->
<%-- [Link]() --%>
</body>
</html>

Page 13
Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected

Handout - JSP

Summary
Attributes are as follows:

language: Used for specifying other scripting languages to be used in a JSP page

extends: Used for specifying some other java classes to be used in a JSP page

import: Used for importing packages or java classes

session: Used for controlling session management

buffer: Used by the out object to handle output generated by the JSP page

autoFlush: Used for controlling buffer flow

isThreadSafe: Used to control the request handling feature

info: Used to set some description for the page

errorPage: Used to set the error page to be called if any error occurs

contentType: Used to specify the MIME type

isErrorPage: Used to specify if the JSP page is an error page or not

pageEncoding: Used to specify the language that the page uses when the page is
sent to the browser

isELIgnored: Used to control the EL expression evaluation in the JSP page>

Test your Understanding


1. What are the important attributes of page directive?

Page 14
Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected

Handout - JSP

Session 10: JSP Page Life Cycle


Learning Objectives
After completing this session, you will be able to:

Comprehend JSP page life cycle

JSP Page Life Cycle


The three stages of JSP's life cycle are:

Translation: It is where the JSP is converted into a Java file

Compilation: It is where the translated java file is compiled to a class file

Execution: It is where the compiled and initialized Servlet (JSP) handles the requests

Summary

Translation: This is the place, where the JSP is converted into a Java file.

Compilation: This is the place, where the translated java file is compiled to a class
file.

Execution: This is the place, where the compiled and initialized Servlet (JSP) handles
the requests.

Test your Understanding


1. Explain JSP page life cycle.

Page 15
Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected

Handout - JSP

Session 12: JSP Model - Advanced


Learning Objectives
After completing this session, you will be able to:

Comprehend translation process

Identify the JSP pages as XML documents

Translation process

The JSP page is first converted into a Java file. This java file is compiled to a class file
and is initialized to handle http requests, just like http Servlet.

The best part is a JSP developer, who need not do this translation manually. The
Servlet container (Tomcat) does this translation.

JSP Pages as XML Documents

A JSP document is an XML document and must comply with the XML standard.

Fundamentally, this means that a JSP document must be well formed, meaning that
each start tag must have a corresponding end tag and that the document must have
only one root element.

In addition, JSP elements included in the JSP document must comply with the XML
syntax.

Try It Out
Problem Statement:
Create JSP named [Link] with only XML tags. The page should contain a instance variable
named names of type [Link]. Add three names of your choice to that list. And then iterate
though the list to print on the browser all the contents of the list.
This can be using the following XML tags:
<jsp:directive>, <sp:declaration>, <jsp:expression> and <jsp:scriptlet>>.
Code:
<jsp:root xmlns:jsp="[Link] version="1.2">
<jsp:[Link] import="[Link].*"/>
<jsp:declaration>private List names;</jsp:declaration>
<jsp:scriptlet>
names=new ArrayList();
[Link]("abc");
[Link]("def");
[Link]("ghi");
for(Object temp:names){
</jsp:scriptlet>

Page 16
Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected

Handout - JSP
<jsp:expression>
temp
</jsp:expression>
<br></br>
<jsp:scriptlet>}</jsp:scriptlet>
</jsp:root>

Summary

Translation: This is the place, where the JSP is converted into a Java file.

A JSP document is an XML document and must comply with the XML standard.

Test your Understanding


1. Define the translation process.
2. List JSP pages as XML documents.

Page 17
Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected

Handout - JSP

Session 13: JSP Implicit Variables and Objects


Learning Objectives
After completing this session, you will be able to:

JSP implicit variables and Objects

JSP Implicit Variables and Objects


Request: An instance of HttpServletRequest
response: An instance of HttpServletResponse
out: An instance of JspWriter
session: An instance of HttpSession
config: An instance of ServletConfig
application: An instance of ServletContext
page: An instance of Object
pageContext: An instance of PageContext
exception: An instance of Throwable

Request
The class or the interface name of the object request is [Link]. The object request
is of type [Link]. This denotes the data included with the HTTP
Request. The client first makes a request that is then passed to the server. The requested object is
used to take the value from clients web browser and pass it to the server. This is performed using
HTTP request like headers, cookies and arguments.

Response
This denotes the HTTP Response data. The result or the information from a request is denoted by
this object. This is in contrast to the request object. The class or the interface name of the object
response is [Link]. The object response is of type [Link].
>httpservletresponse. Generally, the object response is used with cookies. The response object is
also used with HTTP Headers

Session
This denotes the data associated with a specific session of user. The class or the interface name
of the object Session is [Link]. The object Session is of type
[Link]. The previous two objects, request and response, are used to pass
information from web browser to server and from server to web browser respectively. The Session
Object provides the connection or association between the client and the server. The main use of
Session Objects is for maintaining states when there are multiple page requests. This will be
explained in further detail in following

Page 18
Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected

Handout - JSP
Config
This is used to get information regarding the Servlet configuration, stored in the Config object. The
class or the interface name of the Config object is ServletConfig. The object Config is written
[Link]

Application
This is used to share the data with all application pages. The class or the interface name of the
Application object is ServletContext. The Application object is written:
[Link]

Page
The Page object denotes the JSP page, used for calling any instance of a Page's servlet. The
class or the interface name of the Page object is [Link]. The Page object is written:
[Link]

PageContext
This is used to access page attributes and also to access all the namespaces associated with a
JSP page. The class or the interface name of the object PageContext is [Link]. The
object PageContext is written: [Link]

Try It Out
Problem Statement:
Create a jsp named [Link]. Set attributes in all the 4 possible scopes and try to retrieve them.
Also display on the browser the servlet name using the SerlvetConfig instance.
This sample uses the following implicit variables: request, out, session, config, application
Code:
<html>
<body>
<% [Link]("req","Req Atribute");
[Link]("sess","Session Atribute");
[Link]("context","Context Atribute");
[Link]("page","Page Atribute");
%>
<%= [Link]("req")%><br>
<%= [Link]("sess")%><br>
<%= [Link]("context")%><br>
<%= [Link]("page")%><br>
<%= [Link]()%>
</body>
</html>

Page 19
Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected

Handout - JSP
How It Works:
The attributes are stored in various scopes and are retrieved and displayed. Servlet name is
displayed to show the config parameter.

Summary

Request: An instance of HttpServletRequest

Response: An instance of HttpServletResponse

Out: An instance of JspWriter

session: An instance of HttpSession

Config: An instance of ServletConfig

Application: An instance of ServletContext

Page: An instance of object

pageContext: An instance of PageContext

Exception: An instance of Throwable

Test your Understanding


1. What are JSP implicit variables and objects?

Page 20
Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected

Handout - JSP

Session 16: JSP Page Scopes


Learning Objectives
After completing this session, you will be able to:

JSP Page Scopes

JSP Page Scopes

Page Scope

Request Scope

Session Scope

Application Scope

JSP Page Scopes: Page


This scope helps to keep the data available while the page is loading. Any object whose scope is
defined as page scope will disappear as soon as the response is sent to the browser. The object
with a page scope may be modified as often as desired within the particular page but the changes
are lost as soon as the user moves away from the page. By default all beans have page scope.
JSP Page Scopes: Request
Any object created in the request scope will be available as long as the request object is valid. For
example if the JSP page uses a <jsp:forward> tag, then the bean will be accessed in the
forwarded page and if redirect is used then the bean is destroyed.
JSP Page Scopes: Session
In JSP terms, the data associated with the user has session scope. A session does not correspond
directly to the user; rather, it corresponds with a particular period of time the user spends at a site.
Typically, this period is defined as all the hits a user makes to a website between starting and
exiting his browser.
JSP Page Scopes: Application
The bean associated with the application scope will be accessible to all the users and all the pages
in the application.

Try It Out
Problem Statement:

Write a web application that has an index page, which takes username from the user.
If submitted, it has to call a servlet, which then calls another jsp. This jsp has to print
the username attached with the request.

System should retrieve the contact email configured as an init param for whole of the
application:

Page 21
Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected

Handout - JSP
Code:
<HTML>
<HEAD>
<TITLE>Page Scopes Example</TITLE>
</HEAD>
<BODY>
<FORM action=[Link] method=POST>
Username:<INPUT type=text name=username>
Password:<INPUT type=text name=password>
<INPUT type=submit value=go!>
</FORM>
</BODY>
</HTML>

<html>
<head>
<title>Index Page</title>
</head>
<body>
<h2><%= [Link]("userName") %></h2>
<jsp:useBean id="name" class="[Link]" scope="request" />
<jsp:useBean id="name" class="[Link]" scope="session" />
<jsp:useBean id="name" class="[Link]" scope="application"
/>
</body>
</html>
How It Works:

The [Link] calls the servlet mapped for the [Link] call. The servlet sets the
username as an attribute to the scopes request, session and application.

It then forwards the request to the [Link]. It then prints the values from the different
scopes.

Summary

Request: An instance of HttpServletRequest

Response: An instance of HttpServletResponse

Out: An instance of JspWriter

session: An instance of HttpSession

Config: An instance of ServletConfig

Application: An instance of ServletContext

Page: An instance of object

pageContext: An instance of PageContext

Exception: An instance of Throwable.

Page 22
Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected

Handout - JSP
Test your Understanding
1. What do you understand by JSP Page Scopes?

Page 23
Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected

Handout - JSP

Session 18: JSP Static and Dynamic Inclusions


Learning Objectives
After completing this session, you will be able to:

Explain JSP Static and Dynamic Inclusions

Static Inclusions
It can be done using the "include" directive.
<% @include file="[Link]" %>

Dynamic Inclusions
It can be done using the <jsp: include> action tag
<jsp:include page="[Link]" />
Example:
<% @include file="[Link]" %>
< jsp:include page="[Link]"/>

Try It Out
Problem Statement:
Write an index page that includes a header page and a proverb page. The proverb page follows
the header and it displays a proverb, which changes every one hour. The header contains the
name and a logo.
The page should be able to display the header as well as the dynamic proverb page
Code:
<%@ include file="/[Link]" %>
Proverb: <jsp:include page=/[Link] " />
<br>
<br>
<h1>Static and Dynamic Includes</h1>

<h1>Index pages Header</h1>


<img src=[Link]>
<b>An apple a day keeps the doctor away</b>
How It Works:

Start Tomcat server. Open a browser and type the [Link] page

Now change the [Link] to contain some other proverb.

Now do step 1 and see that the new proverb is getting displayed in the index page.

Page 24
Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected

Handout - JSP
Summary

This session gives an overview of JSP static and dynamic inclusions.

If any of the contents in the jsp page is dynamic, use dynamic includes. In other
conditions static includes helps improve systems performance.

Test your Understanding


1. What are JSP static and dynamic inclusions?

Page 25
Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected

Handout - JSP

Session 21: Java Beans with JSP Scriptlets


Learning Objectives
After completing this session, you will be able to:

Explain Java Beans

JavaBeans

JavaBeans components are Java classes that can be easily reused and composed
together into applications.

Any Java class that follows certain design conventions can be a JavaBeans
component.

JavaServer Pages technology directly supports using JavaBeans components with


JSP language elements.

You can easily create and initialize beans and get and set the values of their
properties.

JavaBeans Component Design Conventions:


JavaBeans component design conventions govern the properties of the class and govern the
public methods that give access to the properties.

JavaBeans Component property:


A JavaBeans component property can be:

Read/write, read-only, or write-only.

Simple, which means it contains a single value, or indexed, which means it represents
an array of values..

For each readable property, the bean must have a method of the form:

PropertyClass getProperty() { ... }

For each writable property, the bean must have a method of the form:

setProperty(PropertyClass pc) { ... }

Syntax:
One of the ways to set JavaBeans component properties in a JSP page is using a scriptlet.
<% [Link](value); %>
Retrieving JavaBeans Component Properties:
<% Object o = [Link](); %>
Example:
<% [Link](bookId); %>
<%

int num = [Link]();

%>

Page 26
Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected

Handout - JSP
Try It Out
Problem Statement:
Create a jsp named [Link] and a bean class named [Link] with accessor methods
for name and [Link] the instance variables of the bean class and then get the variables from the
stored request attributes and display in the browser.
Code:
public class Student{
String id = "";
String name = "";
public void setId(String id) {
[Link] = id;
}
public String getId() { return id; }
public void setName(String name) {
[Link] = name;
}
public String getName() {
return name;
}

<%@page import="[Link]" %>


<html>
<head>
<title>Acessing Bean Class Using Scriplet</title>
</head>
<body>
<% Student student=new Student();
[Link]("John");
[Link]("22"); %>
<h1>The Name and Id of the Students are<br></h1>
<h2>Name :
<% [Link]([Link]());
%><br>
Id :
<% [Link]([Link]()); %>
</h2>
</body>
</html>
How It Works:
The values for the instance variables are set and stored in the request attribute and the stored
request attributes are later retrieved using scriptlet and then displayed

Page 27
Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected

Handout - JSP
Summary

JavaBeans components are Java classes that can be easily reused and composed
together into applications.

Any Java class that follows certain design conventions can be a JavaBeans
component.

JavaServer Pages technology directly supports using JavaBeans components with


JSP language elements.

You can easily create and initialize beans and get and set the values of their
properties.

Test your Understanding


1. What is a JSP Bean Class?
2. How can you access Bean class from JSP using scriplet?

Page 28
Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected

Handout - JSP

Session 22: Java Beans with JSP Actions


Learning Objectives
After completing this session, you will be able to:

Access Java Beans using JSP actions

Java Beans and JSP

JavaServer Pages technology directly supports using JavaBeans components with


JSP language elements.

You can easily create and initialize beans and set the values of their properties.

Creating and Using a JavaBeans Component:


JSP page will use a JavaBeans component, using either one of the following formats:
<jsp:useBean id="beanName" class="fully_qualified_classname" scope="scope"/>
or
<jsp:useBean id="beanName" class="fully_qualified_classname" scope="scope">
<jsp:setProperty .../> </jsp:useBean>.

Setting JavaBeans Component Properties:


Syntax:
<jsp:setProperty name=" beanName " property=" propName "/>
<jsp:setProperty name="bookDB" property="bookId"/>

Retrieving JavaBeans Component Properties:


Syntax:
<jsp:getProperty name="beanName property="propName"/>
<jsp:getProperty name="currency" property="format"/>
Example:
<jsp:setProperty name="bookDB" property="bookId"/>
<jsp:getProperty name="currency" property="format"/>

Try It Out
Problem Statement:
Write a JSP page that demonstrates the usage of JSP Action tags. Also develop a bean class to
be called from the JSP page.
The JSP page should declare a variable of that bean type, set the properties of that bean and in
the end it has to display the properties of that bean:

Page 29
Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected

Handout - JSP
Code:
<html>
<head>
<title>Acessing Bean Class Using JSP Action</title>
</head>
<body>
<jsp:useBean id="student" class="[Link]"/>
<jsp:setProperty name="student" property="name" value="John"/>
<jsp:setProperty name="student" property="id" value="123456"/>
<h1>The Name and Id of the Students are<br></h1>
<h2>Name :
<jsp:getProperty name="student" property="name"/><br>
Id :<jsp:getProperty name="student" property="id"/></h2>
</body>
</html>

package [Link];
public class Student{
String id = "";
String name = "";
public void setId(String id) {
[Link] = id;
}
public String getId() { return id; }
public void setName(String name) {
[Link] = name;
}
public String getName() {
return name;
}
}
How It Works:

The bean has to be compiled and the class file has to be present in the classpath.

Start the Tomcat server. Access the [Link] page from the browser.

The JSP actions aids users develop scripless pages, which is easy in terms of
maintaining and is easily readable.

Summary

JSP technology directly supports using JavaBeans components with JSP language
elements.

You can easily create and initialize beans and set the values of their properties.

Page 30
Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected

Handout - JSP
Test your Understanding
1. What is a JSP Bean Class?
2. How can you access Bean class from JSP using JSP Action?>

Page 31
Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected

Handout - JSP

References

Websites

[Link]
ml

Head First Servlets and JSP

SCWCD Exam Study Kit

Books

Page 32
Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected

Handout - JSP

STUDENT NOTES:

Page 33
Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected

You might also like