Title: JSP Java Server Pages
1JSP Java Server Pages
- Representation and Management of Data on the
Internet
2Introduction
3What is JSP Good For?
- Servlets allow us to write dynamic Web pages
- Easy access to request, session and context data
- Easy manipulation of the response (cookies, etc.)
- And lots more...
- It is not convenient to write and maintain long
static HTML using Servlets - out.println("lth1gtBla Blalt/h1gt" "bla bla bla
bla" "lots more here...")
4JSP Idea
- Use HTML for most of the page
- Write Servlet code directly in the HTML page,
marked with special tags - The server automatically translates a JSP page to
a Servlet class and the latter is actually
invoked - In Tomcat 5.0 you can find the generated Servlet
code under CATALINA_BASE/work/
5Relationships
- Servlets HTML code is printed from Java code
- JSP Java code is embedded in HTML code
Java
HTML
Java
HTML
6Example
- ltHTMLgt
- ltHEADgt
- ltTITLEgtHello Worldlt/TITLEgt
- lt/HEADgt
- ltBODYgt
- ltH2gtltIgtlt new java.util.Date() gtlt/Igtlt/H2gt
- ltH1gtHello Worldlt/H1gt
- lt/BODYgt
- lt/HTMLgt
Tomcat 5.0 Generated Servlet
7(No Transcript)
8JSP Limitations and Advantages
- JSP can only do what a Servlet can do
- Easier to write and maintain HTML
- Easier to separate HTML from code
- Can use a "reverse engineering technique" create
static HTML and then replace static data with
Java code
9Basic JSP Elements
10Elements in a JSP file
- HTML code lthtml-taggtcontentlt/html-taggt
- HTML comment lt!-- comment --gt
- JSP Comment lt-- comment --gt
- Expressions lt expression gt
- Scriptlets lt code gt
- Declarations lt! code gt
- Directives lt_at_ directive attribute"value" gt
- Actions discussed later
11JSP Expressions
- A JSP expression is used to insert Java values
directly into the output - It has the form lt expression gt , where
expression can be a Java object, a numerical
expression, a method call that returns a value,
etc... - For example
- lt new java.util.Date() gt
- lt "Hello"" World" gt
- lt (int)(100Math.random()) gt
12JSP Expressions
- A JSP Expression is evaluated
- The result is converted to a string
- The string is inserted into the page
- This evaluation is performed at runtime (when the
page is requested), and thus has full access to
information about the request, the session, etc...
13Expression Translation
ltH1gtA Random Numberlt/H1gt lt Math.random() gt
14Predefined Variables (Implicit Objects)
- The following predefined variables can be used
- request the HttpServletRequest
- response the HttpServletResponse
- session the HttpSession associated with the
request - out the PrintWriter (a buffered version of type
JspWriter) used to fill the response content - application The ServletContext
- These variables and more will be discussed in
details
15ltHTMLgt ltHEADgt ltTITLEgtJSP Expressionslt/TITLEgtlt/H
EADgt ltBODYgt ltH2gtJSP Expressionslt/H2gt ltULgt
ltLIgtCurrent time lt new java.util.Date()
gt ltLIgtYour hostname lt request.getRemoteHo
st() gt ltLIgtYour session ID lt
session.getId() gt ltLIgtThe
ltCODEgttestParamlt/CODEgt form parameter lt
request.getParameter("testParam") gt lt/ULgt
lt/BODYgt lt/HTMLgt
16(No Transcript)
17(No Transcript)
18JSP Scriplets
- JSP scriptlets let you insert arbitrary code into
the Servlet service method ( _jspService ) - Scriptlets have the form lt Java Code gt
- The code is inserted verbatim into the service
method, according to the location of the scriplet - Scriptlets have access to the same automatically
defined variables as expressions
19Scriptlet Translation
lt foo() gt lt bar() gt
public void _jspService(HttpServletRequest
request,
HttpServletResponse response) throws
ServletException, IOException ... response.set
ContentType("text/html") ... out.print(foo())
bar() ...
20An Interesting Example
- Scriptlets don't have to be complete code blocks
lt if (Math.random() lt 0.5) gt You ltBgtwonlt/Bgt
the game! lt else gt You ltBgtlostlt/Bgt the
game! lt gt
if (Math.random() lt 0.5) out.write("You
ltBgtwonlt/Bgt the game!") else
out.write("You ltBgtlostlt/Bgt the game!")
21JSP Declarations
- A JSP declaration lets you define methods or
members that get inserted into the Servlet class
(outside of all methods) - It has the following form
- lt! Java Code gt
- For example
- lt! private int someField 5 gt
- lt! private void someMethod(...) ... gt
- It is usually of better design to define methods
in a separate Java class...
22Declaration Example
- Print the number of times the current page has
been requested since the server booted (or the
Servlet class was changed and reloaded)
lt! private int accessCount 0 gt lt! private
synchronized int incAccess() return
accessCount gt ltH1gtAccesses to page since
server reboot lt incAccess() gt lt/H1gt
23(No Transcript)
24(No Transcript)
25- public class serviceCount_jsp extends...
implements... throws... - private int accessCount 0
- private synchronized int incAccess()
- return accessCount
- public void _jspService(HttpServletRequest
request, - HttpServletResponse
response) - throws ServletException, IOException
- ...
- ...
- out.write("ltH1gtAccesses to page since
server reboot ") - out.print(incAccess())
- ... ...
26jspInit and jspDestroy
- In JSP pages, like regular Servlets, sometimes
want to use init and destroy - It is illegal to use JSP declarations to override
init or destroy, since they (usually) are already
implemented by the generated Servlet - Instead, override the methods jspInit and
jspDestroy - The generated servlet is guaranteed to call these
methods from init and destroy respectively - The standard versions of jspInit and jspDestroy
are empty (placeholders for you to override)
27JSP Directives
- A JSP directive affects the structure of the
Servlet class that is generated from the JSP page - It usually has the following form
- lt_at_ directive attribute"value" gt
- Multiple attribute settings for a single
directive can be combined - lt_at_ directive attribute1"value1" ...
attributeN"valueN" gt - Two types discussed in this section page and
include
28page-Directive Attributes
- import attribute A comma separated list of
classes/packages to import - lt_at_ page import"java.util., java.io." gt
- contentType attribute Sets the MIME-Type of the
resulting document (default is text/html) - lt_at_ page contentType"text/plain" gt
- Note that instead of using the contentType
attribute, you can write - lt response.setContentType("text/plain") gt
29More page-Directive Attributes
- session"truefalse" - use a session?
- buffer"sizekbnone"
- Specifies the content-buffer size (out)
- errorPage"url "
- Defines a JSP page that handles uncaught
exceptions - The page in url must have true in the
page-directive - isErrorPage"truefalse"
- The variable exception holds the exception thrown
by the calling JSP
30showTableA.jsp
ltHTMLgt ltHEADgt ltTITLEgtReading From
Databaselt/TITLEgtlt/HEADgt ltBODYgt lt_at_ page
import"java.sql." gt lt_at_ page
errorPage"errorPage.jsp" gt lt
Class.forName("oracle.jdbc.driver.OracleDriver")
Connection con DriverManager.getConnection("
jdbcoraclethin" "snoopy/snoopy_at_sol41521
stud") Statement stmt con.createStatement()
ResultSet rs stmt.executeQuery("Select
from a") ResultSetMetaData md
rs.getMetaData() int col md.getColumnCount()
gt
31 ltTABLE border"2"gt lt while (rs.next())
gt ltTRgt lt for (int i 1 i lt col i)
gt ltTDgtlt rs.getString(i) gtlt/TDgt lt
gt lt/TRgt lt gt lt/TABLEgt lt/BODYgt lt/HTMLgt
32errorPage.jsp
ltHTMLgt ltHEADgt ltTITLEgtReading From
Databaselt/TITLEgtlt/HEADgt ltBODYgt lt_at_ page
isErrorPage"true" gt lth1gtOops. There was an
error when you accessed the database.
lt/h1gt lth2gtHere is the stack trace lt/h2gt ltfont
color"red"gt ltpregt lt exception.printStackTrace(ne
w PrintWriter(out)) gt lt/pregtlt/fontgt lt/BODYgt lt/HT
MLgt
33Table A exists!
34Table A does not exist!
35The include Directive
- This directive lets you include files at the time
the JSP page is translated into a Servlet - The directive looks like this
- lt_at_ include file"url" gt
- JSP content can affect main page
- In Tomcat 5.x, generated Servlet is updated when
included files change (unlike old versions...)
36ltHTMLgt ltHEADgt ltTITLEgtIncluding
JSPlt/TITLEgtlt/HEADgt ltBODYgt Here is an interesting
page.ltbrgtltbrgt Bla, Bla, Bla, Bla.
ltbrgtltbrgtltbrgt lt_at_ include file"AccessCount.jsp"
gt lt/BODYgt lt/HTMLgt
BlaBla.jsp
lthrgt Page Created for Dbi Course. Email us lta
href"mailtodbi_at_cs.huji.ac.il"gtherelt/agt. ltbrgt lt!
private int accessCount 0 gt Accesses to
page since server reboot lt accessCount gt
AccessCount.jsp
37(No Transcript)
38- out.write("ltHTMLgt \r\n")
- out.write("ltHEADgt ltTITLEgtIncluding
JSPlt/TITLEgtlt/HEADgt\r\n") - out.write("ltBODYgt\r\n")
- out.write("Here is an interesting
page.ltbrgtltbrgt\r\n") - out.write("Bla, Bla, Bla, Bla.
ltbrgtltbrgtltbrgt\r\n") - out.write("\r\n")
- out.write("lthrgt\r\n")
- out.write("Page Created for Dbi Course.
Email us \r\n") - out.write("lta href\"mailtodbi_at_cs.huji.ac.i
l\"gtherelt/agt.\r\n") - out.write("ltbrgt\r\n")
- out.write(" \r\n")
- out.write("Accesses to page since server
reboot \r\n") - out.print( accessCount )
- out.write("\r\n")
- out.write("lt/BODYgt\r\n")
- out.write("lt/HTMLgt ")
39Writing JSP in XML(and vice versa)
- We can replace the JSP tags with XML tags that
represent - Expressions
- Scriptlets
- Declarations
- Directives
40(No Transcript)
41- lt?xml version"1.0" encoding"UTF-8"?gt
- ltjsproot xmlnsjsp"http//java.sun.com/JSP/Page"
version"2.0"gt - ltnumbersgt
- ltjspscriptletgt for(int i1 ilt10 i)
lt/jspscriptletgt - ltnumbergt
- ltjspexpressiongt i lt/jspexpressiongt
- lt/numbergt
- ltjspscriptletgt lt/jspscriptletgt
- lt/numbersgt
- lt/jsprootgt
42(No Transcript)
43Variables in JSP
44Implicit Objects
- As seen before, some useful variables, like
request and session are predefined - These variables are called implicit objects
- Implicit objects are defined in the scope of the
service method - Can these be used in JSP declarations?
- Implicit objects are part of the JSP
specifications
45The objects request and response
- request and response are the HttpServletRequest
and HttpServletResponse arguments of the service
method - Using these objects, you can
- Read request parameters
- Set response headers
- etc. (everything we learned in Servlet lectures)
46The object out
- This is the Writer used to add write output into
the response body - This object implements the interface JspWriter,
which supports auto-flush - Recall that you can adjust the buffer size, or
turn buffering off, through use of the buffer
attribute of the page directive
47The object page
- Simply a synonym for (Object)this
- page is not very useful in JSP pages
- It was created as a placeholder for the time when
the scripting language could be something other
than Java
48The object pageContext
- pageContext is a new object introduced by JSP
- This object encapsulates use of server-specific
features (e.g. higher performance JspWriters) - Access server-specific features through this
class rather than directly, so your code will
conform to JSP spec. and not be server dependent - This object is also used to store page-scoped
Java Beans (discussed later)
49The object session
- This is the HttpSession object associated with
the request - If the session attribute in the page directive is
turned off (lt_at_ page session"false" gt) then
this object is not available - Recall that a session is created by default
50The object config
- This is the ServletConfig of the page, as
received in the init() method - Remember Contains Servlet specific
initialization parameters - Later, we will study how initialization
parameters are passed to JSP pages in Tomcat - You can get the ServletContext from config
51The object application
- This is the ServletContext as obtained via
getServletConfig().getContext() - Remember
- The ServletContext is shared by all
Web-application Servlets (including ones
generated from JSP) - Getting and setting attributes is with
getAttribute and setAttribute of ServletContext - You can use this object to get application-wide
initialization parameters
52Review Variable Scope
53Review Variable Scope
54Review Variable Scope
55Review Variable Scope
56Servlet Package and Helper Classes
- The generated Servlet has a named package
- In Tomcat, this package is org.apache.jsp
- In Java, you cannot use classes from the default
package (i.e. with no package declaration) from a
named package! - Therefore, helper classes used by JSP pages must
have a named package
57JSP Actions
58Actions
- JSP actions use constructs in XML syntax to
control the behavior of the Servlet engine - Using actions, you can
- dynamically insert a resource content
- forward the user to another page
- reuse Java Beans and custom tags - briefly
discussed later
59The forward Action
- jspforward - Forwards the requester to a new
resource - ltjspforward page"relativeURLlt expression
gt"gt - ltjspparam name"parameterName" Â
- value"parameterValue lt expression gt" /gt
- lt/jspforwardgt
- This action is translated to an invocation of the
RequestDispatcher
60The include Action
- jspinclude - Include a resource content at run
time - ltjspinclude page"relativeURLlt expression
gt" - flush"true false" gt   Â
- ltjspparam name"parameterName"
- value"parameterValue lt expression
gt" /gt - lt/jspincludegt
- This action is also translated to an invocation
of the RequestDispatcher
61include Directive vs. Action
- When a file is included using the include
directive, the file itself is included verbatim
into the JSP code, prior to the Servlet
generation - When a resource is included using the include
action, the generated Servlet uses the dispatcher
to include its content at runtime - Question using which of the latter options can
the included element change the HTTP headers or
status?
62JSP Life Cycle
63JSP Life Cycle
- The following table describes the life cycle of
JSP generated Servlet in details
64JSP Life Cycle
Written by Marty Hall. Core Servlets JSP book
www.coreservlets.com
65JSP Translation
- When the JSP file is modified, JSP is translated
into a Servlet - Application need not be reloaded when JSP file is
modified - In Tomcat 5.0, translation is done even if
included files (through the include directive)
are modified - Server does not generate the Servlet class after
startup, if the latter already exists - Generated Servlet acts just like any other Servlet
66init() and destroy()
- init() of the generated Servlet is called every
time the Servlet class is loaded into memory and
instantiated - destroy() of the generated Servlet is called
every time the generated Servlet is removed - The latter two happen even if the reason is
modification of the JSP file
67Thread Synchronization
- After the Servlet is generated, one instance of
it services requests in different threads, just
like any other Servlet - In particular, the service method (_jspService)
may be executed by several concurrent threads - Thus, like Servlets, JSP code should deal with
concurrency
68JSP in Tomcat 5.0
69Tomcat 5.0 Generated Servlet
- ltHTMLgt
- ltHEADgt
- ltTITLEgtHello Worldlt/TITLEgt
- lt/HEADgt
- ltBODYgt
- ltH2gtltIgtlt new java.util.Date() gtlt/Igtlt/H2gt
- ltH1gtHello Worldlt/H1gt
- lt/BODYgt
- lt/HTMLgt
Tomcat 5.0 Generated Servlet
70Generated Servlet Hierarchy(Tomcat 5.0
Implementation)
71Implementation vs. Specification
- JSP files should conform to JSP specifications
and be container independent - For example, JSP files that assume extension of
HttpServlet will compile and run correctly under
Tomcat, but may fail to compile under other
containers - The implicit object pageContext exists for this
reason
72JSP Initial Parameters
- Like Servlets, initial parameters can be passed
to JSP files using the ltservletgt element of the
application configuration file web.xml - Use the sub-element ltjsp-filegt instead of the
sub-element ltservlet-classgt - A ltservlet-mappinggt is also needed
- Use the JSP file as the lturl-patterngt
73- ltweb-appgt
- ltcontext-paramgt
- ltparam-namegtdbLoginlt/param-namegt
- ltparam-valuegtsnoopylt/param-valuegt
- lt/context-paramgt
-
- ltcontext-paramgt
- ltparam-namegtdbPasswordlt/param-namegt
- ltparam-valuegtsnoopasslt/param-valuegt
- lt/context-paramgt
74- ltservletgt
- ltservlet-namegtParamPagelt/servlet-namegt
- ltjsp-filegt/paramPage.jsplt/jsp-filegt
- ltinit-paramgt
- ltparam-namegttableNamelt/param-namegt
- ltparam-valuegtuserslt/param-valuegt
- lt/init-paramgt
- lt/servletgt
- ltservlet-mappinggt
- ltservlet-namegtParamPagelt/servlet-namegt
- lturl-patterngt/initParam.jsplt/url-patterngt
- lt/servlet-mappinggt
- lt/web-appgt
75ltHTMLgt ltHEADgtltTITLEgtJSP initial
parameterslt/TITLEgtlt/HEADgt ltBODYgt
ltH1gtHellolt/H1gt ltH2gtI should use the table
ltIgtlt config.getInitParameter("tableName"
) gtlt/Igt.lt/H2gt ltH2gtTo access the Database, I
should use the login ltIgtlt
application.getInitParameter("dbLogin") gtlt/Igt
and the password ltIgtlt
application.getInitParameter("dbPassword")
gtlt/Igt.lt/H2gt lt/BODYgt lt/HTMLgt
76(No Transcript)
77Appendix 1Java Beans in JSP
78Motivation
- Software components (e.g. objects, data
structures, primitives) are extensively used in
Web applications - For example
- Service local variables
- Attributes forwarded in requests
- Session attributes, like users information
- Application attributes, like access counters
79Motivation
- Standard actions are used to manipulate
components declaration, reading from the
suitable context, setting of new values
(according to input parameters), storing inside
the suitable context, etc. - Java Beans provide a specification for automatic
handling and manipulation of software components
in JSP (and other technologies...)
80Java Beans The Idea
- Wrap your data, in a standard fashion, inside a
Java class (Java Bean) - Use special JSP actions to access and manipulate
the bean - Use special action attributes to specify the
properties of the bean, like its scope
81Example 1 Access Counter
- In the following example, we use a Bean to
maintain an access counter for requests to the
pages
82(No Transcript)
83(No Transcript)
84- package dbi
- public class CounterBean
- private int counter
- public CounterBean() counter 0
- public int getCounter() return counter
- public void setCounter(int i) counter i
-
- public void increment() counter
Bean must reside in a package
Bean is created by an empty constructor
getCounter and setCounter define the property
counter
other methods can be used
85pageA.jsp
ltjspuseBean id"accessCounter"
class"dbi.CounterBean" scope"application"/gt lt
accessCounter.increment() gt ltH1gtWelcome to Page
Alt/H1gt ltH2gtAccesses to this application
ltjspgetProperty name"accessCounter"
property"counter"/gtlt/H2gt ltA HREF"pageB.jsp"gtPa
ge Blt/agt
invokes getCounter()
86pageB.jsp
ltjspuseBean id"accessCounter"
class"dbi.CounterBean" scope"application"/gt lt
accessCounter.increment() gt ltH1gtWelcome to Page
Blt/H1gt ltH2gtAccesses to this application
ltjspgetProperty name"accessCounter"
property"counter"/gtlt/H2gt ltA HREF"pageA.jsp"gtPa
ge Alt/agt
87Example 2 Session Data
- In the following example, we use a Bean in order
to keep a user's details throughout the session
88(No Transcript)
89(No Transcript)
90(No Transcript)
91- package dbi
- public class UserInfoBean
- private String firstName
- private String lastName
- public UserInfoBean() firstName lastName
null - public String getFirstName() return firstName
- public String getLastName() return lastName
- public void setFirstName(String string)
firstName string - public void setLastName(String string) lastName
string
92infoForm.html
ltHTMLgt ltHEADgtltTITLEgtUser Infolt/TITLEgtlt/HEADgt
ltBODYgtltH1gtFill in your detailslt/H1gt ltFORM
ACTION"infoA.jsp"gt Your First Name ltINPUT
TYPE"text" NAME"firstName"gt ltBRgt Your
Last Name ltINPUT TYPE"text" NAME"lastName"gt
ltBRgt ltINPUT TYPE"submit"gt
lt/FORMgt lt/BODYgt lt/HTMLgt
93infoA.jsp
Match parameters to corresponding properties
ltjspuseBean id"userInfo" class"dbi.UserInfoBe
an" scope"session"/gt ltjspsetProperty
name"userInfo" property""/gt ltH1gt
ltjspgetProperty name"userInfo"
property"firstName"/gt ltjspgetProperty
name"userInfo" property"lastName"/gt,
lt/H1gt ltH1gtHave a nice session!lt/H1gt ltA
HREF"infoB.jsp"gtUser Info Blt/agt
94infoB.jsp
ltjspuseBean id"userInfo" class"dbi.UserInfoBe
an" scope"session"/gt ltjspsetProperty
name"userInfo" property""/gt ltH1gt
ltjspgetProperty name"userInfo"
property"firstName"/gt ltjspgetProperty
name"userInfo" property"lastName"/gt,
lt/H1gt ltH1gtHave a nice session!lt/H1gt ltA
HREF"infoA.jsp"gtUser Info Alt/agt
95Advantages of Java Beans
- Easy and standard management of data
- Automatic management of bean sharing and lots
more - Good programming style
- Allow standard but not direct access to members
- You can add code to the setters and getters (e.g.
constraint checks) without changing the client
code - You can change the internal representation of the
data without changing the client code - Increase of separation between business logic
(written by programmers) and HTML (written by GUI
artists)
96Appendix 2Custom JSP Tags
97Custom JSP Tags
- JSP code may use custom tags - tags that are
defined and implemented by the programmer - The programmer defines how each of the custom
tags is translated into Java code - There are two methods to define custom tags
- Tag libraries - used in old versions of JSP
- Tag files - much simpler, introduced in JSP 2.0
98Tag Libraries
- A tag library consists of
- Tag handlers - Java classes that define how each
of the new tags is translated into Java code - A TLD (Tag Library Descriptor) file, which is an
XML file that defines the structure and the
implementing class of each tag
99A Simple TagLib Example
DateTag.java
- package dbi
- import javax.servlet.jsp.JspException
- import javax.servlet.jsp.tagext.SimpleTagSupport
- import java.io.IOException
- public class DateTag extends SimpleTagSupport
- public void doTag() throws JspException,
IOException - getJspContext().getOut().print(new
java.util.Date()) -
100lt?xml version"1.0" encoding"ISO-8859-1"
?gt lttaglib version"2.0"gt lttlib-versiongt1.0lt/tli
b-versiongt lttaggt ltnamegtdatelt/namegt
lttagclassgtdbi.DateTaglt/tagclassgt
ltbody-contentgtemptylt/body-contentgt
lt/taggt lt/taglibgt
dbi-taglib.tld
lt_at_ taglib prefix"dbitag" uri"/WEB-INF/tags/d
bi-taglib.tld" gt lthtmlgtltbodygt lth1gtHello. The
time is ltdbitagdate/gtlt/h1gt lt/bodygtlt/htmlgt
taglibuse.jsp
101(No Transcript)
102Tag Files
- The new version of JSP (2.0) provides an
extremely simplified way of defining tags - The idea for each custom tag, write a tag file
tagName.tag that implements the tag translation
using JSP code - This way, the programmer can avoid creating tag
handlers and TLD files
103The Simplified Example
lt new java.util.Date() gt
date.tag
lt_at_ taglib prefix"dbitag" tagdir"/WEB-INF/tags/"
gt lthtmlgtltbodygt lth1gtHello. The time is
ltdbitagdate/gtlt/h1gt lt/bodygtlt/htmlgt
taguse.jsp
104(No Transcript)
105Other Capabilities of Custom Tags
- Attributes
- You can define the possible attributes of the
Tags - These can be accessed during the Tag translation
- Tag Body
- Tag translation may choose to ignore, include or
change the tag body