Sei sulla pagina 1di 99

JavaTM Education & Technology Services

Developing Web
Applications using Java
Server Pages (JSP)

JavaTM Education & Technology Services


Copyright© Information Technology Institute 1
Table of Contents

• Chapter 1: JSP Basics


• Chapter 2: JSP Syntax
• Chapter 3: JSP and Java Beans

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 2
Chapter 1

JSP Basics

JavaTM Education & Technology Services


Copyright© Information Technology Institute 3
Chapter 1 Outline

‰ What is Java Server Page (JSP)?


‰ What is wrong with servlets?
‰ What is the difference between servlets and JSP?
‰ Advantages
Ad t off JSP
JSP.
‰ How JSP look like?
‰ How JSP works?
‰ javax.servlet.jsp package.
‰ JspPage interface
‰ HttpJspPage Interface
‰ JSP Classes
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 4
What is Java Server Page (JSP) ?

• “An extension of the servlet technology created


to support authoring of HTML and XML pages
pages.“

• What is wrong with servlets ?


– Most Web pages are HTML.
– Every single change will require the involvement of
the servlet programmer.
– No clear separation of presentation and logic.
– Little bit difficult for web programmers.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 5
What is the difference between servlets and
JSP?

• Servlets:
– Are Java programs with embedded HTML
HTML.
– Generate dynamic content.
– Do not separate static and dynamic content
content.
• JavaServer Pages:
– Are HTML pages with embedded Java code or
they can be pure XML.
– Generate dynamic content
content.
– Separate static and dynamic content.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 6
Benefits of JSP

• Easier to author (Web-site development tools).


• Separating the development team responsibilities.
responsibilities
• Business and presentation logic are separated.
• Si lif d
Simplify development
l t with
ith JSP
JSP, JJavaBeans
B and d
custom tags.
• Supports software reuse through the use of
components.
• Recompile automatically when change are made to
the source file.
• Platform independent.
independent
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 7
How JSP look like?

• <HTML> tags stay as they are. When you need to add dynamic
content, all you need to do is enclose your code in <% … %> tags
<%@ page import="java.util.Enumeration" %>
<HTML>
<HEAD><TITLE> Using JSP </TITLE></HEAD>
<BODY BGCOLOR= #DADADA>
<%
Enumeration parameters = request.getParameterNames();
String param = null;
while (parameters.hasMoreElements()) {
param = (String) parameters.nextElement();
out.println(param + ":" + request.getParameter(param) +
"<BR>");}
out.close();
();
%>
</BODY>
</HTML>

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 8
How JSP works ?

J2EE container

Web Yes
First
container 1
time
(p
page
g compiler
p )
Create servlet
http://host/date.jsp date.java
No

Compile servlet
date.class
3
Servlet life cycle

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 9
Example

<HTML> public void _jspService(…..)


<HEAD> {
</HEAD> out.write("<HTML>\r\n");
<BODY> out write("<HEAD>\r\n");
out.write( <HEAD>\r\n );
out.write("</HEAD>\r\n");
out.write("<BODY>\r\n");
<%
% out.println
t i tl ( "JSP iis easy");%>
") % out.println("JSP
t i tl ("JSP iis easy");
")
out.write("\r\n");
out.write("</BODY>\r\n");
</BODY> out.write("</HTML>");
</HTML> }

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 10
Notes on JSP life Cycle

* Source: Core Servlets and Javaserver Pages By Marty Hall, Larry Brown ISBN 0130092290
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 11
Why JSP developers need servlets?

1. JSP pages are translated into servlets.


2 JSP consists
2. i t off static
t ti HTML,
HTML JSP tags,
t and
d
Java code (Servlet code).
3 Some
3. S tasks
t k are better
b tt accomplished
li h d b
by servlets
l t
than by JSP.
4 Combination of servlets and JSP
4. JSP.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 12
javax.servlet.jsp.*

• JSP is involved in two main packages:


– javax.servlet.jsp
– jjavax.servlet.jsp.tagext
j p g Æ custom tags
g - Advanced
• javax.servlet.jsp contains 2 interfaces , 2
Exceptions and 4 classes
• Interfaces :
– JspPage
– HttpJspPage

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 13
javax.servlet.jsp.* (cont’d)

