21/07/2009
Java Server Pages
[Link]
JSP Basics
JSP
Java Server Page (JSP) is a server side script language Saved with .jsp extension A simple, yet powerful Java technology for creating and maintaining dynamic-content webs pages JSP page are converted by the web container into a Servlet instance It focus on the presentation logic of the web application
Architecture of JSP
JSP Expression
Scriptlet
Includes expression in a scripting language page
Refers to code blocks executed for every request.
21/07/2009
Declarations
Comments
Defines the variables and methods for a JSP page
Explains the functioning of the code Comments are ignored by the servlet during compilation Syntax
... <!- HTML comments --> ... ... <%-- JSP comments --%> ... ... <% /*Scripting languages comments*/ %> ...
Directives
Directives Contd
Controls the structure of the servlet by sending messages from the JSP page to the JSP container. Specify the scripting language to used. Denote the use of custom tag library in a JSP page. Be used to include the content of another JSP page. Syntax
Specifies the JSP directive
The types of JSP directives are:
page - Associates the attributes that affect the entire JSP page include - Sends message to the JSP container to include the contents of one file into another taglib - Enables the use of custom tags in the JSP page
... <%directivename attribute = value%> ...
Refers to the directive attribute
9 10
page Directive
include Directive
11
12
21/07/2009
taglib Directive
Standard Actions
Tags affecting the behavior of JSP at runtime and the response sent back to web browser Syntax:
... <jsp: standard action> ...
Standard Action
<jsp: useBean> <jsp: param> <jsp: include> <jsp: forward> <jsp: plugin>
13
Description
Accesses the functions of custom tags Provides name and value to the parameters used by the JSP page Includes the output from one file into the other files Transfers control from a JSP page to another Uses a plugin to execute an applet or bean
14
Implicit Objects
Are loaded by the Web Container automatically and maintains them in a JSP page The names of the implicit objects are reserved words of JSP Access dynamic content using JavaBeans
JSP Implicit Object
Types of implicit objects
15 16
Implicit Objects (cont)
Object Class / Interface
The request Object
Represents the request from the client for a Web page Controls information associated with a request from client Includes the source, URL, headers, cookies and parameters
page config request response out session application pageContext exception
[Link] [Link] [Link] [Link] [Link] [Link] [Link] [Link] [Link]
17
18
21/07/2009
The response Object
Manages the response generated by JSP container and sends response to the client Is passed as a parameter to JSP _jspService() method
The out Object
Represents the output stream, then it will be sent to the client as a response for the request Is has page scope
19
20
The session Object
Provides all the objects available in the JSP pages within the session
The application Object
Is used to share the data between all application pages Can be accessed by any JSP present in the application
21
22
The pageContext Obbject (1)
Provides methods to access all attributes defined by implicit objects in the page. Provides methods to transfer control from one web page to another
The pageContext Obbject (2)
Find the scope or specify the scope
o setAttribute() o getAttribute() o getAttributeNamesInScope() o removeAttribute()
23
24
21/07/2009
Servlet Object (1)
Servlet Object (2)
The config Object: oStores the information of the servlet oRepresents the configuration of the servlet data where a JSP page is compiled oIt has page scope
The page object: is an instance of the servlet processing the current request in a JSP page.
25
26
The exception Object
Error handling
[Link]
Is used to handle errors in a JSP page Is used to trace the exception thrown during the execution It has page scope
<%@page errorpage=[Link]%> < -- some of code,-->
[Link]
<%@page isErrorPage=true%> <% if(exception!=null){ [Link]([Link]()); } %>
27 28
Standard Actions
Are XML like tags which take the form of an XML tag with a name prefixed jsp Are used for
Standard Actions
Forwarding requests and performing includes in page Embedding the appropriate HTML on pages Interacting between pages and JavaBeans Providing additional functionality to tag libraries <jsp:actionName attribute=value>...</ jsp:actionName>
Syntax: Some properties
Using <jsp> prefix The attributes are case sensitive Value in the attributes must be enclosed in double quotes Standard actions can be either an empty or a container tag
30 30
29
21/07/2009
<jsp:include>
<jsp:forward>
Include either static or dynamic file in jsp file at the time of page request. Static case: The content is included in the calling jsp file. Dynamic case: it acts on the request and send back a result that is include in the JSP page. Syntax: <jsp:include: page=webURL|<%=exp%> flush=true/>
31
Its used to forward the request and response to another jsp page or servlet Syntax:
<jsp:forward page={webURL|<%=exp%>}> <jsp:param name={paramName |<%=exp%>}/> <jsp:forward>
<jsp:param>
Allow to pass one or more name/value pairs as parameters to an included or forwarded resource like a jsp page. Syntax:
<jsp:param name=thename value={thevalue|<%=exp%>}
32
<jsp:plugin>
Used in the execution of an applet or bean. Syntax: <jsp:plugin type=bean|applet code=ClassFileName codebase=classFileDirectoryName <jsp:params> <jsp:param name=thename value=thevalue>
<jsp:fallback>
Display a text message to user if the plugin could not start. Syntax:
<jsp:fallback> html message </jsp:fallback>
</jsp:params> [<jsp:fallback> display message to user</jsp:fallback> </jsp:plugin>
33
34
Concept
JavaBeans are reusable components that can be deployed in java. Define the interactivity of Java object
JavaBeans
Allow creation of graphical components that can be reused in GUI application. Can be embedded in multiple applications, servlet and jsp.
Requirements: o Be a public class o Have a public constructor with no arguments
o Have get/set methods to read/write bean properties Components of JavaBeans:
Properties Getters and setters Methods Events
35
36
21/07/2009
<jsp:useBean>
<jsp:getProperty>
Is used to create a reference and include an existing bean component in JSP The <jsp:useBean> follows to locate or instantiate the Bean Attemps to locate a Bean within the scope Defines an object reference variable with the name Stores a reference to it in the variable, if it retrieves the Bean Instantiates it from the specified class, it is cannot retrieve the Bean Syntax: <jsp:useBean id=name class=class scope=page/session/request/application
/>
37
Using for retrieve properties value of the Bean. Retrieves a bean property value using the getter methods and displays the output in a JSP page The <jsp:getProperty> and expression convert the value into a string and insert it into an implicit out object Some drawbacks Fails to retrieve the values of indexes property Fails to directly access enterprise bean components Syntax: <jsp:getProperty name=Bean_Alias property=PropertyName/>
38
<jsp:setProperty>
JavaBeans & Scriptlets
JavaBeans can be accessed from scripting element in different ways. Do it likes in J2SE. The JSP container converts the string values into non string values by the attribute values that evaluate the correct data type to set the property value
Retrieves a bean property value using the getter methods and displays the output in a JSP page The <jsp:getProperty> and expression convert the value into a string and insert it into an implicit out object Some drawbacks:
Fails to retrieve the values of indexes property Fails to directly access enterprise bean components
Syntax:
<jsp:setProperty name=Bean_Alias property=Property_Name value=TheValue param=Parameter/>
39
40
Expression Language
New feature of JSP 2.0 Allows JSP developers to access java objects via a compact, easy-to-use shorthand style (similar to JavaScript) It can handle both expressions and literals Developed by two groups
Expression Language (EL)
JSP Standard Tag Library expert group JSP 2.0 expert group
Syntax:
${EL Expression}
41
42
21/07/2009
EL Implicit Objects
Implicit Objects
Request Headers and Parameters
param: return a value that maps a request parameter name to a single string value ex: "${[Link]} paramValues: return an array of values is mapped to the request parameters from client ex: ${[Link][0]} header: return a request header name and maps the value to single string value. ex: ${header[host]}
pageContext
param servletContext
paramValues
initParam
cookie
header request response session application
headerValues
43
headerValues: return an array of values is mapped to the request header ex: ${[Link]} cookie: returns the cookies name mapped to the single cookie object ex: ${[Link]} initParam: returns a context initialization parameter name, which is mapped to a single value.
44
Scope variables (1)
Variables are used to store and access values in JSP program Variable refers as a attributes that are stored in standard scope such as page, request, session and application Dot operator . or square brackets [ ] can be used to access value of variable Example ${[Link]} ${pageScope[color]}
Scope Variables (2)
45
46
Example
EL Operators
Operators
Arithmetic
Relational
Logical
Empty
* / or div + % or mod
< or lt > or gt < = or le > = or ge = = or eq != or ne
&& or and || or or ! or not
empty
47
48
21/07/2009
Concept
JSP Standard Tag Library (JSTL)
JSTL provides a set of reusable standard tag that work for create jsp pages. JSTL allows programming using tags rather than scriptlet code. JSTL has tags, such as:
Iterators and conditional tags Internationalization tags SQL tags
49
50
Types Of Tags Libraries
JSP Standard Tag Library (JSTL)
Core Tag Library
Core Tag Library
Core Tag Library
I18N & Formatting Tag Library
SQL Tag Library
XML Tag Library
General Purpose Tags
Decision Making Tags
Iteration Tags
set
remove
out
if
choose
forEach
forTokens
51
52
General Purpose Tags
Example
<c:set>: assigns a value to a variable in scope <c:remove>: remove a scope variable <c:out>: evaluate an expression and store a result in the current JspWriter object. <c:catch>: provides an exception handling functionality, such as try-catch inside jsp pages without using scriptlet Syntax:
<c:set var=varName value=value scope=page|request|session|application /> <c:remove var=varName scope=page|request|session|application /> <c:out value=value|expression escapeXml=true |false default=defaultValue /> <c:catch />
53 54
21/07/2009
Decision-Making Tags
<c:if>: used for conditional execution of the code
Iteration Tags
<c:forEach>: used to repate the body content over a collection of objects.
<c:choose>: similar switch statement in java
<c:forTokens>: used to iterate over a collection of tokens separated by user-specified delimiters.
55
56
SQL Tag Library
SQL Tag Library
The sql:setDataSource Tag
setDataSource
query
update
transaction
param
The sql:query Tag
57
58
The sql:update Tag
The sql:param Tag
59
60
10
21/07/2009
The sql:transaction Tag
61
62
I18N Basics(1)
Internationalization The method of designing an application that can be adapted to a region or a language without much change in the technology Helps in creating internationalized Web application that standardize formatted numeric and date-time output (supporting multiple languages) Localization Is a process of making of product or service language, cultural and local look and feel specific A Locale is a simple object identifying a specific language and geographic region ([Link]) Is denoted by xx_YY (language code_letter country) Unicode in Java, is a 16 bit character encoding Resource Bundles contain locale-specific objects
63
Internationalization(I18N)
64
Internationalizing (1)
Resource Bundles Is a set of related classes that inherit from ResourceBundle The several methods
public static final ResourceBundle getBundle(String baseName, Locale locale) public abstract Enumeration getKeys() public Locale getLocale() public final Object getObject(String key) public final String getString(String key)
Internationalizing (2)
Formatting Currencies Currency: this class represents currency by ISO 4217 currency codes public String getCurrencyNode() public String getSymbol()
public static Currency getInstance(Locale locale) NumberFormat: this is an abstract base class for all number formats public final String format(double number) public Currency getCurrency() public static final NumberFormat getInstance() public Number parse(String str) throws ParseException public void setCurrency(Currency currency)
Formatting Dates in Servlets Using predefined Formats: SHORT, MEDIUM, LONG, FULL
Create a formatter with the getDateInstance() method of DateFormat class Invoking the format() method
Customising Formats: Using the SimpleDateFormat class
65
Formatting Percentages public static final NumberFormat getPercentInstance() public static NumberFormat getPercentInstance(Locale inLocale)
66
11
21/07/2009
Internationalizing (3)
Formatting Messages Using the MessageFormat Objects The array of objects using the format specifiers embedded in the pattern formateted by the [Link]() The classes for formatting messages
MessageFormat [Link]
67
12