(JSP) J P

hopeacceptableSoftware and s/w Development

Oct 28, 2013 (3 years and 8 months ago)

83 views

(JSP) J
AVA

SERVER

P
AGES

courtetsy

http
://www.flickr.com/photos/dongga/5887286736/sizes/z/in/photostream/

W
HY

JSP?


You can produce any kind of web document with a
servlet. Servlets allow you to


Read/access form (post) data


Read/access HTTP headers


Read/access request query
paramaters


Read/set cookies


Session tracking


Servlets are really bad for


Generating (X)HTML


JSP solves the 'print("<body>")' kind of problem.


2

E
XAMPLE

JSP F
ILE


Note that the file below is almost HTML.


The name of the file must end in ".
jsp
"


The HTML file has what looks like Java code in it.


The code is executed on the server when the file is requested
by a client.


3

<%@ page import=
"
java.util.Date
"
%>

<HTML>


<HEAD>Time File</HEAD>


<BODY>


The time is now <%= new
java.util.Date
() %>

</BODY>

</HTML>

J
AVA

S
ERVER

P
AGES


JSP pages are (X)HTML files with embedded Java code.


The embedded java represents those parts of the HTML
document that require server
-
side processing to complete.


Kind of like a form letter.


Which to use?


Servlets: if most of the document is dynamically generated


JSP: if most of the document is predefined XHTML with a few
‘placeholders’ for specific data


How does JSP work?


A JSP page will be automatically converted into a Servlet by
the web container.


The servlet is then executed like any other servlet

4

JSP C
YCLE

5

Tomcat
Catalina
Container

Jasper
Compiler

Jasper
Translator

JSP File

Servlet

Bytecode

Java
Servlet

HTTP Request

First page access or source
modified since last access

HTTP Response

JSP L
IFECYCLE


Web containers possess a JSP engine.


Requests may come from a servlet, a web component, or
a browser. When a request comes, the JSP engine checks
for the following conditions:


Is this the first request (ever) for the JSP page.


Has the JSP source been modified since last access


If either condition holds, then the JSP engine will


Parse the JSP document to translate into a Servlet Java file


Compile the Servlet Java file into a class file


The container
loads the Servlet class for execution and
sends the results back to the client
.

6

L
IFECYCLE

S
UMMARY

7

JSP Page first

written

Req

1

Req

2

Server is restarted


Req

3

Req

4

JSP

Page is modified


Req

5

Req

6

JSP translated into

servlet

Yes

No

No

No

Yes

No

Servlet compiled

Yes

No

No

No

Yes

No

Servlet

instantiated
and loaded into
server

Yes

No

Yes

No

Yes

No

init
()

Yes

No

Yes

No

Yes

No

service()

Yes

Yes

Yes

Yes

Yes

Yes

A
NOTHER

E
XAMPLE

8

<%@ page import=
"
java.util.Date
" %>

<BODY>


<H2>JSP Expression</H2>


<UL>


<LI>Current time: <%= new
java.util.Date
() %> </LI>


<LI>Server: <%=
application.getServerInfo
() %></LI>


<LI>Session ID: <%=
session.getId
() %></LI>


<LI>An optional query parameter: <%=
request.getParameter
("test") %></LI>


</UL>

</BODY>

9

/** imports omitted **/


public final class
index_jsp

extends
org.apache.jasper.runtime.HttpJspBase


implements
org.apache.jasper.runtime.JspSourceDependent

