lap trinh web [slide jsp]
TRANSCRIPT
21/07/2009
1
Java Server Pages
http://www.vovanhai.wordpress.com
1
JSP Basics
2
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
3
Architecture of JSP
4
JSP Expression
Includes expression in a scripting language page
5
Scriptlet
Refers to code blocks executed for every request.
6
21/07/2009
2
Declarations
Defines the variables and methods for a JSP page
7
Comments
Explains the functioning of the code
Comments are ignored by the servlet during
compilation
Syntax
...
<!–- HTML comments -->
...
...
<%-- JSP comments --%>
...
...
<% /*Scripting languages comments*/ %>
...
8
Directives 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
...
<%directivename attribute = “value”%>
...
Specifies the JSP directive
Refers to the directive attribute9
Directives – Contd…
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
10
page Directive
11
include Directive
12
21/07/2009
3
taglib Directive
13
Standard Actions Tags affecting the behavior of JSP at runtime and the response sent
back to web browser
Syntax:
...
<jsp: standard action>
...
Standard Action Description
<jsp: useBean> Accesses the functions of custom tags
<jsp: param> Provides name and value to the parameters used by the JSP page
<jsp: include> Includes the output from one file into the other files
<jsp: forward> Transfers control from a JSP page to another
<jsp: plugin> Uses a plugin to execute an applet or bean
14
JSP Implicit Object
15
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
Types of implicit objects16
Implicit Objects (cont)
Object Class / Interface
page javax.servlet.jsp.HttpJspPage
config javax.servlet.ServletConfig
request javax.servlet.http.HttpServletRequest
response javax.servlet.http.HttpServletResponse
out javax.servlet.jsp.JspWriter
session javax.servlet.http.HttpSession
application javax.servlet.ServletContext
pageContext javax.servlet.jsp.PageContext
exception java.lang.Throwable
17
The request Object
18
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
21/07/2009
4
The response Object
19
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
20
Represents the output stream, then it will be sent to the client as a
response for the request
Is has page scope
The session Object
21
Provides all the objects
available in the JSP pages
within the session
The application Object
22
Is used to share the data
between all application
pages
Can be accessed by any
JSP present in the
application
The pageContext Obbject (1)
23
Provides methods to access all attributes
defined by implicit objects in the page.
Provides methods to transfer control
from one web page to another
osetAttribute()
ogetAttribute()
ogetAttributeNamesInScope()
oremoveAttribute()
The pageContext Obbject (2)
24
Find the scope or
specify the scope
21/07/2009
5
Servlet Object (1)
25
The page object: is an instance of the servlet
processing the current request in a JSP page.
Servlet Object (2)
26
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 exception Object
27
Is used to handle errors in a
JSP page
Is used to trace the
exception thrown during
the execution
It has page scope
Error handling
<%@page errorpage=“error.jsp”%>
< -- some of code,…-->
index.jsp
error.jsp
<%@page isErrorPage=“true”%>
<%
if(exception!=null){
out.println(exception.getMessage());
}
%>
28
Standard Actions
29
Standard Actions
30
Are XML like tags which take the form of an XML tag
with a name prefixed jsp
Are used for
Forwarding requests and performing includes in page
Embedding the appropriate HTML on pages
Interacting between pages and JavaBeans
Providing additional functionality to tag libraries
Syntax:<jsp:actionName attribute=“value”>...</jsp:actionName>
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 tag30
21/07/2009
6
<jsp:include>
31
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”/>
<jsp:forward>
32
It’s 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>
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%>}”
<jsp:param>
<jsp:plugin>
33
Used in the execution of an applet or bean.
Syntax:
<jsp:plugintype=“bean|applet”code=“ClassFileName”codebase=“classFileDirectoryName”<jsp:params>
<jsp:param name=“thename” value=“thevalue”>
</jsp:params>[<jsp:fallback> display message to
user</jsp:fallback>
</jsp:plugin>
<jsp:fallback>
34
Display a text message to user if the plug-
in could not start.
Syntax:
<jsp:fallback>
html message
</jsp:fallback>
JavaBeans
35
Concept
36
JavaBeans are reusable components that can be deployed in java.
Define the interactivity of Java object
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
21/07/2009
7
<jsp:useBean> 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
<jsp:getProperty>
38
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 directlyaccess enterprise bean components
Syntax:
<jsp:getProperty name=“Bean_Alias”
property=“PropertyName”/>
<jsp:setProperty>
39
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”/>
JavaBeans & Scriptlets
40
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 propertyvalue
Expression Language
41
Expression Language (EL)
42
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 JSP Standard Tag Library expert group
JSP 2.0 expert group
Syntax: ${EL Expression}
21/07/2009
8
EL Implicit Objects
43
Implicit Objects
pageContext cookieinitParamparamValuesparam
header headerValues
application
servletContext
request
session
response
Request Headers and Parameters
44
param: return a value that maps a request parameter name to
a single string value
ex: "${param.Name}“
paramValues: return an array of values is mapped to the
request parameters from client
ex: “${paramValues.Name[0]}”
header: return a request header name and maps the value to
single string value.
ex: ${header[“host”]}
headerValues: return an array of values is mapped to the
request header
ex: ${headerValues.Name}
cookie: returns the cookies name mapped to the single cookie
object
ex: ${cookie.name.value}
initParam: returns a context initialization parameter name, which is
mapped to a single value.
Scope variables (1)
45
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
${pageScope.color}
${pageScope[“color”]}
Scope Variables (2)
46
EL Operators
47
*
/ or div
+
-
% or mod
< or lt
> or gt
< = or le
> = or ge
= = or eq
!= or ne
&& or and
|| or or
! or not
empty
Operators
EmptyLogicalRelationalArithmetic
Example
48
21/07/2009
9
JSP Standard Tag Library
(JSTL)
49
Concept
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
50
Types Of Tags Libraries
51
JSP Standard Tag Library
(JSTL)
Core Tag
Library
I18N &
Formatting
Tag Library
SQL Tag
Library
XML Tag
Library
Core Tag Library
52
General
Purpose Tags
Decision
Making TagsIteration Tags
set remove out forEach forTokensif choose
Core Tag Library
General Purpose Tags
53
<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 />
Example
54
21/07/2009
10
Decision-Making Tags
55
<c:if>: used for conditional execution of the code
<c:choose>: similar switch statement in java
Iteration Tags
56
<c:forEach>: used to repate the body content over a
collection of objects.
<c:forTokens>: used to iterate over a collection of
tokens separated by user-specified delimiters.
SQL Tag Library
57
SQL Tag Library
setDataSource query update paramtransaction
The sql:setDataSource Tag
58
The sql:queryTag
The sql:update Tag
59
The sql:param Tag
60
21/07/2009
11
The sql:transaction Tag
61 62
Internationalization(I18N)
63
I18N Basics(1)
64
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 (java.lang.Locale)
Is denoted by xx_YY (language code_letter country)
Unicode in Java, is a 16 bit character encoding
Resource Bundles contain locale-specific objects
Internationalizing (1)
65
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)
Formatting Dates in Servlets
Using predefined Formats: SHORT, MEDIUM, LONG, FULL
Create a formatter with the getDateInstance() method ofDateFormat class
Invoking the format() method
Customising Formats: Using the SimpleDateFormat class
Internationalizing (2)
66
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 Percentages
public static final NumberFormat getPercentInstance()
public static NumberFormat getPercentInstance(Locale inLocale)
21/07/2009
12
Internationalizing (3)
67
Formatting Messages
Using the MessageFormat Objects
The array of objects using the format specifiers
embedded in the pattern formateted by the
MessageFormat.format()
The classes for formatting messages
MessageFormat
MessageFormat.Field