Title: EE448: Server-Side Development
1EE448 Server-Side Development
Lecturer David Molloy Time Tuesdays
3pm-5pm Notes http//wiki.eeng.dcu.ie/ee448
Mailing List ee448_at_list.dcu.ie
2Session Tracking
- Session tracking is the capability of the server
to maintain the current - state of a single clients sequential requests
- HTTP is stateless -gt how do you keep track of
client request sequences? - Sites such as those with shopping carts need
this capability - Why not simply use the clients IP address as
identification? Xterm, - proxy servers, multiple browsers etc.
- Therefore, we get client to introduce itself as
it makes each request. - Client provides a unique identifier that lets
the server identify it. - Several different ways of managing session
tracking - - User Authorization
- - Hidden Form Fields
- - URL Rewriting
- - Persistent Cookies
- - Session Tracking API
3User Authorization
- Most application/web servers have some built
in-system for user - authorization
- Apache user authorization used to access module
notes - Tomcat provides functionality to require clients
to login - Example Tomcat Manager Application
- String name req.getRemoteUser() // after
authorization
Easy to Implement Works if user accesses the
site from an alternate machine or browser
- Users must pre-register for A/C
- Users must always log in each time
- Cant simultaneously maintain more
- than one session at same site
- Unsuitable for anonymous session
- tracking
4Hidden Form Fields
- One of the simplest methods for session tracking
- Use standard form fields, which are not
displayed to the client - Parameters passed back to server, when form is
submitted - ltINPUT TYPEhidden NAME"user" value"molloyda"gt
- No different between a hidden and visible field
(at server end!) - Work through example hidden_example.html
- http//localhost8080/student/hidden_example.ht
ml - We pass information from Form to Form -gt
effectively session tracking - Shopping cart this way would pass user id,
quantities and item ids - from form to form
5Hidden Form Fields
Advantages
Easy to Implement Supported by all popular
browsers Users need not log in (server can
generate unique IDs)
Disadvantages
- As quantity of information increases, process
becomes tedious - (unless persistent information is kept on
server, and ID only passed) - Only functions for series of forms (static pages
break the process) - Browser shutdown/changing will break the process
6URL ReWriting
- Every local URL the user might click is
dynamically modified, or - rewritten to include extra information
- Typically, only a unique session ID is passed
(256 characters max) - Different ways of passing the extra information
- Original http//serverport/context/servle
t/ServletName - http//serverport/context/servlet/ServletN
ame/ABCD1234 (path) - http//serverport/context/servlet/ServletN
ame?sessionidABCD1234 - (parameter)
- Path information method works for both GET and
POST - Extra Parameter method does not work for POST
method - Work through
7URL Rewriting
Advantages
Easy to Implement Supported by all popular
browsers Users need not log in (server can
generate unique IDs) URL rewriting works for
all dynamically created documents (not just
forms!)
Disadvantages
- Only small quantities of information can be
rewritten into URLs - (therefore would need server-side persistence)
- Typically, URL rewriting does not work for
static documents - Browser shutdown breaks the process
- Can be very tedious and need to be careful to
find all links etc.
8Persistent/Non Persistent Cookies
- Cookie a simple piece of information stored on
the client, on behalf - of the server
- When a browser receives a cookie, it saves the
cookie on the local hard - drive. Expiry for the cookie can be set -gt
otherwise deleted at - browser shutdown
- Each subsequent visit to the same site, browser
sends cookie back to - the server with each request
- Cookie can be used to store a user ID
- Cookies -gt Security Issues? Few k bytes
non-executable - Cookies not part of original HTTP specification
-gt introducted in - Netscape and have become a de-facto standard
9Persistent/Non-Persistent Cookies
- Servlet API provides javax.servlet.http.Cookie
for using cookies - public Cookie (String name, String value)
- public void HttpServletResponse.addCookie(Coo
kie cookie) - Example
- Cookie cookie new Cookie("userid",
"david_molloy832") - cookie.setMaxAge(7200) // 2 hour expiry
- res.addCookie(cookie)
- Servlet retrieves cookies by calling the
getCookies() method - Cookie cookies req.getCookies()
- if (cookies ! null)
- for (int i0 ilt cookies.length i)
- String name cookiesi.getName()
- String value cookiesi.getValue()
-
-
10Persistent Cookies
Advantages
Efficient and simple way of session tracking
Exist even if browsers and/or servers are
shutdown/restarted Users need not log on
(server can generate Ids) Works for all
documents/pages even static HTML Cookes are
customizable and powerful
Disadvantages
- Major problem is that clients sometimes
configure browsers to - refuse cookies (for security concerns)
- If client refuses cookies, you must fall back on
another solution
11Session Tracking API
- Fortunately, the Servlet API has built-in
support for session tracking - Session tracking should be supported by any web
server that - supports servlets
- To create a new session, you use the
HttpServletRequest objects - getSession() method
- public HttpSession HttpServletRequest.getSessi
on(boolean create) -
- Eg.
- HttpSession session req.getSession(true)
- Method returns the current session associated
with the user making - the request.
- If the user has no current valid session, this
method creates one - if create is set as true, or returns null if
create is false
12Session Tracking API
- HttpSession object has five methods we are
concerned with - - public void setAttribute(String name, Object
value) - Binds a name/value pair to store in the
current session - If the name exists, then it is replaced
- Note You can store an object, rather than
just a String! - - public Object getAttribute(String name)
- Used to get an object stored in the session
- - public Enumeration getAttributeNames()
- Returns an Enumeration of all the current
bound names - stored in the session
- - public void removeAttribute(String name)
- Allows the removal of an object from the
session - - public void invalidate()
- Can manually invalidate their session and
all information
13Session Tracking API
- Demonstrate the SessionCount servlet
- Sessions have a limited lifespan (purposefully!)
- Automatic or manual invalidation (such as
logouts) - When a user accesses a site, that user is
assigned a new HttpSession - object and a unique session ID.
- Session ID is unique and identifies the user
- The session ID is saved on the client in a
cookie or sent as part of a - rewritten URL
- Every server that supports servlets should
implement at least - cookie-based session tracking (using
persistent cookies) - Most servers support session tracking based on
URL rewriting also
14Session Tracking API
Advantages
Very efficient and simple way to implement
session tracking Session information can
persist (server specific) even with server
shutdown/restart Users need not log on (server
generates unique IDs) Works for all
documents/pages, including static HTML
Standardized and included in J2EE Sessions can
be set to time-out at user configurable times
Objects stored rather than just strings
Disadvantages
- Restricted to one browser and tracking lost if
browser shuts down - or crashes
- - Slightly more difficult if clients have cookies
disabled
15JavaServer Pages (JSPs)
- Allow web developers and designers to develop
and maintain - platform-independent, dynamic web pages for
business systems - User interface is seperated from content
generation - Designers can alter overall page layout without
altering the - underlying dynamic content
- JSPs make use of XML-like tags and scriptlets
written in Java - to generate dynamic content
- JSP like an inside-out servlet!
- Work through Hello World example
16JavaServer Pages (JSPs)
- Hello World Example
- ltHTMLgt
- ltHEADgt
- ltTITLEgtJSP Hello World Examplelt/TITLEgt
- lt/HEADgt
- ltBODYgt
- ltH1gt
- lt out.println("Hello World!") gt
- lt/H1gt
- lt/BODYgt
- lt/HTMLgt
17Behind the Scenes
- JSP page is executed by a JSP engine/container,
such as Tomcat - JSP is actually just a servlet that is mapped to
.jsp - JSP Container receives requests to a JSP and
generates response - When server receives a request it recognises the
.jsp extension - and begins special handling
- First time JSP is requested, it is compiled into
a servlet object - and stored in memory -gt output of servlet sent
back to user -
18Behind the Scenes
- Subsequent calls to the JSP in the server cache
increases the - speed of response
- First call to JSP includes the time necessary
for the server to - create and compile the background servlet
- If the .jsp file has not changed since previous
request, the - server invokes the previously compiled servlet
object - Provide an example of a JSP error
19Web Application Structure
- JSP pages share the Write Once, Run Anywhere
characteristic - of Java technology -gt typically packaged
within the WAR
20Features of JSP Pages
- Java Based benefit from all of the Java
language benefits - Reusable - O/S, platform independent, can write
JSPs as components - and reuse in different ways for different
functionality - Seperation of Business Logic and Presentation
web designers can - edit and work on HTML while leaving dynamic
content alone - Large Community Support JSPs are based on a
broad spectrum of - industry input and support
- Platform Independent write once, run anywhere
- Ease of Development non-programmers can use
simple JSP specific - code for simple tasks, especially by using
JavaBeans - Portability JSPs are part of the Web
Application Structure, so can be - ported easily to alternate application servers
21JSPs JavaBeans
- JavaBeans is a portable, platform-independent
component model - written in Java
- JavaBeans are small, reusable, software
components - They deliver functionality to various
applications that need such - functionality
- A JavaBean component can be run anywhere
- Eg. On a client within an AWT component or
within a JSP on a server - JavaBeans are based on the concept of
components, but are not - regarded as such by J2EE (it recognises
EJBs) - JavaBeans are intraprocess components that live
at one location, - such as GUI components, buttons, tables etc.
small grained - application pieces
- Enterprise JavaBeans are interprocess components
that live in
22JavaBeans Examples
- GUI software components such as push buttons or
more complicated - like spreadsheets
- Individual components can be nested and
arbitrarily complex - Eg. A calculator JavaBean could be built from
button JavaBeans etc.
23Sample JavaBean
package dave public class SimpleBean
private String message "No message
specified" public String getMessage()
return(message) public void
setMessage(String message) this.message
message
24JSP using JavaBean
- JavaBean has no main method. To use it we use
the ltjspuseBeangt - tag, as follows
- ltHTMLgt
- ltHEADgt
- ltTITLEgtReusing JavaBeans in JSPlt/TITLEgt
- lt/HEADgt
- ltBODYgt
- ltCENTERgt
- ltjspuseBean id"test" class"dave.SimpleBean"
/gt - ltjspsetProperty name"test" property"message"
value"Hello World!" /gt ltH1gtMessage
ltjspgetProperty name"test" property"message"
/gt lt/H1gt - lt/CENTERgt
- lt/BODYgt
- lt/HTMLgt
25JSP Syntax
- HTML Comments
- lt!-- This is a comment --gt
- Hidden Comments
- lt-- This is a comment not visible to the client
--gt - JSP Directives
- Used to define and set attributes that apply
to the entire JSP page -
26JSP Syntax
- 1. include Directive
- Used to instruct the JSP container to insert
text into a JSP page at - translation time
- Included file can be a HTML file, JSP file, text
file, or a Java code file - lt_at_ include filefileName gt
- eg.
- lt_at_ include fileDateTime.jsp gt
- Work through example DateTime.jsp /
JSPInclude.jsp -
27JSP Syntax
- 2. page Directive
- Page directive is used to define one or more
attributes for the whole - JSP page.
- Can be placed anywhere in the JSP file and still
apply - There are a number of separate page directive
attributes
- import specifies in a comma-seperated list, the
Java - packages that the JSP file should import
- lt_at_ page importjava.util., java.sql.
gt - session can be set to true if the client must
join a session - in order to use the JSP page
- lt_at_ page sessiontrue gt
28- contentType defines the MIME type for the
response. Can - use any valid types supported by the JSP
container. - Defaults to text/html
- lt_at_ page contentTypetext/html gt
- extends the fully qualified name of the
superclass of this - JSP
- lt_at_ page extendsClassName gt
- languageScripting Language
- Multiple scripting languages may be used in
JSP files if - supported. The default value is Java.
29- 3. taglib Directive
- Taglib directive supported since JSP Version 1.1
- Allows JSP authors to define their own tags
- lt_at_ taglib gt directive declares that the JSP
file uses custom tags, - names the tag library that defines them and
specifies their prefix - Not concerned with taglib any further in this
module
30Scripting Elements
- JSP scripting elements allow Java code to be
inserted into the - servlet that will be generated from the
defined JSP page - 3 types of scripting elements
- Declarations
- Scriptlets
- Expressions
31Declarations
- JSP declaration allows definition of methods or
variables - Declared variables and methods have class scope
and are available - throughout the JSP page
- Variable declarations must be made before you
use them in your - JSP file
- Syntax lt! Declaration gt
- Examples
lt! String testString Hello World! gt lt!
int x,y,z gt lt! int count 0 gt
32Scriptlets
- Scriptlets provide the ability to directly
insert code into an HTML - document.
- Scriptlets can contain any code that is valid
based on the language - specified in the language directive
- Java code in our module only
- A scriptlet is a block of Java code embedded in
the service() method - of a compiled servlet
- -gt The code is executed on every clients
request for the JSP - Any number of scriptlets can appear within a JSP
page - Syntax
- lt javacode gt
33Scriptlets
Eg. ltHTMLgt ltHEADgt ltTITLEgtJSP Scriptlet
Examplelt/TITLEgt lt/HEADgt ltBODYgt lt
out.println("Your address is "
request.getRemoteAddr()) gt lt/BODYgt lt/HTMLgt
- View the output in Scriptlet.jsp
34Scriptlets
- There are four implicit variables automatically
available to a JSP file - 1. request reference to the HttpServletRequest
object - 2. response reference to the
HttpServletResponse object - 3. in reference to the BufferedReader object
that is part of - the client request
- 4. out reference to the PrintWriter object
sent to the client - Allows us in particular to handle client
interaction
35Scriptlets
- Example of form interaction
ltHTMLgt ltHEADgt ltTITLEgtJSP Form Examplelt/TITLEgt
lt/HEADgt ltBODYgt lt out.println("Your value for
parameter A " request.getParameter("a"))
out.println("ltBRgtYour value for parameter B
" request.getParameter("b")) gt lt/BODYgt
lt/HTMLgt
- Demonstrate SimpleForm.jsp w/o/with parameters
36Expressions
- Expression element contains an expression that
is valid in the - scripting language used
- They are like single-line scriptlets
- An expression is a tag, that will be replaced by
the value of the - evaluated expression
- Value is evaluated, converted to a string, and
inserted where the - expression occurs in the JSP file
- Syntax
- lt expression gt
- Example
The current time is lt new java.util.Date() gt
Your IP address is lt request.getRemoteAddr()
gt ltnumber1 " multiplied by " number2 "
gives " number1number2gt
37Examples
- Work through examples from notes
JSP Database Connectivity
- JSP applications like servlets connect to
databases using JDBC - Covered later in the module