• Classes:
– JspFactory
J F t
– PageContext
– JspEngineInfo
– JspWriter
• Exceptions:
– JspException
– JspError.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 14
JspPage interface

• The JspPage is the interface that must be implemented


byy all JSP servlet classes.
• It contains two methods:
– public void jspInit()
– p
public void jjspDestroy()
p y()

Example:
<% ! Æ(Note it is <%! JSP Declaration Not <%)
public void jspInit() {
System.out.println("Init");
}
public void jspDestroy() {
System.out.println("Destroy");
}
%>

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 15
HttpJspPage Interface

• It extends the JspPage interface.

• It has got only one method :


– public void _jspService ( HttpServletRequest
request,HttpServletResponse response ) throws
ServletException, IOException.

• It’s called by the JSP container, to generate the content


of the JSP page.

• you can't include this method in a JSP page, because


the page content itself represents this method
method.
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 16
JSP Classes

• The JspFactory class


• The JspEngineInfo class
• The PageContext class Æ “Implicit
Implicit objects
objects”
• The JspWriter class

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 17
1-The JspFactory Class
• A
An abstract
b t t class
l that
th t provides
id methods
th d ffor obtaining
bt i i
other objects needed for the JSP page processing.

• The class has the static method getDefaultFactory that


returns a JspFactory object.

• From the JspFactory object, a PageContext and a


JspEngineInfo object can be obtained using:

– public abstract JspEngineInfo getEngineInfo( )

