Title: JSP Java Server Page
1JSP Java Server Page
- DBI Representation and Management of Data on
the Internet
2What is JSP
- http//java.sun.com/products/jsp
- A way to create dynamic web pages
- Based on Java Technology
- Large library base
- Platform independence
- Server side processing
- Separates the graphical design from the dynamic
content
3Relationships
- In servlets,
- HTML code is printed from java code
- In JSP pages
- Java code is embadded in HTML code
Template text
Java
HTML
Java
HTML
4In General Lines
- JSP-enabled server
- picks up .jsp page
- parses it
- converts it to runnable form
- runs it
- Converts page to a Java servlet (JspPage), with
your code inside the _jspService() method - compiles it
- runs servlet protocol
5Separating Graphical Design and Dynamic Content
- Not a new idea (e.g. PHP, mod_perl, shtml, ASP)
- Graphical Design and System Design are two
separate and distinct specialities - Different languages (HTML vs. Java)
- Different goals
- Different Training
- Should be separated for optimal project
management - JSP does this by allowing special Java tags in
HTML
6An Example
- lt!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN"gt - ltHTMLgt
- ltHEADgt
- ltTITLEgtHello World Examplelt/TITLEgt
- lt/HEADgt
- ltBODYgt
- ltH2gtHello World Examplelt/H2gt
- ltBgtlt out.println("Hello World") gtlt/Bgt
- lt/BODYgt
- lt/HTMLgt
7(No Transcript)
8Translating and Executing JSP Pages
- A JSP page is executed in a JSP container,
generally installed in a Web server - Think of a JSP container as a JVM with suitable
software installed - The underlying semantic model is that of a
servlet - A typical JSP container will translate the JSP
page to a Java servlet - By default, translation and compilation of a JSP
page is likely to occur the first time the page
is accessed
9The Source Code
- In Tomcat 3.2.1, you can find the generated Java
and the class files in a subdirectory under
tomcat_home/work.
10Translation
ltH1gtA Random Numberlt/H1gt lt Math.random() gt
11JSP Features
- Standard directives guiding translation of a JSP
page to a servlet - Standard actions in the form of predefined JSP
tags - Script language declarations, scriptlets, and
expressions for including Java (or other
language) fragments that embed dynamic content - A portable tag extension mechanism, for building
tag librarieseffectively extending the JSP
language
12More Details
13Template HTML
- The HTML code that wraps the code is like a
template - Created as an ordinary HTML
- The dynamic parts are created on runtime and are
inserted into the template
14JSP Scripting Elements
- JSP scripting elements let you insert Java code
into the servlet that will be generated from the
JSP page - There are three forms
- Expressions of the form lt expression gt that
are evaluated and inserted into the output, - Scriptlets of the form lt code gt that are
inserted into the servlet's service method, and - Declarations of the form lt! code gt that are
inserted into the body of the servlet class,
outside of any existing methods
15JSP Expressions
- A JSP expression is used to insert Java values
directly into the output - It has the following form
- lt Java Expression gt
- The Java expression is
- evaluated,
- converted to a string, and
- 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
16Predefined Variables
- The following predefined variables can be used
- request, the HttpServletRequest
- response, the HttpServletResponse
- session, the HttpSession associated with the
request (if any) - out, the PrintWriter (a buffered version of type
JspWriter) used to send output to the client
17Examples
- For example, the following shows the date/time
that the page was requested - Current time lt new java.util.Date() gt
- For example, the following shows the hostname
- Your hostname
- lt request.getRemoteHost() gt
18ltHTMLgt ltHEADgt ltTITLEgtJSP Expressionslt/TITLEgt lt/
HEADgt ltBODYgt ltH2gtJSP Expressionslt/H2gt ltULgt ltLIgtCur
rent time lt new java.util.Date() gt ltLIgtYour
hostname lt request.getRemoteHost() gt ltLIgtYour
session ID lt session.getId() gt ltLIgtThe
ltCODEgttestParamlt/CODEgt form parameter lt
request.getParameter("testParam")
gt lt/ULgt lt/BODYgt lt/HTMLgt
19(No Transcript)
20JSP Scriplets
- JSP scriptlets let you insert arbitrary code into
the servlet method that will be built to generate
the page ( _jspService ) - Scriptlets have the following form
- lt Java Code gt
- Scriptlets have access to the same automatically
defined variables as expressions
21Producing Code
- Scriplets produce output HTML by printing into
the out variable - Example
- lt
- String queryData request.getQueryString()
- out.println("Attached GET data " queryData)
- gt
22HTML Code in Scriptlets
- HTML code before and after the scriplets is
converted to print methods
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.println("You
ltBgtwonlt/Bgt the game!") else
out.println("You ltBgtlostlt/Bgt the game!")
23lt foo() gt lt bar() gt
public void _jspService(HttpServletRequest
request,
HttpServletResponse response) throws
ServletException, IOException request.setConten
tType("text/html") HttpSession session
request.getSession(true) JspWriter out
response.getWriter() out.println(foo()) bar()
...
24Example of Using Scriplets (1)
lt!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN"gt ltHTMLgt ltHEADgt ltTITLEgtColor
Testinglt/TITLEgt lt/HEADgt lt String bgColor
request.getParameter("bgColor") boolean
hasExplicitColor if (bgColor ! null)
hasExplicitColor true else
hasExplicitColor false bgColor
"WHITE" gt
25Example of Using Scriplets (2)
ltBODY BGCOLOR"lt bgColor gt"gt ltH2
ALIGN"CENTER"gtColor Testinglt/H2gt lt if
(hasExplicitColor) out.println("You supplied
an explicit background color of " bgColor
".") else out.println("Using default
background color of WHITE. Supply the
bgColor request attribute to try a
standard color, an RRGGBB value, or to see
if your browser supports X11 color
names.") gt lt/BODYgt lt/HTMLgt
26(No Transcript)
27JSP Declaration
- A JSP declaration lets you define methods or
fields that get inserted into the main body of
the servlet class (outside of the service method
processing the request) - It has the following form
- lt! Java Code gt
- Declarations do not produce output
- They are used, for example, to define variables
28Example
- We want to print out 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
- Accesses to page since server reboot
- lt accessCount gt
29Predefined Variables
- As we have seen before, there are variables that
can be used in the code - There are eight automatically defined variables,
sometimes called implicit objects - The available variables are request, response,
out, session, application, config, pageContext,
and page
30request
- This is the HttpServletRequest associated with
the request - It lets you
- look at the request parameters (via
getParameter), - the request type (GET, POST, HEAD, etc.), and
- the incoming HTTP headers (cookies, etc.)
31response
- This is the HttpServletResponse associated with
the response to the client - The output stream is buffered,
- Thus, it is legal to set HTTP status codes and
response headers, even though this is not
permitted in regular servlets once any output has
been sent to the client
32out
- This is the PrintWriter used to send output to
the client - However, in order to make the response object
useful, this is a buffered version of PrintWriter
called JspWriter - Note that you can adjust the buffer size, or even
turn buffering off, through use of the buffer
attribute of the page directive
33session
- This is the HttpSession object associated with
the request - Sessions are created automatically, so this
variable is bound even if there was no incoming
session reference (unless session was turned off
using the session attribute of the page
directive)
34application
- This is the ServletContext as obtained via
getServletConfig().getContext() - Servlets and JSP pages can hold constant data in
the ServletContext object - Getting and setting attributes is with
getAttribute and setAttribute - The ServletContext is shared by all the servlets
in the server
35config
- This is the ServletConfig of the page
36pageContext
- JSP introduced a new class called PageContext
- It encapsulate use of server-specific features
like higher performance JspWriters - The idea is that, if you access the
server-specific features through this class
rather than directly, your code will still run on
"regular" servlet/JSP engines
37page
- This is simply a synonym for this
- page is not very useful in Java codes in JSP
pages - It was created as a placeholder for the time when
the scripting language could be something other
than Java
38JSP Directives
- A JSP directive affects the overall structure of
the servlet class that is created 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"
- attribute2"value2"
- ...
- attributeN"valueN" gt
39Directives
- There are three main types of directive
- page, which lets you do things like
- import classes
- customize the servlet superclass
- include, which lets you
- insert a file into the servlet class at the time
the JSP file is translated into a servlet - taglib directive
- indicates a library of custom tags that the page
can include
40The page Directive
- The page directive lets you define the following
attributes - import"package.class
- lt_at_ page import"java.util." gt
- contentType"MIME-Type"
- lt_at_ page contentType"text/plain" gt
- (it is the same as
- lt response.setContentType("text/plain") gt)
41More Page Directives
- isThreadSafetruefalse
- Normal servlet processing or implementing
SingleThreadModel - sessiontruefalse
- Allowing/disallowing sessions
- buffersizekbnone
- specifies the buffer size for the JspWriter out
- autoflushtruefalse
- Flush buffer when full or throws an exception
when buffer isfull
42And More Directives
- extendspackage.class
- infomessage
- A message for the getServletInfo method
- errorPageurl
- Define a JSP page that handles uncaught
exceptions - isErrorPagetruefalse
- languagejava
43The 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"relative url" gt
44Writing JSP in XML
- We can replace the JSP tags with XML tags that
represent - Expressions
- Scriptles
- Declarations
- Directives
45ltjspexpressiongt Java Expression
lt/jspexpressiongt
lt Java Expression gt
ltjspscriptletgt Code Java lt/jspscriptletgt
lt Code gt
ltjspdeclarationgt Java Declaration
lt/jspdeclarationgt
lt! declaration gt
ltjspdirective.type Attribute value/gt
lt_at_ directive gt
46Actions
- JSP actions use constructs in XML syntax to
control the behavior of the servlet engine - You can
- dynamically insert a file,
- reuse JavaBeans components,
- forward the user to another page, or
- generate HTML for the Java plugin
47Available Actions
- Available actions include
- jspinclude - Include a file at the time the page
is requested - jspuseBean - Find or instantiate a JavaBean
- jspsetProperty - Set the property of a JavaBean
- jspgetProperty - Insert the property of a
JavaBean into the output - jspforward - Forward the requester to a new page
- jspplugin - Generate browser-specific code that
makes an OBJECT or EMBED tag for the Java plugin
48The jspinclude Action
- This action lets you insert files into the page
being generated - The file inserted when page is requested
- The syntax looks like this
- ltjspinclude page"relative URL"
- flush"true" /gt
49The jspforward Action
- Forwards request to another page
- Syntax
- ltjspforward page"relative URL"/gt
- It has a single attribute, page, which should
consist of a relative URL - This could be a static value, or could be
computed at request time - Examples
- ltjspforward page"/utils/errorReporter.jsp" /gt
- ltjspforward page"lt someJavaExpression gt" /gt
50Using Beans
- JavaBeans are reusable software components that
can be manipulated visually in a builder tool - Introspaction analyze how the bean works
- Customization the user can customize the look
of the bean - Events support
- Properties support
- Persistence allowing saving the bean on a
persistent mechanism and loading it
51Some Facts about Beans
- The bean Class should include a constructor with
no arguments - The bean class should not include public
variables (fields) - Access to the attributes of the bean is through
methods that look like - getName / setName for non-boolean fields
- isName / setName for boolean fields
52The jspuseBean Action
- This action lets you load in a JavaBean to be
used in the JSP page - The simplest syntax for specifying that a bean
should be used is - ltjspuseBean id"name
- class"package.class" /gt
53Using a Bean
ltjspuseBean id"name class"package.class" /gt
- Create an object of the given class
- Bind the object to a variable with the given name
54Using a Bean
ltjspuseBean iddb classdbiClasses.WebDatabas
e" /gt
55Using a Bean
ltjspuseBean idhandler classConnectionHandle
r" typeRunnable/gt
56More on Beans
- Creating a Bean with jspuseBean is like creating
an object - The scope of the bean can be beyond the page
where it is declared - Beans are used for resource collaboration
57Getting the Properties of a Bean
- Use jspgetProperty to get a property of a bean
- Use the attributes name and property to get the
requested property
ltjspgetProperty namedb propertylogin /gt
lt db.getLogin() gt
58Setting the Properties of a Bean
- Use jspsetProperty to set a property of a bean
- Use the attributes name, property and value to
set the value to the property
ltjspsetProperty namedb propertylogin
valuesnoopy/gt
lt db.setLogin(snoopy) gt
59Example
package dbiTests public class SimpleBean
private String message"No message specified"
public String getMessage()
return(message) public void
setMessage(String message) this.message
message
60ltHTMLgt ltHEADgt ltTITLEgtReusing JavaBeans in
JSPlt/TITLEgt lt/HEADgt ltBODYgt ltCENTERgt ltTABLE
BORDER5gt ltTRgtltTH CLASS"TITLE"gt Reusing
JavaBeans in JSP lt/TABLEgt lt/CENTERgt ltPgt
ltjspuseBean id"test" classdbiTest.SimpleBean"
/gt ltjspsetProperty name"test"
property"message" value"Hello WWW" /gt
ltH1gtMessage ltIgt ltjspgetProperty name"test"
property"message" /gt lt/Igtlt/H1gt lt/BODYgt
lt/HTMLgt
61Getting the Values from the Request
ltjspsetProperty namedb propertylogin
valuelt request.getParameter(login)gt /gt
62Getting the Parameter Automatically
- If we wand that the value of the parameter
dblogin of the request will be set to the bean db
automatically we can use
ltjspsetProperty namedb propertylogin
paramdblogin /gt
63All Input Parameters
- What will the following do?
ltjspsetProperty namedb property /gt
64Shared Beans
- So far, we assumed that object that were created
using jspuseBean were bound to to the local
variables in the _jspService method - The scope attribute of jspuseBean gives us more
possibilities
65The page Value of scope
- The default value of scope
- The object has a binding to the local variable
- The object is positioned in the PageContext for
the current request - A servlet can get the value by pageCotext.getAttri
bute
66The application Value of scope
- The object has a binding to the local variable
- The object is positioned in the ServletContext
- A servlet can get the value by application.getServ
letCotext().getAttribute - Allows both servlets and JSP pages to work with
the same object - Allows a servlet to create a bean that will be
used in JSP pages
67The session Value of scope
- The object has a binding to the local variable
- The object is positioned in the HttpSession for
the current request - A servlet can get the value by session.getAttribut
e
68The request Value of scope
- The object has a binding to the local variable
- The object is positioned in the ServletRequest
for the current request - A servlet can get the value by request.getAttribut
e
69A Conditional Bean
- The jspuseBean component will create a new bean
only if there is no existing bean with the same
id and scope - If an existing bean is found, it will be bound to
the variable defined by id - Since bean objects are not always created you can
have a java code that is executed only if a new
bean is created
70Example of Conditional Bean
public class AccessCounterBean private String
firstPage private int accessCount 1
public String getFirstPage()
return(firstPage) public void
setFirstPage(String firstPage)
this.firstPage firstPage public int
getAccessCount() return(accessCount)
71Example of Conditional Bean
ltjspuseBean idcounter classAccessCounterBean
" scopeapplication/gt ltjspsetProperty
namecounter propertyfirstPage
valueCurrent Page Name/gt lt/jspuseBeangt
72Comments
- lt-- comment --gt
- A JSP comment
- Ignored by JSP-to-scriptlet translator
- Any embedded JSP scripting elements, directives,
or actions are ignored - lt!-- comment --gt
- An HTML comment
- Passed through to resultant HTML
- Any embedded JSP scripting elements, directives,
or actions are executed normally - / comment / or // comment
- Java comment
- Part of the Java code
73Quoting Conventions
- lt\ - used in template text (static HTML) and in
attributes where you really want lt - \gt - used in scripting elements and in
attributes where you really want gt - \ \ - for using quotes in attributes
- \\ for having \ in an attribute
74Init and Destroy
- JSP pages, like regular servlets, sometimes want
to use init and destroy - Problem the servlet that gets built from the JSP
page might already use init and destroy - Overriding them would cause problems
- Thus, it is illegal to use JSP declarations to
declare init or destroy
75Init and Destroy
- Solution use jspInit and jspDestroy
- The auto-generated servlet is guaranteed to call
these methods from init and destroy - The standard versions of jspInit and jspDestroy
are empty (placeholders for you to override)
76JSP vs. Javascript
- Javascript
- Client side
- Less secure
- Browser Dependent
- Unstable
77JSP vs. ASP
- Active Server Pages (ASP)
- Similarities
- Server side dynamic web page generators
- Share similar syntax lt gt
- Modular programming (e.g. ActiveX, JavaBeans)
- Focus on database connectivity
- Differences
- ASP is a product while JSP is a specification
78JSP vs. ASP (cont.)
- JSP
- Based on Java Technology
- Platform independence
- Unix, AS400, VMS, Windows
- More vendors choice
- ASP
- Microsoft programming languages
- Near Monopoly
79JSP vs. Servlets
- But JSP pages are converted to Servlets? Arent
they the same? - Similarities
- Provide identical results to the end user
- JSP is an additional module to the Servlet Engine
80JSP versus Servlets (cont.)
- Differences
- Servlets HTML in Java code
- HTML code inaccessible to Graphics Designer
- Everything very accessible to Programmer
- JSP Java Code Scriptlets in HTML
- HTML code very accessible to Graphics Designer
- Java code very accessible to Programmer
(Seperating content from appearance)