Download Advanced Servlets: Absolute URLs, GET vs. POST, Session Tracking, and Logging and more Study Guides, Projects, Research Logic in PDF only on Docsity!
CSCI 4208. Univ. of New Orleans Topic 4: Advanced Servlets 1
Developing Advanced Web
Applications
CSCI 4208
Spring 2008
Topic 4
Servlets - II
CSCI 4208. Univ. of New Orleans Topic 4: Advanced Servlets 2
Topics
Absolute vs. Relative URLs
Section 2.5 of textbook (Jackson)
Interacting with Servlet Container
Session Tracking
Maintaining State
GET vs. POST
Error Handling and Logging
CSCI 4208. Univ. of New Orleans Topic 4: Advanced Servlets 3
Absolute URLs
An absolute URL is a complete URL
Contains protocol, hostname (and port) and exact path
to the local resource
E.g. http://localhost:8080/cs4208/bookReview.html
But in many applications you cannot (and/or
should not) hardcode the absolute URLs
The application may be deployed to a host not known
at development time. Port may need to changed, etc.
Note: In servlet code, absolute URLs can always
be generated by using info
From methods on SerlvetRequest and
ServletContext
Or from configuration parameters
CSCI 4208. Univ. of New Orleans Topic 4: Advanced Servlets 4
Relative URLs
In many web applications, relative URLs are used for
linking within the website
Two types of relative URLs
1. Root relative
URL is relative to the ROOT of the web server Has a leading ‘/’ E.g., /index.html
2. “Sibling” relative
URL is relative to the current resource URL doesn’t have a leading ‘/’ E.g., index.html Unix directory path syntax can also be used E.g., ../images/return.gif
CSCI 4208. Univ. of New Orleans Topic 4: Advanced Servlets 5
Base URL
Every relative URL is a shorthand for some
absolute URL
To convert a relative URL to an absolute
URL, a base URL is used
By default the base URL is the doc’s URL with
any query string removed
Aside:
The default base URL can be overridden
By using HTML base element and specifying a
different URL
CSCI 4208. Univ. of New Orleans Topic 4: Advanced Servlets 6
From Sibling Relative URL to
Absolute URL
A sibling relative URL within a document is
converted to an absolute URL by
Taking the doc’s base URL
Removing everything after the final ‘/’
Replacing it with the sibling relative URL
If the sibling relative URL is an empty string,
the absolute URL is the same as the entire
base URL
Including query string
CSCI 4208. Univ. of New Orleans Topic 4: Advanced Servlets 10
Recommendation
Generate and use relative URLs
With root relative URL, try not to hard-code the
name of the web-application
Can get that information from the deployment
descriptor
CSCI 4208. Univ. of New Orleans Topic 4: Advanced Servlets 11
Topics
Absolute vs. Relative URLs
Interacting with Servlet Container
Session Tracking
Maintaining State
GET vs. POST
Error Handling and Logging
CSCI 4208. Univ. of New Orleans Topic 4: Advanced Servlets 12
Initialization Parameters
Sometimes a servlet may need initial
parameters that are outside the compiled code
E.g., database connection information
javax.servlet.ServletConfig object is
used by a Servlet Container to pass
configuration information to a servlet
This object is created by the Servlet Container
and includes information from the web.xml
corresponding to the this particular servlet
CSCI 4208. Univ. of New Orleans Topic 4: Advanced Servlets 13
Providing Initialization Parameters
Initialization parameters can be provided for a
Servlet using the elements init-param ,
param-name and param-values in
web.xml
E.g.,
< servlet>
<servlet-name>Greeting</servlet-name> <servlet-class>GreetingServlet</servlet-class>
< init-param>
<param-name>greeting</param-name> <param-value>Welcome</param-value> </init-param>
CSCI 4208. Univ. of New Orleans Topic 4: Advanced Servlets 14
GreetingServlet.java
public class GreetingServlet extends
HttpServlet {
public void doGet(HttpServletRequest req,
HttpServletResponse res)
throws IOException, ServletException{
String greeting =
getServletConfig().getInitParameter(
"greeting");
CSCI 4208. Univ. of New Orleans Topic 4: Advanced Servlets 15
Application Wide Information
ServletCofig object provides configuration
information for a specific servlet
But a servlet belongs to a particular web application and
can need information about that web application
E.g., database connection information is very likely to be the same for all servlets in the web application
javax.servlet.ServletContext provides support
for this
One ServletContext object per web-application
ServletContext is contained within the
ServletConfig object
getServletConfig().getServletContext() Or simply getServletContext()
CSCI 4208. Univ. of New Orleans Topic 4: Advanced Servlets 19
Topics
Absolute vs. Relative URLs
Interacting with Servlet Container
Session Tracking
HttpSession
How is it done?
Maintaining State
GET vs. POST
Error Handling and Logging
CSCI 4208. Univ. of New Orleans Topic 4: Advanced Servlets 20
Session Tracking: Need
Very few advanced applications are confined to a
single page
A mechanism is needed to track a User through
a site
Recall from Topic 1:
HTTP is a stateless protocol
Not aware of any previous request or response
Not responsible for knowing that repeated requests
are from the same client to the same server
CSCI 4208. Univ. of New Orleans Topic 4: Advanced Servlets 21
Session Tracking in Servlets
The Servlet API provides classes and method
to track sessions
HttpSession object
Created for a client being served by code run in a
Servlet container
Servlet can then bind data to this object
On subsequent requests by the client, the data can
be read or modified
Data item is shared over the lifetime of the session
Session object is destroyed after a certain amount of
inactive time
CSCI 4208. Univ. of New Orleans Topic 4: Advanced Servlets 22
Session Tracking: Example
Get the session from
HttpServletRequest, creating a new
session if it does not exist already
HttpSession thisUser = req.getSession();
Store information in the session object
thisUser.setAttribute(
“currPageNum”, new Integer(59));
When processing a later request, we can
read the value of currPageNum that was
stored earlier
Integer pageNum = (Integer) thisUser.getAttribute( “currPageNum”);
CSCI 4208. Univ. of New Orleans Topic 4: Advanced Servlets 23
Topics
Absolute Vs. Relative URLs
Interacting with Servlet Container
Session Tracking
HttpSession
How is it done?
Maintaining State
GET vs. POST
Error Handling and Logging
CSCI 4208. Univ. of New Orleans Topic 4: Advanced Servlets 24
Session Tracking: How?
When an instance of HttpSession is
created, it is associated with an ID
This generated ID is then sent back as part of
the Http response and is expected back with
each subsequent Http request
Mechanisms for providing Session Tracking:
Cookies
URL Rewriting
Hidden Field
CSCI 4208. Univ. of New Orleans Topic 4: Advanced Servlets 28
Example: CookieServlet
**Cookie[] cookies = request.getCookies(); if(cookies == null){ cookieInfo.append("
cookies EQ null"); Cookie firstCookie = new Cookie("preference", "refresh periodically"); Cookie secondCookie = new Cookie("frequency", "medium to high"); response.addCookie(firstCookie); response.addCookie(secondCookie); }else{ for(int i = 0; i < cookies.length; i++) cookieInfo.append(cookies[i].getName()
- "=“ + cookies[i].getValue()); }**
CSCI 4208. Univ. of New Orleans Topic 4: Advanced Servlets 29
Session Tracking & URL Rewriting
Servlet API provides HttpSession to get
around the statelessness of HTTP
Generally the first choice of a web server is to
use the Cookie mechanism for session
tracking
But if a client does not support cookies or
refuses to accept cookies, web servers can
use an alternate mechanism
URL-rewriting
CSCI 4208. Univ. of New Orleans Topic 4: Advanced Servlets 30
URL Rewriting
HttpServletResponse provides a method
encodeURL(String aURL)
For robust session tracking, all URLs emitted
by a servlet should be run through this
method
Method includes the logic to determine
whether the session ID needs to be encoded
in the URL
If the user's browser does support cookies, the
URLs are simply returned unchanged
If encoding is needed, this method encodes the
specified URL by including the session ID in it
CSCI 4208. Univ. of New Orleans Topic 4: Advanced Servlets 31
URL Rewriting: Example
E.g., Encode a link in a generated page:
out.println(“<A HREF=\””);
out.println(resp.encodeURL(
“/servlet/DepositServlet”);
out.println(“\”>Deposit”);
The HTML would be something like:
<A
HREF=“/servlet/DepositServlet$FA
Deposit”
CSCI 4208. Univ. of New Orleans Topic 4: Advanced Servlets 32
URL Rewriting: Benefit and Cost
As mentioned before for robust session
tracking,all URLs emitted by a Servlet should
be run through this method
There is a cost with URL rewriting
The server has to parse each request URL to get
the session id
By default many web servers have URL
rewriting turned off
You will probably need to modify server
configuration files to enable URL rewriting
CSCI 4208. Univ. of New Orleans Topic 4: Advanced Servlets 33
Hidden Fields
Similar to text fields with one very important difference Hidden field does not show on the page The user thus can't type anything into a hidden field A subsequent request will thus contain whatever value is set for this field in the HTML source document by the previous response Can be used for session tracking <input type="hidden" name=“session_tracker" value=“xyzdsddf"> Servlet adds this HTML code to a generated page before sending the response Servlet gets parameter session_tracker from requests and uses the value to tie a request to previous requests from this client Comment: instead of each servlet doing this, a filter can be used for such functionality We will study filters in a later lecture
CSCI 4208. Univ. of New Orleans Topic 4: Advanced Servlets 37
javax.servlet.ServletContext
One ServletContext object per web-application
Can be obtained by calling:
getServletContext() This is defined on HttpServlet
Storing information in the servlet context
getServletContext().setAttribute( “dbconnection”, dbConn);
Getting information from the servlet context
java.sql.Connection dbConn = (java.sql.Connection) getServletContext().getAttribute( “dbconnection”);
CSCI 4208. Univ. of New Orleans Topic 4: Advanced Servlets 38
Resource Cleanup
Resources may need to be cleaned up when an
HTTP session gets destroyed
E.g., a file was opened for this session and we want
to close the file when the session goes away
In Tomcat, the file conf/web.xml has a
session-timeout element whose value
determines the length of inactivity to cause
session to be destroyed
A session that has been inactive for more than
the set limit will be destroyed
The cause of inactivity may have been that the User
had closed the browser
CSCI 4208. Univ. of New Orleans Topic 4: Advanced Servlets 39
Session Binding & Unbinding
Servlet API includes the interface
javax.servlet.http.HttpSessionBindingList
ener
Objects implement this interface so that they can be
notified when they are being bound or unbound from a
Http Session
valueBound(HttpSesisonBindingEvent)
Raised when a binding occurs due to HttpSession.setAttribute being called to store the object on the session
valueUnbound(HttpSessionBindingEvent)
Raised when an unbinding occurs HttpSession.removeAttribute is used on this object E.g., when the session has timed-out
CSCI 4208. Univ. of New Orleans Topic 4: Advanced Servlets 40
Topics
Absolute Vs. Relative URLs
Interacting with Servlet Container
Session Tracking
Maintaining State
GET vs. POST
Error Handling and Logging
CSCI 4208. Univ. of New Orleans Topic 4: Advanced Servlets 41
GET vs. POST
The processing of GET and POST is very
similar in the servlets
Q: Why use one vs. the other?
A: Base decision on
Amount of data to send
CSCI 4208. Univ. of New Orleans Topic 4: Advanced Servlets 42
GET vs. POST: amount of data
A POST request has a body part
From parameters are sent in the body
Can send a query string of any length
GET request sends query string as part of the
URL
Length of URL is generally limited
The limit is web server dependent
=> For long query string, POST should be used
CSCI 4208. Univ. of New Orleans Topic 4: Advanced Servlets 46
Status Codes
Notice that in our servlet examples, we never
set the status code for HTTP response
The code works because by default the Servlet
container automatically sets the status code to
200/OK
We can explicitly set the code by calling:
res.setStatus(int statusCode)
Note: Mnemonic messages for the most used codes
are defined in HttpServletResponse
E.g., you can (and should) use
res.setStatus(HttpServletResponse.SC_OK
CSCI 4208. Univ. of New Orleans Topic 4: Advanced Servlets 47
Error Handling
In our sample code, we didn’t check for errors
or handle exceptions
In general program must detect errors, catch
exceptions and give a meaningful response to
the User
If the error is a standard HTTP error, e.g., 404,
you should set it as an error on HttpResponse
object and let the browser display the message
res.sendError(
HttpServletResponse.SC_NOT_FOUND,
“Too sleepy, can’t find anything”);
CSCI 4208. Univ. of New Orleans Topic 4: Advanced Servlets 48
Logging
Logging: act of keeping a record of important
information in some serialized form
You have almost certainly used logging in at
least one form
System.out.println
Logging is one way to debug a program
More importantly:
“debugging statements stay with the program;
debugging sessions are transient.”
“The Practice of Programming” Kernighan & Pike
Learning what information to log is an
important issue in software development
CSCI 4208. Univ. of New Orleans Topic 4: Advanced Servlets 49
API’s for Logging
In Servlet API, ServletContext object
provides log() methods
Where the output will be written is specific to the
Servlet Container
I will provide information for Tomcat
If in your Java code, anything written to
System.out will be written to a file in
$CATALINA_HOME/logs/
JDK itself also now has support for logging in
the package
java.util.logging
You may want to use (one of) these API’s for
debugging your programs
CSCI 4208. Univ. of New Orleans Topic 4: Advanced Servlets 50
Summary
The difference between
Absolute and relative URLs
GET and POST
Important parts of the Servlet API
How does the Servlet API overcomes HTTP’s
statelessness?
How can you manage state in your servlets?
How can the servlet interact with the environment?
Using ServletConfig and ServletContext objects