– public
bli abstract
b t tP PageContext
C t t getPageContext
tP C t t (Servlet
(S l t
requestingServlet, ServletRequest request,
ServletResponse response, String errorPageURL,
boolean needsSession
needsSession, int buffer
buffer, boolean autoFlush)
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 18
The JspFactory Class (cont.)

• The following
g code is p
part of the _ jjspService
p
method that is generated by the JSP container:

JspFactory _jspxFactory
jspxFactory = null;
PageContext pageContext = null;

_jspxFactory =JspFactory.getDefaultFactory();
pageContext = _jspxFactory.getPageContext ( this,
request,
response,"",
""
true, 8192,
true);

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 19
2-The JspEngineInfo Class

– The JspEngineInfo class is an abstract class


that provides information on the JSP
container.
– It has only one method,
getSpecificationVersion, returns the JSP
container's version number.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 20
3-The PageContext Class

– PageContext represents a class that provides


methods that are implementation-dependent.
implementation dependent.

– The PageContext class itself is abstract


abstract, so in
the _ jspService method of a JSP servlet
class, a PageContext object is obtained by
calling the getPageContext method of the
JspFactory class.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 21
The PageContext Class (cont.)

– The PageContext class provides methods that


are used to create other objects.
j
• getOut method returns a JspWriter object that is
used to send strings to the web browser.
• getRequest,
tR t returns
t a ServletRequest
S l tR t object.
bj t
• getResponse, returns a ServletResponse object.
• getServletConfig,
getServletConfig returns a ServletConfig object.
object
• getServletContext, returns a ServletContext object.
• getSess
getSession,
o , returns
etu s aan HttpSession
ttpSess o object
object.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 22
4-The JspWriter Class

• The JspWriter class is derived from the


java.io.Writer class and represents a Writer that
you can use to write to the client browser.

• Of its many methods, the most important are the


print and println methods.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 23
Implicit Objects of PageContext class

• request Æ javax.servlet.http.HttpServletRequest
• response Æ javax.servlet.http.HttpServletResponse
• out Æ javax.servlet.jsp.JspWriter
javax servlet jsp JspWriter
• session Æ javax.servlet.http.HttpSession
• application Æ javax.servlet.ServletContext
javax servlet ServletContext
• config Æ javax.servlet.ServletConfig

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 24
Review

• Revisiting the generated Servlet out of a JSP


file
• If the code written in the JSP p
page
g was onlyy:
<%
out.println("JSP is easy");
%>

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 25
Strategies for invoking dynamic code
1 Call
1. C ll JJava code
d di
directly
tl (S
(Scriptlets)
i tl t ) Simple

2 Develop separate utility classes


2. classes, Insert into JSP page
only the Java code needed to invoke the utility classes.

3. Develop separate utility classes structured as beans.

4. MVC architecture. A servlet respond to original request,


look up data, and store results in beans, forward to a
JSP page to present results, JSP page uses beans.
Complex
1. Use the JSP expression language. Advanced
2. Use custom tags.
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 26
Strategies for invoking dynamic code (cont’)

• Why limiting the amount of Java code in JSP


pages ?
– Development.
– Compilation.
– Debugging.
– Division of labor.
– Testing.
– Reuse.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 27
Lab Exercise

JavaTM Education & Technology Services


Copyright© Information Technology Institute 28
Assignments

• Make a simple JSP displaying the time.


• Make an html page that redirect a request to an
JSP

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 29
Chapter 2

JSP Syntax

JavaTM Education & Technology Services


Copyright© Information Technology Institute 30
Chapter 2 Outline

‰ JSP tags :
‰ Directive elements
‰ Scripting elements
‰ Action elements
‰ Converting into XML syntax

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 31
JSP Syntax

• JSP contains 2 main things :


– JSP tags/
t / JSP elements
l t : make
k up the
th syntax
t andd
semantics of JSP.
– Template Data : anything else ,not understood by
the JSP container
• example :HTML tags
• JSP tags are :
– Directive elements
– Scripting
S i ti elements
l t
– Action elements

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 32
JSP tags

JSP tags

Directive Scripting Action

page Scriptlets

include Declarations

taglib Expressions

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 33
1-Directive Elements

• They are messages to the JSP container


containing information on how the JSP container
must translate a JSP page into a corresponding
servlet.
• They are actually instructions to the container
not a code.
• Directives Types :
– Page directives
– Include directives
– Tag library directives (used with custom tags )

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 34
1-Directive Elements (cont’d)

• Directive element Syntax


– <%@ directive (attribute="value")* %>
• Example
– <%@ page buffer="16384" session="false" %>
– <%@ include file=“footer.html" %>
– <%@ talib uri=“….” prefix =“c”%> Æ Advanced

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 35
1-Directive Elements (cont’d)
a-Page Directive Attributes
Atribute Value Type Default
import Fully qualified class name None
"text/html;charset=ISO-
contentType MIME type, character set
8859-1”
session Boolean “true”
buffer Buffer size in Kb or false 8192
autoFlush Boolean "true”
info String Depends on the container
errorPage URL None
isErrorPage Boolean "false”
isThreadSafe Boolean "true”
extends Class name None
g g
language Scripting
p g language
g g name "java"
j

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 36
1-Directive Elements (cont’d)
a-Page Directive Attributes

• Examples
– <%@ page import="java.util.Enumeration" %>
– <%@
@ppage
g session="false" %>
– <%@ page buffer="16384" %>
– <%@ page autoFlush="false" %>
– <%@ page errorPage="ErrorPage.jsp" %>
• It’s not allowed to repeat assigned attributes
exceptt for
f import
i t attribute
tt ib t

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 37
1-Directive Elements (cont’d)
a-Page Directive Attributes

Notes on import attribute


• 1st and 2nd strategy for invoking dynamic code.
• Utility classes should always be in packages and the JSP
page should use the import attribute.
• By default
default, the generated servlet imports java.lang.*,
java lang *
javax.servlet.*, javax.servlet.jsp.*, javax.servlet.http.*.
• The onlyy ppage
g attribute that is allowed to appear
pp multiple
p
times.
• The utility classes should be placed in /WEB-NF/classes/
• Note:
<%@ page import="package.class1,...,package.classN" %>

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 38
1-Directive Elements (cont’d)
b-The Include Directive

• It enables JSP page authors to include the


contents of other files in the current JSP page.
• We can include static page like html or another
JSP page.
p g
• Include Syntax:
– <%@
@ include file="relativeURL" %>
• Example:
– <%@
@ include file=“header.html" %>

• Note the g
generated servlet’s code.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 39
2-Scripting Elements

• It allows you to insert Java code in your JSP


pages.
• 1st and 2nd strategy
gy for invoking
g dynamic
y code.
• There are three types:
– Scriptlets
p
– Declarations
– Expressions

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 40
2-Scripting Elements (cont’d)
a-Scriptlets

• Inserted into the servlet’s _jspService method

• Syntax
<% //// put here your java code //// %>

l :
• Example
E
<%
out.println("Current
t i tl ("C t Time:
Ti " + getSystemTime())
tS t Ti ()) ;
%>

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 41
2-Scripting Elements (cont’d)
b-Declarations
• IIt’s
’ usedd to d
declare
l methods
h d or variables.
i bl
• Inserted into the body of the servlet class, outside
any existing
i ti methods.
th d
• Can not access the implict objects of _jspService
method
• Syntax:
<%! //// put your code here //// %>
• Examples:
<%! String getSystemTime() {
return Calendar.getInstance().getTime().toString();
}%>
}%
<%! int x; %>
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 42
2-Scripting Elements (cont’d)
c-Expressions

• It’s used to evaluate expressions and print them


to the user.
• It’s used instead of out.println()

• Syntax:
<%=
% put the variable here %>
%
• Example:
<%=
% java.util.Calendar.getInstance().getTime() % %>
The same result of :
out.print( java.util.Calendar.getInstance().getTime() );

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 43
Assignment

• Write a utility class that generates a random


number within a given range
range.
• Invoke methods of this utility class from jsp page
using scripting elements
elements.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 44
3-Standard Action Elements

They consists of :
• jsp:include
• jsp:forward
• jsp:param
• jsp:plugin
• jsp:params
• jsp:fallback
• jsp:useBean
• jsp:setProperty
• jsp:getProperty

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 45
3-Standard Action Elements(cont’)
Include, forward and param

• They got the same effect of RequestDispatcher


include and forward
• Syntax:
<jsp:include page
page="relativeURL“>
relativeURL >
( <jsp:param . . . /> )*
</jsp:include>
j p

<jsp:forward page="relativeURL">
( <jsp:param . . . /> )*
</ jsp:forward >

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 46
3-Standard Action Elements(cont’)
Include, forward and param
Notes on jsp:include
• The included pages can be
- HTML files,
fil plain
l i text
t t files,
fil JSP pages, S
Servlets
l t
- With JSP pages and servlets, only the output of the page
is included, not the actual code.
• Do not use complete HTML documents for the included
pages.
• The included page uses the same request object as the
originally requested page and sees the same request
parameters.
• The main page can add to or replace the request
parameters using jsp:param.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 47
3-Standard Action Elements(cont’)
Include, forward and param
Notes on jsp:forward
• Using jsp:forward obtain the complete output from the
destination page
page.
• The main page must not have any output.
• The main page can add to or replace the request
parameters using jsp:param.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 48
jsp:include vs. include directive
<j i l d page=““ urll “ />
<jsp:include <%@ iinclude
l d file=“
fil “ urll “%>

• Insert JSP code into the


• Include
I l d ththe output
t t off
main page before that
a page at request time
main page is translated
into a servlet.

• The main page must be


• No change needed in
updated whenever any of
the main page when the
the included p
pages
g
included pages change
change.
change.

• The included code can


•The included p
pages
g
contain JSP constructs
cannot use any JSP
such as field definitions
constructs that affect the
and content-type settings
main page as a whole.
that affect the main page
as a whole.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 49
Assignment

• Use both jsp:include and include directive to


include header to your jsp and Note the
difference.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 50
3-Standard Action Elements(cont.)
Plugin, Fallback and params

• Sun developed a browser plug-in for Netscape and


Internet Explorer that lets you use the Java 2 platform in
a variety
i t off browser
b versions.
i
• In some browsers, the normal APPLET tag will not work
with the plug-in.
plug in. Instead, use OBJECT tag for Internet
Explorer and EMBED tag for Netscape.
• The <jsp: plugin> is used to generate HTML <OBJECT>
or <EMBED>
EMBED tags t that
th t instruct
i t t theth browser
b to
t download
d l d
the Java Plugin software, if required, and initiate the
execution of the Java applet
pp specified.
p
• Note: The applet .class files must not be placed in WEB-
INF/classes, as the browser, not the server, uses them.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 51
3-Standard Action Elements(cont.)
Plugin, Fallback and params

<APPLET CODE="MyApplet.class” WIDTH=475 HEIGHT=350>


<PARAM NAME="PARAM1" VALUE="VALUE1">
</APPLET>

< jsp:plugin type=


type="applet”
applet code=
code="MyApplet
MyApplet.class
class” width=
width="475"
475 height=
height="350">
350 >
<jsp:params>
<jsp:param name="PARAM1" value="VALUE1" />
</jsp:params>
</jsp:plugin>

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 52
3-Standard Action Elements(cont.)
useBean, setProperty and getProperty

• Used to contact a bean


– Will be described in details in the next chapter

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 53
Comment tag

• HTML comments
<!-- HTML Comment -->
<! >

• JSP comment
<%-- JSP Comment --%>

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 54
Assignment

• Use <jsp: plugin> to embed Applet in your jsp


page.
g

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 55
Converting into XML syntax

• Benefits:
– The content of the JSP page can be validated against
a set of descriptions.
– The JSP page can be manipulated using an XML
tool.
– The JSP page can be generated from a textual
representation by applying an XML transformation

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 56
Converting into XML syntax (cont’d)

• Syntax
– <jsp:directive.directiveName attribute_list />
– <jsp:declaration>
j d l ti d l ti code
declaration d </jsp:declaration>
/j d l ti
– <jsp:scriptlet> scriptlet code </jsp:scriptlet>
– <jsp:expression>
jsp:expression expression </jsp:expression>
/jsp:expression
• Examples:
<jsp:directive.page
j p p g attr=“value” />
<jsp:scriptlet> String s; s =
request.getParameter("user"); </jsp:scriptlet>
<jsp:text>
<jsp:text>…….</jsp:text>
</jsp:text>

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 57
Converting into XML syntax (cont’d)

• Notes on XML Syntax:


– XML element names can contain colons, XML-
compatible
tibl version
i off allll standard
t d d JSP elements
l t
starts with the jsp prefix (or namespace).

– XML tags are case sensitive.

– XML tags must be explicitly closed.

– To get ' within an attribute value, use \‘.


To get ", use \“; to get \, use \\; to get %>, use %\>;
and to get <%,
<% use <\%<\%.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 58
Chapter 3

JSP and Java Beans

JavaTM Education & Technology Services


Copyright© Information Technology Institute 59
Chapter 3 Outline

‰ What is a Bean?
‰ <useBean> Tag Structure.
Structure
‰ How to use a request parameter to feed the value of a
bean variable ?

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 60
What is a Bean?

• A bean is a java class with certain rules defined


by the JavaBeans specification.

• Beans extend no particular class and use no


particular interface.

• The 3rd strategy for invoking dynamic code.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 61
Why beans?

• Why we should use beans in JSP ?


– Avoiding spagitti code.
– No Java syntax, instead XML-compatible tags.
– Clear separation of roles.
– Simpler object sharing.
– Convenient correspondence between request
parameters
t and
d object
bj t properties.
ti

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 62
Java Beans Rules

• A bean class must have a default constructor


((which will be called when JSP elements or
servlets create beans).

• A bean class should have no public instance


variables.

• Persistent values (properties) should be


accessed through methods called getXxx and
setXxx.
Or isXxx and setXxx for bolean properties.
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 63
Java Beans Rules (cont’)

• Example:
- If yyour Book bean class has a long
g instance variable
isbn and a boolean borrowed.
- Then your bean class should have the following
methods to make isbn and borrowed accessible by the
standard JSP actions:

long getIsbn ()
void setIsbn (long isbn)
boolean isBorrowed ()
void setBorrowed (boolean borrowed)

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 64
Java Beans Rules (cont’)

• Notes on Bean classes :

– Place all your beans in packages.

– Install them in the normal Java code directories:


WEB-INF/classes/ for individual classes and
WEB-INF/lib for JAR files.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 65
<useBean> Tag Structure
• < jsp:useBean
j B ((attribute="value")+
ib " l ") /> /
• Main attributes :
– id
– class
– scope (page
(page, request,
request session,
session application)
• Example:
<jsp:useBean id=
id=“beanName"
beanName" scope="session"
class=" com.mybeans.MyFirstBean"/>

• This element can either build a new bean or


access a preexisting one in the specified scope
scope.
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 66
<useBean> Tag Structure (cont’)

• You must use the fully qualified class name for


the class attribute regardless of whether you use
<%@ page import... %> to import packages.

<jsp:useBean id=“bookBean“
class=" com.mybeans.MyBookBean"/>

<% com.mybeans.MyBookBean bookBean = new


com.mybeans.MyBookBean(); %>

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 67
<getProperty> & <setProperty> Tags
Structure

• Accessing Properties in a bean through :


– jsp:getProperty
– jsp:setProperty
Syntax:
<jsp:getProperty name=" beanName "
property="propertyName"/>

• This element reads and outputs the value of a


bean property.
• Reading a property means calling its getXxx
method.
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 68
<getProperty> & <setProperty> Tags
Structure (cont’)

<jsp:setProperty
jsp:setProperty name
name=" beanName "
property=“propertyName" value="value"/>

• This element modifies a bean property (i.e.,


calls its setXxx method).
method)

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 69
<getProperty> & <setProperty> Tags
Structure (cont’)

• JSP expression could be used to call a method


on the object
j with the variable specified by
y the id
attribute.
<%= bookBean.getIsbn() %>

<jsp:getProperty
j pg p y name=" bookBean "
property=“isbn"/>

• It is not advisable but can be useful with loops,


conditional statements, and methods not
represented as properties.
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 70
<getProperty> & <setProperty> Tags
Structure (cont’)

• JSP scriptlet could be used to explicitly call


methods on the bean object.
j
<% bookBean.setIsbn (1234567890); %>

<jsp:setProperty name=" bookBean"


property=“isbn"
p p y value=“1234567890"/>

• It is not advisable but can be useful in setting


g the
value conditionally or calling methods other than
getXxx or setXxx on the object.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 71
Example
package com.mybeans;
com mybeans;
public class MyFirstBean {
private String firstName;
public String getFirstName()
{
return firstName;
}
public void setFirstName(String name)
{
firstName name
firstName=name;
} }
Note:In beans terminology the class is said to have a String
property called firstName.
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 72
Example (cont.)

<jsp:useBean
jsp:useBean id
id= “myBean”
myBean
class=“com.mybeans.MyFirstBean” />

<jsp:setProperty name= “myBean”


property=“firstName”
p p y value= “Ali” />

The
e First
st Name
a e is
s <jsp:getProperty
jsp get ope ty
name=“myBean” property=“firstName” />

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 73
Example (cont.)

• Note You can access the bean methods using


scripting
g tags
g
<jsp:useBean id= “myBean”
class=“com.mybeans.MyFirstBean” />
<%
% String
St i name = “ Ali ””;
myBean.setFirstName (name);
%>
The First Name is <%= myBean.getFirstName()%>

• Note: Whenever possible, avoid mixing the XML-


compatible jsp:useBean tags with JSP scripting elements
containing
t i i explicit
li it JJava code.
d
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 74
How to use a request parameter to feed the
value of a bean variable ?

Consider this case:

<% int isbn = 1;


tryy {
isbn =
Integer.parseInt(request.getParameter(“isbNum"));
} catch(NumberFormatException nfe) { }
%>
<j
<jsp:setProperty
tP t name=“bookBean”
“b kB ” property=“isbn"
t “i b "
value="<%= isbn %>" />

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 75
How to use a request parameter to feed the
value of a bean variable ? (cont’)
• JSP offers a better solution:
<jsp:setProperty name="BeanName"
property="PropertyName“
property= PropertyName param=
param="parameterName"/>
parameterName />

• For Example:
<jsp:setProperty name=“bookBean” property=" isbn"
param= “isbNum”/>
• isbNum is the name of the request parameter.
• The value of the request parameter isbNum is automatically used as the
value of the bean pproperty
p y isbn.
• Type conversions from String to primitive types (byte, int, double, etc.)
and wrapper classes (Byte, Integer, Double, etc.) are automatically
performed.
p
• If the specified parameter is missing from the request, no action is taken
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 76
How to use a request parameter to feed the
value of a bean variable ? (cont’)

• If the request parameter name and the bean


property name are the same the param attribute
could be omitted
Example:
p
If the request parameter has the name isbn
<jsp:setProperty name=“bookBean” property=" isbn“ />

• To Associate all properties with request


parameters (Form Beans)
<jsp:setProperty name=“bookBean” property=" *“ />

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 77
Scope of the Bean

• page
• request
• session
i
• application

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 78
Scope of the Bean (cont’)

1. page:
– The default value.
– The bean is bound to a local variable (accessible by
this jsp page only)
only).
– The bean object is placed in the PageContext object
for the duration of the current request.
– The code can access it by calling getAttribute on the
predefined pageContext variable of the page.
– The
Th bean
b is
i nott shared
h d and d th
thus a new b
bean will
ill b
be
created for each request.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 79
Scope of the Bean (cont’)

2. request:
– The bean is bound to a local variable
variable.
– The bean object is placed in the HttpServletRequest
object for the duration of the current request.
– The servlet code can access it by calling getAttribute
on the request variable.
– Note
N t that
th t two
t JSP pages or a JSP page and d a servlet
l t
share request objects jsp:include, jsp:forward or the
include or forward methods of RequestDispatcher
q p is
used.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 80
Scope of the Bean (cont’)

3. session:
– The bean is bound to a local variable.
– The bean object will be stored in the HttpSession
object associated with the current request
request.
– The servlet code can access it by calling getAttribute
on the session variable.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 81
Scope of the Bean (cont’)

4. application:
– Th
The bbean iis b
boundd tto a llocall variable.
i bl
– The bean object will be stored in the ServletContext
available through the predefined application variable
or by a call to getServletContext.
– The ServletContext is shared by all servlets and JSP
pages in
i th
the WWebb application.
li ti
– Values in the ServletContext can be retrieved with the
getAttribute method.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 82
Lab Exercise

JavaTM Education & Technology Services


Copyright© Information Technology Institute 83
Assignment

• Write a jsp page that populates a Java bean with


the data from the user and forward to another
jsp page or servlet that displays the data.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 84
Chapter 4

MVC Frameworks

JavaTM Education & Technology Services


Copyright© Information Technology Institute 85
Chapter 4 Outline

‰ MVC Design Pattern.


‰ Why MVC?
‰ MVC Frameworks.
‰ Implementing
I l ti MVC with
ith RequestDispatcher.
R tDi t h

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 86
MVC Design Pattern

• Model-View-Controller (MVC) is an architectural


design pattern used to build complex computer
applications.
• It aims to separate data (model) and user
i t f
interface (view).
( i )
• The MVC architecture divides applications into
th
three layers
l :
• Model: The data and business logic
• View: The presentation and User Interface
• Controller: The flow control

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 87
Why MVC?

• Why MVC?
1 Dividing responsibilities:
1.
• Business logic and presentation are separated.
• y change
Flexibility: g in one layer
y does not affect
the other.

2. Ease of maintenance.

3 Pre and Post Processing (sec


3. (security,
rit logging
logging, etc
etc…))

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 88
MVC Frameworks

• The 4th strategy for invoking dynamic code.


• The original
g request
q is handled by
y a servlet.
• The servlet invokes the business-logic and data-access
code and creates beans to represent the results , decides
which JSP page present those results and forwards the
request to it.

• This servlet is the Controller.


• The beans representing the results are the Model.
• The jsp that presents the results are the View.

• The most popular MVC


C fframework is Apache Struts.
S
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 89
MVC Frameworks (cont’)

1-request
Controller
(Servlet)
2

Client 3
browser

View
Model
5-response (JSP)
4

Servlet Container Database (EIS)

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 90
Steps of Implementing MVC

1. Define beans to represent the data.


2 Use a servlet to handle requests
2. requests.
3. The servlet invokes business logic or data-access code
to obtain the results. The results are placed in the
beans (Populate the beans).
4. Store the bean in the request, session, or servlet
context.
context
5. Forward the request to a JSP page (using forward
method of RequestDispatcher)
6. Extract the data from the beans. The JSP page
accesses beans with jsp:useBean and jsp:getProperty
tags
tags.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 91
Notes on the Steps of Implementing MVC

• The Java beans must have a default constructor since a


servlet or other Java routine (never a JSP page) will
create the beans
beans.

• A controller servlet handles the initial request, it can read


request parameters and request headers.

• The controller servlet can also use the populateBean


method of Jakarta Commons BeanUtils component to
automatically populate a form bean with the request
parameters.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 92
Notes on the Steps of Implementing MVC (cont’)

• Jakarta Commons BeanUtils component performs the


reflection and the type conversion.

• You can download this component from


http://commons apache org/components html
http://commons.apache.org/components.html

• Note that to install and use any external component :


– List the JAR files in your CLASSPATH for development.
– Put the JAR files in the WEB-INF/lib directory of your Web
application for deployment
deployment, .
• To share JAR files across Web applications, put JAR
files in /common/lib.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 93
Example on using BeanUtils component
import org.apache.commons.beanutils.BeanUtils;
public class MyRequestServlet extends HttpServlet
{
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {
PrintWriter out=response.getWriter();
MyBean bean=new MyBean();
t {
try{
BeanUtils.populate (bean, request.getParameterMap());
}catch(Exception e)
{
e.printStackTrace();
}
} }
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 94
Notes on the Steps of Implementing MVC (cont’)

• The Servlet can then call some business logic code,


invoke an Enterprise JavaBeans component, or query a
d t b
database tto d
determine
t i ththe results
lt and
d fill iin th
the value
l
object beans.

• A servlet can store data for JSP pages in three main


places: in the HttpServletRequest, in the HttpSession,
andd iin th
the S
ServletContext.
l tC t t

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 95
Notes on the Steps of Implementing MVC (cont’)
BeanObject
B Obj t bbean = new B BeanObject
Obj t ((...);
)
request.setAttribute ("key", bean );
<jsp:useBean id="key" type=“myPackage.BeanObject"
scope= “request” />

BeanObject bean = new BeanObject (...);


HttpSession session = request.getSession();
session.setAttribute ("key", bean );

<jsp:useBean id="key" type=“myPackage. BeanObject "


scope= “session” />

BeanObject bean = new BeanObject (...);


getServletContext().setAttribute("key", bean );

<jsp:useBean
<jsp seBean id
id="key"
"ke " ttype=“myPackage.
pe “m Package BeanObject "
scope= “application” />
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 96
Notes on the Steps of Implementing MVC (cont’)
• You can place your jsp pages under the WEB-INF
directory to prevent clients from accessing them directly
and only servlets can forward requests to them.

• Using forward method of RequestDispatcher, makes the


client sees the URL of the original servlet, not the URL of
the final JSP page.

• If the destination page uses relative URLs for images or


style
y sheets, it needs to make them relative to the servlet
URL or the server root, not to the destination page’s
actual location.
e.g.
e g <LINK REL=STYLESHEET HREF="/path/my-styles
HREF= /path/my-styles.css
css”
TYPE="text/css">
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 97
Project

• After the user correctly log in to the Application,


a specified home page g is displayed
y according g to
the priviliges of the user.
• Only the managers can add, edit or delete
another employee.
• Implement the MVC architecture and avoid using
direct java code in the jsp pages as much as you
can.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 98
References & Recommended Reading

• Core Servlets and JSP.


• J
Java for
f the
th Web
W b with
ith Servlets,
S l t JSP,JSP and
d EJB.
EJB
• Sun presentations.
• Oracle presentations.
• SCJWD study guide.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 99

Potrebbero piacerti anche