Professional Documents
Culture Documents
Why JSP?
Servlet/CGI approach: server-side code is a program with HTML embedded JavaServer Pages (and PHP/ASP/ColdFusion) approach: serverside code is a document with program embedded
Supports cleaner separation of program logic from presentation Facilitates division of labor between developers and designers
JSP Example
Default namespace is XHTML
JSP Example
Also uses two JSP-defined namespaces
JSP Example
JSP-defined markup (initialization)
JSP Example
Standard XHTML
JSP Example
JSP scriptlet
JSP Example
JSP Example
JSP Example
JSP Example
JSP Example
Used html as root element
Can use HTML-generating tools, such as Mozilla Composer, to create the HTML portions of the document JSP can generate other XML document types as well
JSP Example
JSP Example
Namespaces
JSP (basic elements, normal prefix jsp) Core JSP Standard Tag Library (JSTL) (prefix c)
Tag library: means of adding functionality beyond basic JSP JSTL included as part of the JWSDP 1.3 version of Tomcat JSTL provides a number of useful functions (more later)
JSP Example
JSP Example
JSP elements
directive.page: typical use to set HTTP response header field, as shown (default is text/xml) output: similar to XSLT output element (controls XML and document type declarations) In this example, output element causes XML declaration to be suppressed in the XHTML document produced, and provides all of the content for the document type declaration (i.e., name of root element, public and system identifiers)
JSP Example
JSP Example
JSP Example
Template data: Like XSLT, this is the HTML and character data portion of the document (head start tag through body start tag) Scriptlet: Java code embedded in document
While often used in older (non-XML) JSP pages, we will avoid scriptlet use One use (shown here) is to add comments that will not be output to the generated page
JSP Example
JSP Example
Core tag library supports simple programming
if: conditional
empty: true if variable is non-existent or undefined
set: assignment
application scope means that the variable is accessible by other JSP documents, other users (sessions)
Exceptions provide traceback information for the servlet, not the JSP
The servlets are stored under Tomcat work directory
Body of HTML document generated by the translated servlet would begin with a paragraph saying Hello to the user specified by the username parameter in the request query string
${visits} in template code translates to out.write() of value of variable Core tags (e.g., if) normally translate to a method call
Web Applications
A web application is a collection of resources that are used together to implement some web-based functionality Resources include
Components: servlets (directly-coded or JSPgenerated) Other resources: HTML documents, style sheets, JavaScript, images, non-servlet Java classes, etc.
Web Applications
Sharing data between components of a web application
Tomcat creates one ServletContext object per web application Call to getServletContext() method of a servlet returns the associated ServletContext ServletContext supports setAttribute()/getAttribute() methods
Web Applications
Within Tomcat, all of the files of a simple web app are placed in a directory under webapps
JSP documents can go in the directory itself Hidden files--such as servlet class files--go under a WEB-INF subdirectory (more later)
Once the web app files are all installed, use Tomcat Manager to deploy the app
Dr. Thomas Tran CSI3140 Lecture Notes (based on Dr. Jeffrey Jacksons slides)
Web Applications
Deploying a web app consisting of a single JSP document HelloCounter.jspx:
Create directory webapps/HelloCounter Copy JSP doc to this directory Visit localhost:8080/manager/html Enter HelloCounter in WAR or Directory URL box and click Deploy button
Web Applications
Manager app provides clickable command links for each deployed application:
Stop: web app becomes unavailable (404 returned) Start: web app becomes available again Reload: stop web app, restart with latest versions of files (no need to restart server) Undeploy: stop app and remove all files!
Always keep a copy of app outside webapps
Web Applications
Set parameters of a web application by
Creating a deployment descriptor (XML file) Saving the descriptor as WEB-INF/web.xml
Web Applications
Web Applications
Web Applications
Some examples:
Setting an initial value accessible by application.getInitParameter():
Setting the length of time (in minutes) before a session times out:
Web Applications
Mapping URLs to app components:
Web Applications
There are four URL patterns (from high to low precedence)
Web Applications
Methods on request object for obtaining path information:
Example: /HelloCounter/visitor/test.jsp getContextPath(): returns /HelloCounter getServletPath(): returns /visitor getPathInfo(): returns /test.jsp
As (part of) the value of certain JSP attributes: evaluates to data type that depends on context
Dr. Thomas Tran CSI3140 Lecture Notes (based on Dr. Jeffrey Jacksons slides)
Arithmetic:
+, - (binary and unary), * /, % (or div, mod)
empty: true if arg is null or empty string/array/Map/Collection Conditional: ? : Array access: [ ] (or object notation) Parentheses for grouping
page: JSP implicit object representing the servlet itself JSP objects page, request, session, and application all have getAttribute() and setAttribute() methods
These objects store EL scoped variables (e.g., visits)
and if EL scoped variable index can be cast to integer then can access elements of aVar by
aVar[index] aVar.index
JSP Markup
Three types of markup elements:
Scripting
Ex: scriptlet Inserts Java code into servlet
Directive
Ex: directive.page Instructs JSP translator
Action
Standard: provided by JSP itself Custom: provided by a tag library such as JSTL
JSP Markup
Two JSPX directives
directive.page; some attributes:
contentType session: false to turn off use of session object errorPage: relative URL of application resource to be requested if an uncaught exception occurs in this JSP document isErrorPage: true to access EL implicit exception object
JSP Markup
JSTL is divided into several functional areas, each with its own namespace:
Namespace prefix is
JSP Markup
JSP Markup
Common variables:
var
Represents name of a scoped variable that is assigned to by the action Must be a string literal, not an EL expression
scope
Specifies scope of scoped variable as one of the literals page, request, session, or application
JSP Markup
set action
Setting (and creating) a scoped variable
Setting/creating an element of Map
Map Key
Actually, this fails at run time in JWSDP 1.3 (which treats EL implicit object Maps as read-only)
JSP Markup
remove action
Only attributes are var and scope
Removes reference to the specified scoped variable from the scope object <c:remove var=visits scope=application />
JSP Markup
out action
Normally used to write a string to the out JSP implicit object Automatically escapes XML special characters
If value is null, output is empty string
Override by specifying a value for the default attribute
JSP Markup
url action
value attribute is a URL to be written to the out JSP implicit object URLs beginning with / are assumed relative to context path param elements can be used to define parameters that will be URL encoded
JSP Markup
Alternative to the value attribute (set and param elements)
If element has content, this is processed to produce a String used for value Even out element will produce string, not write to the out object
Assigns value of variable messy (XML escaped) to scoped variable clean
JSP Markup
if action
General form includes scoped variable to receive test value
Assigned Boolean value of test attribute
The above markup creates (or sets, if variable already exists) a scoped variable named testResult in the default page scope and, if the condition is true, sends the contained character data to the out object
JSP Markup
choose action <c:choose> <c:when test=${visits eq 1}> Hi!</c:when> <c:when test=${visits eq 2}> Welcome back!</c:when> <c:otherwise> Youre a regular!</c:otherwise> </c:choose>
JSP Markup
forEach action
Used to increment a variable (writes 2, 4, 6, 8 to the out object):
Used to iterate over a data structure (iterates through header EL implicit object and outputs a list containing one item for each header field in the HTTP request being processed):
JSP Markup
forEach action
Can iterate over array, Map, Collection, Iterator, Enumeration Elements of Map are Map.Entry, which support key and value EL properties:
JavaBeans Classes
JSTL Core actions are designed to be used for simple, presentation-oriented programming tasks More sophisticated programming tasks should still be performed with a language such as Java JavaBeans technology allows a JSP document to call Java methods
JavaBeans Classes
Example
JavaBeans Classes
Using a JavaBeans class in JSP
JavaBeans Classes
Using a JavaBeans class as shown:
Class must have a default (no-argument) constructor to be instantiated by useBean
Automatically supplied by Java in this example
JavaBeans Classes
Simple property design patterns
Two types: getter and setter
Both require that the method be public getter:
no arguments returns a value (i.e., cannot be void) name begins with get (or is, if return type is boolean) followed by upper case letter
setter:
one argument (same type as getter return value) Void (i.e., must not return a value) name begins with set followed by upper case letter
Dr. Thomas Tran CSI3140 Lecture Notes (based on Dr. Jeffrey Jacksons slides)
JavaBeans Classes
EL calls simple property design method in response to access of bean property:
Attempt to read property generates call to associated get/is method (or error if none exists) Attempt to assign value to property generates call to associated set method (or error)
JavaBeans Classes
Example setter method
JavaBeans Classes
Simple property design pattern methods associate bean properties with beans
Name of bean property obtained by removing get/is/set method prefix and following the rule:
If remaining name begins with two or more upper case letters, bean property name is remaining name: setAValue() AValue If remaining name begins with a single upper case letter, bean property name is remaining name with this letter converted to lower case: getWelcome() welcome
Instantiating Beans
Beans can be instantiated by a servlet and made available to JSP via scope objects
Servlet
Instantiating Beans
useBean only instantiates a bean if one does not already exist, can optionally perform initialization
Using Beans
Example: mortgage calculation
Using Beans
Tag Libraries
Wouldnt it be nicer to write the mortgage app as
Tag Libraries
Tag Libraries
Place custom tag definition in a tag file having the name of the custom action
mortgage.tagx
Place tag file in a tag library (e.g., directory containing tag files)
/WEB-INF/tags
MVC
Many web apps are based on the ModelView-Controller (MVC) architecture pattern
Model Components
View
MVC
Typical JSP implementation of MVC
MVC
Forwarding an HTTP request from a servlet to another component:
By URL
Ex: /HelloCounter.jspx
By name
MVC
MVC
How does the controller know which component to forward to?
getPathInfo() value of URLs can be used Example:
servlet mapping pattern in web.xml: URL ends with: getPathInfo() returns:
MVC
JSP include action (not the same as the include directive!)
Execute specified component and include its output in place of the include element
MVC
Adding parameters to the request object seen by an included component:
request object seen by navbar.jspx will include parameter named currentPage with value home