{


/** some code omitted **/



public void _
jspService
(final
javax.servlet.http.HttpServletRequest

request, final
javax.servlet.http.HttpServletResponse

response)


throws
java.io.IOException
,
javax.servlet.ServletException

{



/** some code omitted **/



try {


response.setContentType
("text/html");


pageContext

= _
jspxFactory.getPageContext
(this, request,
response, null
, true, 8192, true);


_
jspx_page_context

=
pageContext
;


application =
pageContext.getServletContext
();


config

=
pageContext.getServletConfig
();


session =
pageContext.getSession
();


out =
pageContext.getOut
();


_
jspx_out

= out;



out.write
("
\
n");


out.write
("
\
n");


out.write
("<html>
\
n");


out.write
(" <head>
\
n");


out.write
(" <title>Demo1</title>
\
n");


out.write
(" </head>
\
n");


out.write
(" <body>
\
n");


out.write
("
\
n");


out.write
(" <H2>JSP Expression</H2>
\
n");


out.write
(" <UL>
\
n");


out.write
(" <LI>Current time: ");


out.print
( new
java.util.Date
() );


out.write
(" </LI>
\
n");


out.write
(" <LI>Server: ");


out.print
(
application.getServerInfo
() );


out.write
("</LI>
\
n");


out.write
(" <LI>Session ID: ");


out.print
(
session.getId
() );


out.write
("</LI>
\
n");


out.write
(" <LI>An optional query parameter: ");


out.print
(
request.getParameter
("test") );


out.write
("</LI>
\
n");


out.write
(" </UL>
\
n");


out.write
("
\
n");


out.write
("
\
n");


out.write
("</body>
\
n");


out.write
("</html>
\
n");


} catch (
java.lang.Throwable

t)
{



/** code omitted **/


}


}

}

V
IEW

S
OURCE

10

P
REDEFINED

VARIABLES

11

<%@ page import=
"
java.util.Date
" %>

<BODY>


<H2>JSP Expression</H2>


<UL>


<LI>Current time: <%= new
java.util.Date
() %> </LI>


<LI>Server: <%=
application.getServerInfo
() %></LI>


<LI>Session ID: <%=
session.getId
() %></LI>


<LI>An optional query parameter: <%=
request.getParameter
("test") %></LI>


</UL>

</BODY>

Predefined variables in a JSP page

JSP I
MPLICIT

VARIABLES


There are predefined variables in JSP

1.
request
: This is the
HttpServletRequest

associated with the request, and lets you look
at the request parameters (via
getParameter
), the request type (GET, POST, HEAD, etc.),
and the incoming HTTP headers (cookies,
Referer
, etc.).

2.
response
: This is the
HttpServletResponse

associated with the response to the client..

3.
out
: This is the
PrintWriter

used to send output to the client.

4.
session
: This is the HttpSession object associated with the request.

5.
application
: This is the
ServletContext

as obtained via
getServletConfig
().
getContext
().

6.
config
: This is the
ServletConfig

object for this page.

7.
pageContext
: JSP introduced a new class called
PageContext

to encapsulate use of
server
-
specific features.

8.
page
: This is simply a synonym for this.

12

JSP


JSP pages consist of four different types of elements

1.
Directives


ways to control the JSP container

1.
<%@ directives %>

2.
Declarations


Java variable declarations

1.
<%! declarations %>

3.
XHTML


template text

4.
Scriptlets



Java code embedded in HTML

1.
<% statements %>

5.
Expressions


Java expressions (not statements)

1.
<%= … %>

13

E
XAMPLE

<UL>


<LI><B>
Scriptlet
.</B><BR/>


<%
out.println
("Attached GET data: " +
request.getQueryString
()); %></LI>


<LI><B>Declaration (plus expression).</B><BR/>


<%! private
int

accessCount

= 0; %>


Accesses to page since server reboot: <%= ++
accessCount

%></LI>


<LI><B>Directive (plus expression).</B><BR/>


<%@ page import = "
java.util
.*" %>


Current date: <%= new Date() %></LI>

</UL>

14

JSP D
IRECTIVES


JSP directives control how the
JSP engine
structures the
generated Servlet. JSP
directives
do not directly produce
code.


Directives control settings
such as page settings, and
inclusion of packages, classes, and custom tag
libraries.


Directives
are processed at JSP translation
time, not
execution
time
.



The general syntax of a JSP directive is:


<%@ directive attribute1=”value1” attribute2=”value2” .
.%>

15

D
IRECTIVES

16

Directive Example

Description

<%@ include file
=“header.jsp"
%>

Inserts

the specified file at the given location

<%@ page
autoFlush
="true" %>

Tells JSP to flush the page buffer when it fills

<%@ page buffer=
sizekb

%>

Gives the size of the page buffer in kb or none for no buffer

<%@ page
contentType
=“text/html"
%>

Sets the content type and character encoding of the page

<%@ page
errorPage
="path" %>

Defines a page to display if an error occurs in the JSP page

<%@ page extends="Java class" %>

Changes the generated servlet's class

<%@ page import
=“
java.util.Vector
"
%>

Adds to the Java package import list for the generated Java file

<%@ page info="description" %>

Gives a brief description for the page

<%@ page
isErrorPage
="true" %>

Gives an error page access to the exception implicit variable

<%@ page
isThreadSafe
="true" %>

Tells the JSP that multiple pages can execute in parallel

<%@ page language="
lang
" %>

Sets the JSP script language to lang

<%@ page session="true" %>

Tells JSP that the page participates in a session

<%@ taglib prefix="x" uri="foo" %>

Configures tags with prefix x to use the tag library
foo

<%@ page isELIgnored="false" %>

Ensures that EL

expressions are evaluated

JSP
S
CRIPTLETS


A JSP
scriptlet

is used to contain Java code fragments.


A
scriptlet

is transformed into a Java statement and is inserted into the
service method of the JSP page’s servlet.


17

<%


String username =
request.getParameter
("username");


if ( username != null &&
username.length
() > 0 ) {

%>


<%@include file="response.jsp" %>

<%


}

%>

S
CRIPTLETS

18

<html>


<
head><title>Hello World</title></head>


<
body>


Hello
World!<
br
/>


<%
out.println
("Your IP address is " +
request.getRemoteAddr
()); %>


</
body>

</html>

JSP E
XPRESSION

L
ANGUAGE

(EL)


Similar to JavaScript expressions


Expressions are not statements


An expression is a value


An expression doesn’t ‘do something’


Syntax: "
${expression}"


JSP expressions are translated into Java code
automatically


although JSP expressions are not exactly
the same as Java expressions.

19

JSP EL


EL data often comes from forms.



param
” store a collection of all form data values


${
param.address
} for example


${
param
[‘
cust
-
address’]}



pageContext
” gives information about the request


pageContext.contentType


pageContext.contentLength


pageContext.remoteAddr

20

EL I
MPLICIT

VARIABLES


The EL includes (too many) implicit variables:

1.
param
: Maps a request parameter name to a single value

2.
paramValues
: Maps a request parameter name to an array of values

3.
header
: Maps a request header name to a single value

4.
headerValues
: Maps a request header name to an array of values

5.
cookie
: Maps a cookie name to a single
cookie

6.
initParam
: Maps a context initialization parameter name to a single
value

7.
pageScope
: Maps page
-
scoped variable names to their values

8.
requestScope
: Maps request
-
scoped variable names to their values

9.
sessionScope
: Maps session
-
scoped variable names to their values

10.
applicationScope
: Maps application
-
scoped variable names to their
values


21

JSP E
XAMPLE

22

<%@page
contentType
="text/html"
pageEncoding
="UTF
-
8"%>

<!DOCTYPE HTML PUBLIC "
-
//W3C//DTD HTML 4.01 Transitional//EN"

"http://www.w3.org/TR/html4/loose.dtd">


<html>


<head>


<meta http
-
equiv="Content
-
Type"


content="text/html;
charset
=UTF
-
8">


<title>JSP Page</title>


</head>


<body>


<form action="tempConvertEL2.jsp" method="POST">


<p>


Celsius temperature:


<input type="text" name="
ctemp
" value="" />


<input type = "submit"


value = "Convert to Fahrenheit" />


</p>


</form>


</body>

</html>

JSP E
XAMPLE

23

<%@page
contentType
="text/html"
pageEncoding
="UTF
-
8"%>

<!DOCTYPE HTML PUBLIC "
-
//W3C//DTD HTML 4.01 Transitional//EN"

"http://www.w3.org/TR/html4/loose.dtd">


<html>


<head>


<meta http
-
equiv="Content
-
Type" content="text/html; charset=UTF
-
8">


<title>JSP Page</title>


</head>


<body>


<p>


Given temperature in Celsius: “${
param.ctemp
}” <
br
/>


Temperature in Fahrenheit:“${(1.8 *
param.ctemp
) + 32}”


</p>


</body>

</html>

JSP E
XAMPLE

24

<!DOCTYPE html PUBLIC "
-
//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<%@ page
isELIgnored
=
"false" %>

<%@ page import=
"java.io.*,
java.util
.*" %>

<html>

<head>

<title>Auto Refresh Header Example</title>

</head>

<body>

<center>

<h2>Auto Refresh Example</h2>

<%


// Set refresh,
autoload

time as 5 seconds


response.setIntHeader
("Refresh", 5);


// Get current time


Calendar
calendar

=
new
GregorianCalendar
();


String
am_pm
;


int

hour =
calendar.get
(
Calendar.HOUR
);


int

minute =
calendar.get
(
Calendar.MINUTE
);


int

second =
calendar.get
(
Calendar.SECOND
);


if(
calendar.get
(
Calendar.AM_PM
) == 0)


am_pm

= "AM";


else


am_pm

= "PM";


String CT = hour+":"+ minute +":"+ second +" "+
am_pm
;


out.println
("Current Time is: " + CT + "
\
n");

%>

</center>

</body>

</html>

JSP E
XAMPLE

25

<%@ page
language
=
"java"
contentType
="
text
/html;
charset
=ISO
-
8859
-
1"

pageEncoding
=
"UTF
-
8"%>

<%@ page
isELIgnored
=
"false"%>

<!DOCTYPE html PUBLIC "
-
//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http
-
equiv
=
"Content
-
Type" content="text/html; charset=UTF
-
8">

<title>For Loop</title>

</head>

<body>

<%
for(
int

size=1; size<10; size++) { %>

<div style=
"font
-
size:<%=size %>
em
">
Div

<%= size %></div>

<% } %>

</body>

</html>

JSP E
XAMPLE

26

<%@ page language=
"java"
contentType
="text/html; charset=ISO
-
8859
-
1"
pageEncoding
="ISO
-
8859
-
1" %>

<%@ page import=
"
java.util
.*" %>

<%@ page import=
"
javax.servlet.http.Cookie
" %>

<!DOCTYPE html PUBLIC "
-
//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http
-
equiv
=
"Content
-
Type" content="text/html; charset=ISO
-
8859
-
1">

<title>Headers</title>

</
head>

<body>

<%! Enum
eration<String>
headerNames
; %>

<table>

<%

headerNames

=
request.getHeaderNames
();

response.addCookie
(
new
Cookie(
UUID.randomUUID
().
toString
(),
UUID.randomUUID
().
toString
()));

while(
headerNames.hasMoreElements
()) {

String header =
headerNames.nextElement
();

%>

<
tr
>

<td><%= header %></td>

<td><%=
request.getHeader
(header) %></td>

</
tr
>

<%

}

%>

</table>

</body>

</html>

JSTL


The JSTL (JSP Standard Template Library) elements define control structures and
other functionality that JSP doesn’t.


These tags are XML tags that map to Java functions


<%@
taglib

uri
=“http://java.sun.com/
jsp
/
jstl
/core”
prefix
=“c”%>


27

Area

Subfunction

Prefix

Core

Variable support

c

Flow control

URL management

Miscellaneous

XML

Core

x

Flow control

Transformation

I18n

Locale

fmt

Message formatting

Number and date formatting

Database

SQL

sql

Functions

Collection length

fn

String manipulation

C
ORE

T
AGS

Area

Function

Tags

Prefix

Core

Variable
support

remove

set

c

Flow control

choose


when


otherwise

forEach

forTokens

if

URL
management

import


param

redirect


param

url


param

Miscellaneous

catch

out

28

SET/REMOVE


SET
: sets the value of an EL variable. If the variable does not
already exist, it is created.


Example


<c:set
var
="
foo
" scope="session" value="..."/>


or from the body of the tag:


<c:set
var
="
foo
">

... </c:set>


Example, the following sets an EL variable named

bookID

with
the value of the request parameter named

Remove:


<c:set
var
="
bookId
" value="${
param.Remove
}"/>



REMOVE
: removes an EL variable


<c:remove
var
="cart" scope="session"/>


29

C
ONDITIONALS

(IF)


IF: a one
-
branch conditional based on the value of the
‘test’ attribute.

30

<c:if test="${p == q}">

Generate this template text if p equals q

</c:if>


<c:if test="${p}">

Generate this template text if p equals "true“

</c:if>

C
ONDITIONALS

(C
HOOSE
)


CHOOSE
: a multi
-
way conditional (if
-
then
-
if
-
else)

31

<c:choose>


<c:when test="${p == 0}">


Generate this template text if p equals 0


</c:when>



<c:when test='${p == 1}">


Generate this template text if p equals 1


</c:when>



<c:otherwise>


Generate this template text if p equals anything else


</c:otherwise>

</c:choose>

I
TERATOR

(FOREACH)


forEach
:

iterates over a collection of objects.


The collection is specified via the ‘items’ attribute


Arrays


Collection subclasses


Map subclasses


The current item is specified via the ‘
var
’ attribute


If the items

attribute is of type

java.util.Map
, then the current
item will be of type

java.util.Map.Entry
, which has the following
properties:


key: The key under which the item is stored in the underlying

Map


value: The value that corresponds to the key


Even String

objects can be iterated over if the string contains a
list of comma
-
separated values (for example:
Monday,Tuesday,Wednesday,Thursday,Friday
)!


32

FOR
E
ACH

E
XAMPLE

33


<table>


<c:forEach items="${
headerValues
}"
var
="entry">


<
tr
><td>"${
entry.key
}"</td>


<c:forEach items="${
entry.value
}"
var
="
keyvalue
">


<td>"${
keyvalue
}"</td>


</c:forEach>


</
tr
>


</c:forEach>

</table>

<!
--

headerValues

is a map. The values are arrays
--
>

OUT


out: evaluates an expression and outputs the result of the
evaluation.


<c:out value="value" [
escapeXml
="{
true|false
}"]

[default="
defaultValue
"] />


If the result of the evaluation is a

java.io.Reader

object,
then data is first read from the

Reader

object and then
written into the output.


If
escapeXml

is ‘true’ then the character conversions
listed in the below table are applied.


34

Character

Character Entity Code

<

&
lt
;

>

&
gt
;

&

&amp;

'

&#039;

"

&#034;

35

<%@ page
contentType
="text/html"
pageEncoding
="UTF
-
8"%>

<%@
taglib

prefix = "c"


uri

= "http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE HTML PUBLIC "
-
//W3C//DTD HTML 4.01 Transitional//EN"

"http://www.w3.org/TR/html4/loose.dtd">


<html>


<head>


<meta http
-
equiv="Content
-
Type"


content="text/html;
charset
=UTF
-
8">


<title> Temperature Converter </title>


</head>


<body>


<c:if test = "${
pageContext.request.method

!= 'POST'}">


<form action="index.jsp" method="POST">


Celsius temperature:


<input type="text" name="
ctemp
" value="" />


<input type = "submit"


value = "Convert to Fahrenheit" />


</form>


</c:if>


<c:if test = "${
pageContext.request.method

== 'POST'}">


Given temperature in Celsius:


<c:out value = "${
param.ctemp
}" /> <
br

/>


The temperature in Fahrenheit:


<c:out value = "${(1.8 *
param.ctemp
) + 32}" />


</c:if>


</body>

</html>