Chapter 8
Using JSP[TM]
Scripting/Page Directive
© 2002, Sun Microsystems, Inc. All rights reserved.
Objectives
• Discuss all the scripting elements:
– Declarations, scriptlets, and expressions.
• Show common directives.
• Examine the implicit objects:
– Discuss different scope in JSP[tm].
• Demo:
– A tax calculator JSP.
• Lab exercise:
– Write a JSP to play a number guess game.
Application Designs
Anatomy of a JSP
• Static template text.
• Dynamic content:
– Scripting elements.
– Directives.
– Standard actions.
– Custom tags. (see detail in chapter 10)
JSP Scripting Elements
• Declarations:
– define variables and methods.
– <%! String destination; %>
• Scriptlets
– JSP code fragments.
– <% destination =
request.getParameter("destination");
%>
• Expressions:
– results of evaluating the expression are
converted to a string.
– <p>Destination: <%= destination %>
Declarations
• Used to define variables, methods.
• Examples:
– Variable declaration:
• <%! String destination; %>
• Results in member variables within the
compiled servlet.
– Method declaration:
• <%! public String getDestination() { return
destination} %>
The scope of the declaration is in a JSP file.
– If the JSP file includes other files within the
include directive, the scope expands to cover the
included files as well.
Scriptlets
• Programming code fragments that
perform tasks beyond the capabilities of
markup languages (HTML).
• <% scriptlet %>
• Everything defined in scriptlet goes to
service() method in JSP servlet.
– Variables declared in scriptlets are local
variables in service() method.
Expressions
• Expressions evaluated during the generation of
a response.
– The result is converted into a string, also
called the output stream.
– Inserted into the servlet's output. i.e.
Results in something like
out.println(expressions)
• Syntax
– <%= destination %>
– Semi-colons are not allowed for expressions.
• Expressions are evaluated in a left-to-right
order.
– <%= count++%> <%=newValue=count %>
Directives
• Directives are messages to the JSP container
and do not produce output into the current
output stream.
• They have a syntax as follows:
– <%@ directive {attr=value}* %>
• Important directives:
– page: Communicate page dependent attributes and
communicate these to the JSP container.
• <%@ page import="java.util.*"%>
– include: Used to include text and or code at JSP
page translation-time.
• <%@ include file="header.html" %>
– Taglib: Indicates a tag library that the JSP
container should interpret.
Purpose of the Page Directives
• Give high-level information about the servlet
that results from the JSP page.
• Control
– Which classes are improted.
• <%@ page import="java.util.*" %>
– What MIME type is generated.
• <%@ page contentType="MIME-Type" %>
– How multithreading is handled.
• <%@ page isThreadSafe="true" %> <%!--
Default --%>
• <%@ page isThreadSafe="false" %>
– What page handles unexpected errors.
• <%@ page errorPage="errorpage.jsp" %>
Implicit Objects
• A JSP page has access to certain implicit
objects that are always available, without
being declared first.
• They are the following:
– request(HttpServletRequest)
– response(HttpServletRepsonse).
– session(HttpSession)
– application(ServletContext).
– pageContext, out(of type JspWriter)
– config(ServletConfig), page, exception.
Different Scope
Application, Session Scope
Client 1
server
Session 1
Session ID 1
Client 2 Session ID 2
Session 2
Client 1
server
application
Client 2
Session, Request, Page Scope
client
request
response request response
Page 1 forward Page 2 Page 3 Page 4
forward
Page scope Page scope Page scope Page scope
request scope
request scope
Session scope
Comments
• Two types of comments in JSP:
– Comments that document what the JSP is
doing.
• <%-- this is a comment ... --%>
• <% /** this is a comment ... **/ %>
– Comments that are send as a response to
users.
• <!-- comments ... -->
• <!-- comments <%=expression %> more
comments ... -->
Tax Calculator JSP
<%@ page import = "java.util.*" %>
<%! public double salestax = 0; %>
Directive
<%! public int value = 0; %>
<%! public double cost = 0; %>
<%! public String z; %>
<%! boolean valuessubmitted; %>
<%--HTML to generate a table --%>
<FORM METHOD="GET">...
</FORM>
<% if (valuessubmitted==true) {
String price = request.getParameter("price");
String tax = request.getParameter("tax");
Scriptlet Integer x = Integer.valueOf(price);
Double y = Double.valueOf(tax);
value = x.intValue();
salestax = y.doubleValue(); Implicit
salestax = salestax/100; Object
cost = (value + (value * salestax));
int one = ((int)(cost * 10)) % 10;
int two = ((int)(cost * 100)) % 10;
String result = new String((int)cost + "." + one + two);
%>
The cost of the product, with sales tax, is: <%= result %>
<% } else {
valuessubmitted=true;
Expression
} %>
Demo
Summary
• Showed JSP scripting elements and
directives.
• Discussed various scope in JSP.
• Overuse of scripting code can make
JSP confusing and hard to debug and
maintain.
• Guidelines:
– Use scripting code only when a JSP
requires limited scripting.
– Use it only when component functionality
is unavailable.
Chapter 9
Developing JavaBeans[TM]
Component
© 2002, Sun Microsystems, Inc. All rights reserved.
Objectives
• Show JSP[tm] standard tag actions.
• Demonstrate
– How to use JSP and JavaBeans[tm] component.
– How to develop JavaBeans component.
– How to share data between JSP pages and
servlets.
– The difference between include directive and
include action.
• Demo:
– Counter bean and Mortgage calculator demo.
• Lab exercise:
– Write a form bean and JSP to process a form.
Application Designs
Anatomy of a JSP
• Static template text
• Dynamic content
– Directives
– Scripting elements
– Standard actions
– Custom tags
JSP Standard Actions
• Actions are used to access Java objects
from the JSP™ page.
• The syntax for action elements is based on
XML.
• Example of JSP standard tags:
– <jsp:useBean id="clock"
class=“calendar.JspCalendar” />
– <jsp:getProperty name=“customer” property=“name”
/>
– <jsp:setProperty name=“customer” property=“name”
param=“username” />
– <jsp:include page=“/templates/copyright.html” />
– <jsp:forward page=“/displayPage.html” />
– <jsp:plugin type="applet"
code="codecamp.applet.TestApplet.class"
width="475" height="350" />
What are JavaBeans?
• JavaBeans is a portable, platform-independent
components model written in Java for creating
reusable components.
• JavaServer Pages use action tags to access, modify
and create server-side objects (such as
JavaBeans).
• JavaBeans conventions:
– JavaBeans must have a zero-argument (empty)
constructor.
– Should have no public instance variables (fields).
– Persistent values should be accessed through
methods called getXxx and setXxx.
– The default scope of JavaBeans is "page".
Standard Action Tags Using
JavaBeans Component
• Format of jsp:useBean standard tag:
– <jsp:useBean id="clock"
class=“calendar.JspCalendar” />
– Equivalent to <%calendar.JspCalendar clock=
new calendar.JspCalendar();%>
• The tag specifies how to find or create a bean.
– If an existing bean is to be accessed, it is
either retrieved from the session or the
request context. Bean stores where other
servlets/JSP pages can find it.
– If a bean needs to be created, it is instantiated
without explicit Java programming.
Standard Action Tags Using
JavaBeans Component (Cont.)
• Accessing Bean properties:
– Format <jsp:getProperty name=“customer”
property=“name” />
– Equivalent to <%=customer.getName() %>
– Accessing a bean object via a tag without explicit
Java programming language. (i.e. Calls to
getXxx() methods.)
• Setting Bean Properties:
– Format <jsp:setProperty name=“customer”
property=“name” param=“username” />
– Equivalent to <%=customer.setName("username")
%>
– Setting a bean properties via a tag without
explicit Java programming language. (i.e. Calls to
setXxx methods.)
Counter JSP Sample
<%@ page import="component.CounterBean" %>
<jsp:useBean id="session_counter"
class="component.CounterBean" scope="session" />
<jsp:useBean id="app_counter" class="component.CounterBean"
scope="application" />
<% session_counter.increaseCount();
synchronized(page) {
app_counter.increaseCount();
}
%>
<h3>
Number of accesses within this session:
<jsp:getProperty name="session_counter" property="count" />
</h3><p><h3>
Total number of accesses:
<% synchronized(page) { %>
<jsp:getProperty name="app_counter" property="count" />
<% } %>
</h3>
Counter Bean Sample
package component;
public class CounterBean {
private int count;
//use default constructor.
public int getCount() {
return count;
}
public void increaseCount() {
count++;
}
}
Counter Bean Demo
Associate Bean Properties with
Request Form Parameters
• If the property is a String, can do:
– <jsp:setProperty...value='<%request.getPara
meter("...")%>' />
• The parameters for a form based page
indicates:
– Value should come from specified request.
– Simple automatic type conversion performed.
• Using "*" for the property attribute
indicates:
– Value should come from request parameter
whose name matches property name.
– <jsp:setProperty name="pay"
property="*" />
• If the JavaBean scope is defined as
Mortgage Calculator JSP Sample
<%@ page import="loancalc.PaymentBean" %>
<jsp:useBean id="pay" scope="page"
class="loancalc.PaymentBean" />
<jsp:setProperty name="pay" property="*" />
//html form data
<FORM METHOD="GET">...</FORM>
<%
if ( pay.getPrincipal() !=0 && pay.getInterestRate() !=0 &&
pay.getTerm() !=0 ) {
%>
Your monthly payment is: <jsp:getProperty name="pay"
property="payment"/>
<% } else { %>
You must enter values for the loan, interest rate, and term.
<% } %>
Payment JavaBean Sample
package loancalc;
public class PaymentBean {
private int principal;
private int term;
private double interestRate; //it is case sensitive.
private boolean success;
public PaymentBean() {
reset();
}
public int getPrincipal() {
return principal;
}
public void setPrincipal(int p) {
principal = p;
}
public int getTerm() {
return term;
}
public void setTerm(int t) {
term = t;
}
Payment JavaBean Sample (Cont.)
public double getInterestRate() {
//getInterestrate() WON'T work!
return interestRate;
}
public void setInterestRate(double i) {
interestRate = i;
}
public String getPayment() {
double duration = 12*term;
double r = 1.0 + (interestRate/12) / 100.0;
double denom = 1.0 - Math.pow( 1.0 / r, duration );
double monthlyRate = principal * (r - 1.0) / denom;
success=true;
return toThreeDecimalPlaces(monthlyRate);
}
public boolean getSuccess() {
return success;
}
public void reset() {
principal=0;
term=0;
interestRate=0;
success=false;
}
Mortgage Calculator Demo
Storing Data in Request
• Store data that servlet looked up and
that JSP will use in this request.
• Sevlet: store data.
BeanClass value = new BeanClass(..);
request.setAtrribute("bean", value);
• JSP: retrieve data.
<jsp:useBean
id = "bean"
class="BeanClass"
scope="request" />
Storing Data in Session
• Store data that servlet looked up and
that JSP will use in this request and in
later requests from the same client.
• Sevlet: store data.
BeanClass value = new BeanClass(..);
HttpSession
session=request.getSession(true);
session.setAttribute("bean", value);
• JSP: retrieve data.
<jsp:useBean
id = "bean"
class="BeanClass"
scope="session" />
Storing Data in Servlet Context
• Store data that servlet looked up and
that JSP will use in this request and in
later requests from the any client.
• Sevlet: store data.
BeanClass value = mew BeanClass(..);
getServletContext()
.setAttribute("bean", value);
• JSP: retrieve data.
<jsp:useBean
id = "bean"
class="BeanClass"
scope="application" />
Other Standard Action Tags
• <jsp:forward>
– Forwards request to HTML page, JSP, or
servlet
– <jsp:forward page="relativeUrl" />
• <jsp:include>
– Includes output or response from another
file into this current JSP page.
– <jsp:include page="relativeUrl"
flush="true" />
• <jsp:plugin>
– Downloads Java plugin to browser to
execute applet or bean.
Including Pages at Translation
Time
• <%@ include file ="Relative URL" %>
• The include directive includes the content of this
specified page into main where JSP content
affects main page.
– However, servers are not required to detect
changes to the included file, you need to force
main JSP file to change whenever the included
file changes.
– Can use Unix "touch" command to enforce
change, or
• <%--Navbar.jsp modified 3/1/00 --%>
<%@ include file="Navbar.jsp" %>
• Use include directive if the file changes rarely.
It is faster than include action.
Including Pages at Request Time
• <jsp:include page ="Relative URL" flush="true"
/>
• JSP content cannot affect main page, only
output of included JSP page is used.
– This permits updates to the included content
without changing the main page(s).
– Not permitted to specify false for the flush
for JSP1.1, but it is fixed in JSP1.2.
• Use the include action only for content that
changes often, and if which page to include
cannot be decided until the main page is
requested.
Summary
• Demonstrated how to use JavaBeans
component in JSP pages.
• Examined the difference between
include directive and include action.
• Discussed how to share data between
JSP pages and servlets by using
JavaBeans.