Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Topic 6 Servlets and JSPS: Ict337 Advanced Software Development Murdoch University Topic 6

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 51

ICT337 Advanced Software Development

Murdoch University Topic 6

Topic 6
Servlets and JSPs

 What are servlets?

 Why server side programming?

 HTTP Basics

 CGI versus servlets

 How web servers handle servlets

 Session tracking

 Servlet output

 Guidelines for servlet-driven webs

 What are JSPs?

 How web servers handle JSPs

Topic6.doc Page 1
ICT337 Advanced Software Development
Murdoch University Topic 6

What are servlets?


Servlets are Java-based web server extension programs.
They are the java equivalent of native web server
extension technologies, such as Microsoft’s ASP (Active
Server Page) and Netscape’s NSAPI. The main
differences are:
 The servlet API is a standard Java extension and is
therefore portable and platform-neutral.
 Servlets are secure, since they operate within the
context of a security manager, similar to applets.
 The servlet API is vastly easier to use than
comparable proprietary native APIs.
Servlets are sometimes referred to as the server-side
applets.
The Java servlet API provides a highly scalable model
for adding functionality to web servers.
A servlet runs as a thread within the context of the web
server’s Java virtual machine.

Topic6.doc Page 2
ICT337 Advanced Software Development
Murdoch University Topic 6

Why server side programming?


Most enterprise applications need to provide customers
the freedom to
o browse catalogue
o place orders
o track account and transaction status

While applets are good at enhancing the look and feel of


a web page, they are inadequate for conducting business
(eCommerce), where programs are required to run on the
server and to access databases and perform complex
transaction processing.

HTTP Basics
Servlets use the HTTP protocol, so a basic understanding
of the protocol is assumed when using servlets.
Requests, Responses, and Headers
 HTTP is a simple, stateless protocol. A
client, such as a web browser, makes a
request, the web server responds, and
the transaction is done.
 When the client sends a request, the first
thing it specifies is an HTTP command,
called a method, that tells the server the
type of action it wants performed.

Topic6.doc Page 3
ICT337 Advanced Software Development
Murdoch University Topic 6

 This first line of the request also specifies


the address of a document (a URL) and
the version of the
HTTP protocol it is using. For example:
GET /intro.html HTTP/1.0

 This request uses the GET method to ask


for the document named intro.html, using
HTTP Version 1.0.
 After sending the request, the client can
send optional header information to tell
the server extra information about the
request, such as what software the client
is running and what content types it
understands.
 This information doesn’t directly pertain
to what was requested, but it could be
used by the server in generating its
response. Here are some sample request
headers:
User-Agent: Mozilla/4.0 (compatible; MSIE
4.0; Windows 95)
Accept: image/gif, image/jpeg, text/*, */*

 The User-Agent header provides


information about the client software,
while the Accept header specifies the
media (MIME) types that the client prefers
to accept.

Topic6.doc Page 4
ICT337 Advanced Software Development
Murdoch University Topic 6

 After the client sends the request, the


server processes it and sends back a
response. The first line of the response is
a status line that specifies the version of
the HTTP protocol the server is using, a
status code, and a description of the
status code.
 For example:

HTTP/1.0 200 OK

 This status line includes a status code of


200, which indicates that the request was
successful, hence the description “OK”.
Another common status code is 404, with
the description “Not Found”—as you can
guess, this means that the requested
document was not found.

Topic6.doc Page 5
ICT337 Advanced Software Development
Murdoch University Topic 6

GET and POST methods


The GET and POST methods are used to get information
and upload information to the webserver respectively.
GET actually has the ability to pass information to
the server and because of this is often used
incorrectly. Many servers will limit the size of the url
for a GET request to only 240 characters.
POST is used for sending (posting) information to the
server. It generally has an unlimited length.
GET and POST are generally the only methods we will
be dealing with in this unit, and generally speaking, are
the only two methods most developers need.

Other methods
 In addition to GET and POST, there are
several other lesser-used HTTP methods.
 There’s the HEAD method, which is sent
by a client when it wants to see only the
headers of the response, to determine the
document’s size, modification time, or
general availability.
 There’s also PUT, to place documents
directly on the server, and DELETE, to do
just the opposite. These last two aren’t
widely supported due to complicated
policy issues.

Topic6.doc Page 6
ICT337 Advanced Software Development
Murdoch University Topic 6

 The TRACE method is used as a


debugging aid—it returns to the client the
exact contents of its request.
 Finally, the OPTIONS method can be used
to ask the server which methods it
supports or what options are available for
a particular resource on the server.

CGI versus servlets


Server extension APIs, including the Java servlet API and
CGI, share the request/response model of HTTP (since
they operate within the context of an HTTP request). In
this model,
 an incoming request has an environment context and
an associated input stream, and
 An output stream for results.
It is up to the application how to parse the input stream
and format the output stream.
Servlets are used mostly in high-performance
applications, in which the overhead of a CGI-based
solution was unacceptable. CGI programs have the
following drawbacks:
 There is a great deal of overhead in servicing a CGI
request.
 It is difficult to implement a service that maintains

Topic6.doc Page 7
ICT337 Advanced Software Development
Murdoch University Topic 6

persistent connections to other services.


These drawbacks are all overcome by servlets.
In addition, servlets can handle a large volume of
requests (because the footprint of the VM process is
shared by all servlets). Even the servlet object instance
itself is shared between multiple invocations of the same
servlet (thus provide persistence).
Servlets thus have advantages over alternatives in
stability, scalability and performance, persistence.
How web servers handle HTTP requests for servlets

1. Client issues an HTTP request, which includes the


reserved folder name /servlet in the URL
2. web server intercepts the request, retrieves the class
name (appears after the /servlet in the URL). The

Topic6.doc Page 8
ICT337 Advanced Software Development
Murdoch University Topic 6

web server passes objects encapsulating the HTTP


request and a response object to the servlet
3. the servlet can interrogate the request to get
parameters and other info about the request and its
source. It can also call other classes loaded or
available on the web server
4. the servlet can also optionally communicate with
database management software or another server
5. after processing and data gathering, the servlet
creates an HTML document by writing to an output
stream acquired from the response object (see 2
above)
6. the web server redirects the output from the servlet
to the client

Topic6.doc Page 9
ICT337 Advanced Software Development
Murdoch University Topic 6

HTTP request types in servlets


The GET and POST requests are to be handled by the
doGet and doPost methods of your servlet class that
extends the abstract HttpServlet class. These methods
are automatically called by the HttpServlet class’s
service method, which is called when a request arrives
at the server. The method service performs the
following steps in order:
o determines the request type
o calls the appropriate method (doGet or doPost)

There is no need for you to call the service method in


your servlets.

Every call to doGet and doPost for an HttpServlet


receives
o an object that implements the interface
HttpServletRequest. This object contains the
request from the client. A variety of methods are
available in this interface and the ServletRequest
interface (super-interface of
HttpServletRequest) to enable the servlet to
process the client’s request, egs
 getContextPath()
 Cookie[] getCookie()

Topic6.doc Page 10
ICT337 Advanced Software Development
Murdoch University Topic 6

 HTTPSession getSession()
 String getParameter(String name)

o an object that implements the interface


HttpServletResponse. The web server that
executes the servlet creates an
HttpServletResponse object. The web server
passes the HttpServletResponse object to the
servlet’s service method (which, in turn, passes it
to doGet or doPost). This object contains the
response to the client. A variety of methods are
available in this interface and the
ServletResponse (super-interface of
HttpServletResponse) to formulate the response
to the client, egs
 ServletOutputStream getOutputStream()
 PrintWriter getWriter()
 void setContentType(String type)

Apart from the doGet and doPost methods, the abstract


class HttpServlet also provides methods such as
doDelete (for client to remove documents from the
server) and doPut (for client to place documents onto the
server).

Servlet example 1: HelloWorld

Topic6.doc Page 11
ICT337 Advanced Software Development
Murdoch University Topic 6

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class HelloWorld extends HttpServlet


{
public void doGet(HttpServletRequest req,
HttpServletResponse res)throws ServletException,
IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<HTML>");
out.println("<HEAD><TITLE>Hello
world</TITLE></HEAD>");
out.println("<BODY>");
out.println("<BIG>Hello World</BIG>");
out.println("</BODY></HTML>");
} //doGet
}

Notes:
1. We import the necessary classes,
javax.servlet.* for servlets and java.io
for the printwriter.
2. We inherit from HttpServlet to make the
class a servlet.
3. We overload the doGet method to provide a
starting point for processing. You can
think of the doGet or doPost method as
your main method.
4. The doGet method has two parameters, a
HttpServletRequest, and a
HttpServletResponse. The
HttpServletRequest object holds the http
protocol request from the client,

Topic6.doc Page 12
ICT337 Advanced Software Development
Murdoch University Topic 6

including all passed parameters, headers,


etc. The HttpServletResponse object will
be used to send a HTTP protocol response
back to the client.
5. We get the writer of the
HttpServletResponse object and write the
response directly to it’s output stream.

Servlet example 2: TodayServlet


import java.io.*;
import java.util.Date;
import javax.servlet.*;
import javax.servlet.http.*;

public class TodayServlet extends HttpServlet {

public void doGet(


turn off HttpServletRequest request,
page HttpServletResponse response)
caching throws IOException, ServletException {
response.setContentType( "text/html" );
response.setHeader( "Pragma:", "no cache" );
response.setHeader( "Cache-Control", "no cache");
response.setHeader( "Expires","0" );

PrintWriter out = response.getWriter();


out.println( "<HTML>" );
out.println( "<HEAD>" );
out.println( "<TITLE>Today</TITLE>" );
out.println( "</HEAD>" );
out.println( "<BODY>" );
out.println( "<Hl>The current date and time
is: </Hl>" );
Date today = new Date();

Topic6.doc Page 13
ICT337 Advanced Software Development
Murdoch University Topic 6

out.println( "<p>" + today + "</p>" );


out.flush();
out.println( "</BODY>" );
out.println( "</HTML>" );
}
}

In this unit I recommend using Sun ONE with TOMCAT


to handle the development (and deployment) of servlets.
See the handout in the topic 6 folder of the ftp site. If you
follow the instructions then you will find it more
convenient to just cut and paste from the above code into
the servlet template.

Tomcat is a servlet container and JavaServer Pages


implementation. It may be used stand alone or in
conjunction with other web servers, eg. Apache (version
1.3 or later); Microsoft Internet Information Server
(version 4.0 or later).
TOMCAT by itself is available (free) from
http://java.sun.com.

If you are NOT using Sun ONE then you need to compile
(as usual) the servlet, install a servlet container (like
TOMCAT), configure the container appropriately and put
the servlet.class in the right directory structure for the
container. (Sun ONE does all that for you).

The handout also explains how a client accesses the


servlet.

Topic6.doc Page 14
ICT337 Advanced Software Development
Murdoch University Topic 6
Servet example 3: HTTPPostServlet
The example above is very simple: it shows the use of the doGet method. In the
example, the argument request (of type HttpServletRequest) is not used in the
method body. Below is a more complex example.

// A simple survey servlet


import javax.servlet.*;
import javax.servlet.http.*;
import java.text.*;
import java.io.*;
import java.util.*;

public class HTTPPostServlet extends HttpServlet { Like the doGet


method, the
//all threads access this instance variable doPost method
private String animalNames[] = has the same two
arguments
{ "dog", "cat", "bird", "snake", "none" };

public void doPost( HttpServletRequest request,


HttpServletResponse response )
throws ServletException, IOException
{ File survey.txt resides on the
int animals[] = null, total = 0; server.

Topic6.doc Page 15
ICT337 Advanced Software Development
Murdoch University Topic 6
File f = new File( "survey.txt" );

if ( f.exists() ) {
// Determine # of survey responses so far
try {
ObjectInputStream input = new ObjectInputStream(
new FileInputStream( f ) );
If the file survey.txt exists
animals = (int []) input.readObject(); then open it and read an array of
input.close(); // close stream count (int array animals) and
computes the value for the
variable total. Note:
for ( int i = 0; i < animals.length; ++i )
variable total contains the
total += animals[ i ];
total number of survey
} responses
catch( ClassNotFoundException cnfe ) {
cnfe.printStackTrace();
} If the file does not exist then
} create the array animals (by
else default, all elements of the array
animals = new int[ 5 ]; will have the value 0

// read current survey response


String value = request.getParameter( "animal" );
++total; // update total of all responses

Topic6.doc Page 16
ICT337 Advanced Software Development
Murdoch University Topic 6
// determine which was selected and update its total
for ( int i = 0; i < animalNames.length; ++i )
If the user has selected the i-th
if ( value.equals( animalNames[ i ] ) )
animal as his favourite animal then
++animals[ i ]; increase the counter for that animal
(indicated by the array index i)
// write updated totals out to disk
ObjectOutputStream output = new ObjectOutputStream(
new FileOutputStream( f ) );

output.writeObject( animals );
output.flush();
output.close();

// Calculate percentages
double percentages[] = new double[ animals.length ];

for ( int i = 0; i < percentages.length; ++i )


percentages[ i ] = 100.0 * animals[ i ] / total;

// send a thank you message to client


response.setContentType( "text/html" ); // content type

PrintWriter responseOutput = response.getWriter();


StringBuffer buf = new StringBuffer();
buf.append( "<html>\n" );

Topic6.doc Page 17
ICT337 Advanced Software Development
Murdoch University Topic 6
buf.append( "<title>Thank you!</title>\n" );
buf.append( "Thank you for participating.\n" );
buf.append( "<BR>Results:\n<PRE>" );

DecimalFormat twoDigits = new DecimalFormat( "#0.00" );


for ( int i = 0; i < percentages.length; ++i ) {
buf.append( "<BR>" );
buf.append( animalNames[ i ] );
buf.append( ": " );
buf.append( twoDigits.format( percentages[ i ] ) );
buf.append( "% responses: " );
buf.append( animals[ i ] );
buf.append( "\n" );
}

buf.append( "\n<BR><BR>Total responses: " );


buf.append( total );
buf.append( "</PRE>\n</html>" );

responseOutput.println( buf.toString() );
responseOutput.close();
}
}

Topic6.doc Page 18
ICT337 Advanced Software Development
Murdoch University Topic 6
The associated HTML file is:
<HTML>
<HEAD>
<TITLE>Servlet HTTP Post Example</TITLE>
</HEAD>

<BODY>
<FORM METHOD="POST" ACTION=
"http://localhost:8081/servlet/HTTPPostServlet">
What is your favorite pet?<BR><BR>
<INPUT TYPE=radio NAME=animal VALUE=dog>Dog<BR>
<INPUT TYPE=radio NAME=animal VALUE=cat>Cat<BR>
<INPUT TYPE=radio NAME=animal VALUE=bird>Bird<BR>
<INPUT TYPE=radio NAME=animal VALUE=snake>Snake<BR>
<INPUT TYPE=radio NAME=animal VALUE=none CHECKED>None
<BR><BR><INPUT TYPE=submit VALUE="Submit">
<INPUT TYPE=reset>
</FORM>
</BODY>
</HTML>

Let’s call the above HTML file animal.html. The standard TOMCAT directory
structure suggests that animal.html should be placed under the root directory which
contains WEB-INF as well.

Topic6.doc Page 19
ICT337 Advanced Software Development
Murdoch University Topic 6

A few notes on the HTTPPostServlet example:


 The method doPost responds to POST requests.
 Method doPost throws a ServletException if the
client’s request cannot be handled, and a IOException
if a problem occurs during stream processing.
 The ACTION in the html form object specifies the
server-side form handler – HTTPPostServlet
 The METHOD=”POST” helps the servlet decide how to
handle the request and possibly causes the browser to
attach arguments to the end of the URL specified in the
ACTION.

 The file survey.txt, if not existent, would be created.


Subsequent calls to the servlet would update this file.
The file can be found created in the web-module root
directory if using tomcat directly. (If using Sun ONE
then it might be in Sun ONE’s bin directory instead.)
How to run the above HTTPPostServlet example?
 Run the servlet under TOMCAT or Sun ONE.
 Open a web browser and enter the URL
http://localhost:8081/animal.html
Again, localhost can be replaced with the IP address
of the machine on which the TOMCAT server is
running. Check the port number by running it under
Sun ONE.

Topic6.doc Page 20
ICT337 Advanced Software Development
Murdoch University Topic 6

Session tracking
Many web sites today provide custom Web pages and/or
functionality on a client-by-client basis.
An example of a service that is customized on a client-
by-client basis is a shopping cart for shopping on the
web. Obviously, the server must distinguish between
clients so the company can determine the proper items
and charge the proper amount for each client.
Another example is marketing. Companies often track
the pages you visit throughout a site so that can display
advertisements that are targeted to your browsing trends.
(A problem with tracking is that many people consider it
to be an invasion of their privacy, an increasing sensitive
issue in our information society.)

A popular way to customize Web pages is via cookies.


Cookies can store information on the user’s computer for
retrieval later in the same browsing session or in future
browsing sessions. See the CookieEg folder.
An alternative approach is to track a session with the
JSDK’s interfaces and classes from the
javax.servlet.http package that support session
tracking. See the SessionEg1 folder.

Topic6.doc Page 21
ICT337 Advanced Software Development
Murdoch University Topic 6

HttpSession
A session is a single continuous interaction with a
particular use. The session-tracking mechanism allows
an arbitrary collection of objects to be associated with a
session.
The actual implementation of session tracking is server
dependent. One common mechanism is to use an id to
track the session and associate a hash table of some sort
with this id. The hash table is stored in memory
throughout the session.
Some servers with a large number of sessions open
would serialize the data to disk. The session id can be
passed between the server and client to identify the
session (since HTTP is a stateless protocol).
Programmer can retrieve session id by calling the
getID() method via a HttpSession object (or its
subclass object). An HttpSession object can be created
by calling the getSession() method via a
HttpServletRequest object.

The expiry time of sessions is configurable (by the server


administrator).

Topic6.doc Page 22
ICT337 Advanced Software Development
Murdoch University Topic 6

SessionEg1

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class SessionEg1 extends HttpServlet {

public void doGet( HttpServletRequest request,


HttpServletResponse response )
throws ServletException, IOException
{
PrintWriter output;
int total=0;

// Get the user's session object.


// Create a session (true) if one does not exist.
HttpSession session = request.getSession( true );

Topic6.doc Page 24
ICT337 Advanced Software Development
Murdoch University Topic 6
String tot=(String)session.getAttribute("total");
if(tot!=null)
total=Integer.parseInt(tot);
// add a value for user's choice to session
total++;
session.setAttribute("total", Integer.toString(total));

response.setContentType( "text/html" );
output = response.getWriter();

// send HTML page to client


output.println( "<HTML><HEAD><TITLE>" );
output.println( "Sessions" );
output.println( "</TITLE></HEAD><BODY>" );
output.println(total);
output.println( "</BODY></HTML>" );

output.close(); // close stream


}
}
Topic6.doc Page 25
ICT337 Advanced Software Development
Murdoch University Topic 6

SessionEg2
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.Enumeration;

public class SessionEg1 extends HttpServlet {


private final static String names[] =
automatic { "C", "C++", "Java", "Visual Basic 6" };
ally called private final static String isbn[] = {
when the "0-13-226119-7", "0-13-528910-6",
Submit "0-13-012507-5", "0-13-528910-6" };
button is
clicked.
public void doPost( HttpServletRequest request,
HttpServletResponse response )
throws ServletException, IOException
{
provides a
PrintWriter output; argument true 
mechanism String language = request.getParameter( "lang" ); create a new session
for sharing if one does not exist;
data between // Get the user's session object. argument false 
servlets // Create a session (true) if one does not exist. use the previous one
visited by a HttpSession session = request.getSession( true ); (if not exist then
user during a return null)
browser
session
Topic6.doc Page 26
ICT337 Advanced Software Development
Murdoch University Topic 6

// add a value for user's choice to session


session.setAttribute( language, getISBN( language ) );

response.setContentType( "text/html" );
output = response.getWriter();

// send HTML page to client


output.println( "<HTML><HEAD><TITLE>" );
output.println( "Sessions" );
output.println( "</TITLE></HEAD><BODY>" );
output.println( "<P>Welcome to Sessions!<BR>" );
output.println( "<P>" );
output.println( language );
output.println( " is a great language." );
output.println( "</BODY></HTML>" );

output.close(); // close stream


}

public void doGet( HttpServletRequest request,


HttpServletResponse response )
throws ServletException, IOException
{
PrintWriter output;

Topic6.doc Page 27
ICT337 Advanced Software Development
Murdoch University Topic 6

// Get the user's session object.


// Don't create a session (false) if one does not exist.
HttpSession session = request.getSession( false );

// get names of session object's values


Enumeration attributeNames;
do not create a new
if ( session != null ) HttpSession object
attributeNames = session.getAttributeNames(); (ie. use the previous
one). User must
else have navigated to
attributeNames = null; other pages before
coming back here.
response.setContentType( "text/html" );

// do not cache this page


response.setHeader( "Pragma", "no cache" );
response.setHeader( "Cache-Control", "no cache" );
response.setHeader( "Expires", "0" );

output = response.getWriter();

output.println( "<HTML><HEAD>);
output.println( "<TITLE> Sessions II </TITLE>" );
output.println( "</HEAD><BODY>" );

Topic6.doc Page 28
ICT337 Advanced Software Development
Murdoch University Topic 6

if ( attributeNames != null && attributeNames.hasMoreElements() ) {


output.println( "<H1>Recommendations</H1>" );

// get value for each name in attributeNames


for ( int i = 0; attributeNames.hasMoreElements(); i++ ) {
String name = (String)attributeNames.nextElement();
String value = (String) session.getAttribute( name );

output.println(name + " How to Program. " +


"ISBN#: " + value + "<BR>" );
}
}
else {
output.println( "<H1>No Recommendations</H1>" );
output.println( "You did not select a language or" );
output.println( "the session has expired." );
}

output.println( "</BODY></HTML>" );
output.close(); // close stream
}

private String getISBN( String lang )


{

Topic6.doc Page 29
ICT337 Advanced Software Development
Murdoch University Topic 6
for ( int i = 0; i < names.length; ++i )
if ( lang.equals( names[ i ] ) )
return isbn[ i ];

return ""; // no matching string found


}
}

Topic6.doc Page 30
ICT337 Advanced Software Development
Murdoch University Topic 6
The associated HTML file for testing the post method is SessionEg1.html, as shown
below:
<HTML>
<HEAD>
<TITLE>Sessions</TITLE>
</HEAD>
<BODY>
<FORM ACTION="http://localhost:8081/servlet/SessionEg2"
METHOD="POST">
<STRONG>Select a programming language:<br>
</STRONG><BR>
<PRE>
<INPUT TYPE="radio" NAME="lang" VALUE="C">C<BR>
<INPUT TYPE="radio" NAME="lang" VALUE="C++">C++<BR>
<INPUT TYPE="radio" NAME="lang" VALUE="Java"
CHECKED>Java<BR>
<INPUT TYPE="radio" NAME="lang"
VALUE="Visual Basic 6">Visual Basic 6
</PRE>
<INPUT TYPE="submit" VALUE="Submit">
<INPUT TYPE="reset"> </P>
</FORM>
</BODY>
</HTML>

Topic6.doc Page 32
ICT337 Advanced Software Development
Murdoch University Topic 6

Use the following BookRecommendation1.html file to


test the get method of the SessionEg1 servlet:

<HTML>
<HEAD>
<TITLE>Book Recommendation</TITLE>
<META NAME="Pragma" CONTENT="no-cache">
<META NAME="Cache-Control" CONTENT="no-cache">
<META NAME="Expires" CONTENT="0">
</HEAD>
<BODY>
<FORM ACTION="http://localhost:8081/
servlet/SessionEg2"
METHOD="GET">
Press "Recommend books" for a list of books.
<INPUT TYPE="submit" VALUE="Recommend books">
</FORM>
</BODY>
</HTML>

See also the example in SessionInfoServlet folder.

Topic6.doc Page 34
ICT337 Advanced Software Development
Murdoch University Topic 6

Cookies
While Sessions provide a method for storing data about a
current user interaction, they are not intended for storing
information permanently. Cookies, on the other hand,
are key-value pairs that a servlet can associate with a
client and that can have an arbitrary expiration time.
The drawbacks of cookies are threefold:
1. they can only be strings
2. cookies are stored on the client, so they take on
client disk space; for this reason, most browsers
limit their number (~20) and size (total=4K)
3. cookies have to be sent over the Internet with each
request.
4. Clients can block cookies altogether.

Advantages: Cookies are easy to program, are flexible.


Cookies are associated with a specific server and path,
preventing other servers from reading the info they
contain. Cookies can be assigned expiry dates, making
them persistent between sessions.

Example: see the CookieEg folder

Topic6.doc Page 35
ICT337 Advanced Software Development
Murdoch University Topic 6

Servlet output

A servlet can send only one response, which must be a


complete HTML page, however…
 Alternative response
the servlet can choose between alternative responses,
or…
 Redirect the request and response to another source
the servlet can also redirect the request and response to
another source by creating a request dispatcher
object from the servlet context for the destination URL
and then transferring the HTTP request and response
through the request dispatcher this method is in the class
GenericServlet, the
RequestDispatcher rd = superclass of HttpServlet
getServletContext().getRequestDispatcher(
”skiclub/index.html”); req is a HttpServletRequest
rd.forward(req, res); object; res is a
HttpServletResponse object

 Delegate response to another servlet


the servlet can delegate the responsibility of creating
the response object to another servlet. This is done by
calling the sendRedirect method in the
HttpServletResponse class, eg:
res.sendRedirect(”http://
…/servlet/shopping.PlaceOrder”);

Topic6.doc Page 36
ICT337 Advanced Software Development
Murdoch University Topic 6

Note that the URL in a sendRedirect must be an


absolute address. Often, this technique is used to
transfer the client to another web site.

Redirection becomes a very useful technique when combining


servlets and JSP’s.

Topic6.doc Page 38
ICT337 Advanced Software Development
Murdoch University Topic 6

Guidelines for servlet-driven webs


 multithreading:
o do not use fields of the servlet class (eg. the
HttpServletResponse class) as working storage
because the threads share the same instance
variables.
o Only use instance variables for globals that can
be shared by all threads, i.e. JDBC connection
pool, hit counter, etc. All instance variables are
shared by threads.
o use Session objects rather than fields (see
above) to store state data. Each client has a
separate session, so session data is thread-safe.
o local variables are thread safe because the JVM
maintains a separate stack frame for each thread
o declare methods that should run for only one
client at a time to be synchronized, eg. client
registering data into the database.
 Use applets judiciously:
o Thin clients improve the performance of your
web
o Adding some fat to the clients saves
transmission time and aggravation, eg. data field
checking in form entering can be done on the
client side.
o NOTE: The output HTML document from a
servlet can include <APPLET> and <SCRIPT> tags.
An applet called in an HTML page that is
generated by a servlet can do anything like other
Topic6.doc Page 39
ICT337 Advanced Software Development
Murdoch University Topic 6

applets in any web page.


(see Topic 5 Multitier Systems regarding thin and
fat clients)
 Be wary of the Browser Back button
o Page caching of the browser is of concern here.
To tell the web browser not to cache a page,
include the <META> tags in the HTML
response header:
<HTML>
<HEAD>
<META NAME=”Pragma” CONTENTS=”no-cache”>
<META NAME=”Cache-Control”
CONTENTS=”no-cache”>
<META NAME=”Expires” CONTENT=”0”>
</HEAD> different web
browsers
In general, you should turn off caching understand
for all pages that contain dynamic different meta
tags, so we
content. usually have to
provide a number
 Security of them.
 Authentication?
 Authorization?
 Data integrity
 Accountability?

Topic6.doc Page 40
ICT337 Advanced Software Development
Murdoch University Topic 6

Java Server Pages (JSPs)


Server-side scripting is a technique by which program
code is embedded in HTML documents and then parsed
by a Web server. This technique enables more flexibility
in the layout of HTML documents during Web
application development. Sun provides a form of server-
side scripting called JavaServer Pages (JSPs). JSPs
features special HTML pages that include embedded Java
code.
JSPs help solve the following problems that are inherent
to servlets:
o calling print methods to write HTML is clumsy
o developing a large web site requires a team of people
with a variety of skills. Design of HTML page can be
left to the graphic and user interface designers rather
than Java programmers
In short, JSPs let you write your HTML in HTML rather
than in Java.

In many ways, JSPs look like standard XHTML or XML


documents. In fact, JSPs normally include XHTML or
XML markup. Such markup is known as fixed-template
data or fixed-template text.
Programmers tend to use JSPs when most of the content
sent to the client is fixed template data;
Programmers tend to use servlets when most of the
content sent to the client is dynamically generated with
Java code.

Topic6.doc Page 41
ICT337 Advanced Software Development
Murdoch University Topic 6

JSP example 1: Today.jsp


Below is an example of a JSP: Today.jsp
(c.f. TodayServlet.java)

<HTML>
<HEAD>
<META NAME=”Pragma” CONTENTS=”no-cache”>
<META NAME=”Cache-Control” CONTENTS=”no-cache”>
<META NAME=”Expires” CONTENT=”0”>
<TITLE>Today</TITLE>
</HEAD>
<%@ page import=”java.util.*” %>
<BODY>
<H1>The current date and time is:</H1>
<P> <%= new Date() %> </P>
</BODY>
</HTML>

Topic6.doc Page 42
ICT337 Advanced Software Development
Murdoch University Topic 6

Scripting components in JSPs


JSP scripting components include scriptlets, comments,
expressions, declarations and escape sequences.

JSP element Description & Examples


<%@ page Defines attributes of the page, eg. packages
attribute=value… to import and whether page uses an
%> HTTPSession object, eg.
<%@ page info=”An example
JSP” %>
<%@ page
import=”skiclub.*” %>
<%@ page lang=”java”
session=”true” %>
<%@ include file= Directive: substitutes text or code from
”relativeURL” specified file, eg.
%> <%@ include file=
”banner.html” %>
<%@ taglib uri= Directive: declares a library of custom tabs
”uri”… %> to extend the JSP set, eg.
<%@taglib uri=”myTagLibrary” %>

<%! … %> Declaration: declares a variable for use in


this JSP. eg,
<%! double intRate=2.32; %>
<%! skier = new
ClubMember(); %>
<%! Vector v = new Vector();
%>
<%= … %> Expression: Inserts value of the Java
expression into page, eg.
<%= skier.getName() %>
<%= Math.sqrt(a*a + b*b) %>
<%=

Topic6.doc Page 43
ICT337 Advanced Software Development
Murdoch University Topic 6

(int)Session.getValue(”id”)
%>
<% … %> Scriptlet: execute enclosed Java code
<% // item is declared
// and holds data
for (int m=0;
m < item.length;
m++) {
System.out.println(
”item: ”+
item[m].getName());
}
%>

To call a JSP, you give the URL to the browser the same
way as you would to request any HTML page. The only
difference is the extension being .jsp rather than .htm or
.html, eg. after putting Today.jsp under the topic7
directory, you can use the following URL
http://localhost:8081/Today.jsp

Topic6.doc Page 44
ICT337 Advanced Software Development
Murdoch University Topic 6

How web servers process JSPs

The Web server handles a request for JavaServer Pages


by forwarding the request to a special servlet. This
servlet, called the PageCompileServlet, takes requests
for JSPs and carries out an appropriate action. If the
page is requested for the first time, the action is to
compile the JSP into a servlet and ask the servlet to
service the request. Subsequent requests for the same
page results in a direct request to the servlet generated
from the JSP. The PageCompileServlet generates a
servlet for each JSP and that servlet handles all further
requests.

Combining JSPs and servlets in a web can be effective.


The Figure below shows how servlets, JSPs, browsers,
and supporting classes the server can relate to each other:

Topic6.doc Page 45
ICT337 Advanced Software Development
Murdoch University Topic 6

The numbers in the figure correspond to the following


numbered steps:

1. client enters the URL of a servlet


2. browser submits an HTTP request with a GET or
POST method
3. server runs the servlet, calling the service method.
(The servlet may process input from a form,
manipulate session data.)
4. servlet can redirect the HTTP request and response
to the JSP
5. if necessary, the page-compile process converts the
JSP to a servlet and page-compiles it. Then the
server loads and runs the JSP-generated servlet,
calling the service method
6. the HTML page produced by JSP-generated servlet
is returned to the client’s browser.

Topic6.doc Page 46
ICT337 Advanced Software Development
Murdoch University Topic 6

Implicit objects in JSPs


You can use the objects listed below in your JSP file
without declaring them.

Variable Package / Description


name Class
request javax.servlet.http The HTTP request
HttpServletRequest
originally sent to the
server
response javax.servlet.http The HTTP response to
HttpServletResponse
the request
pageContext javax.servlet.jsp An object encapsulating
PageContext
the context for this page
session javax.servlet.http The Session object
HttpSession
associated with the
request and response
application javax.servlet The object returned by
ServletContext getServletConfig().g
etContext(). This
object represents the
container in which the
JSP executes.
out javax.servlet.jsp An object that writes to
JspWriter
the response output
stream
config javax.servlet The ServletConfig
ServletConfig
object for this JSP
page java.lang The this object
Object
reference in this JSP

Topic6.doc Page 47
ICT337 Advanced Software Development
Murdoch University Topic 6

JSP Example 2: Welcome.jsp

<?xml version = "1.0"?>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<!-- Fig. 10.4: welcome.jsp -->


<!-- JSP that processes a "get" request containing data. -->

<html xmlns = "http://www.w3.org/1999/xhtml">

<!-- head section of document -->


<head>
<title>Processing "get" requests with data</title>
</head>

<!-- body section of document -->


<body>
<% // begin scriptlet

String name = request.getParameter( "firstName" );

if ( name != null ) {

Topic6.doc Page 48
ICT337 Advanced Software Development
Murdoch University Topic 6
%> <%-- end scriptlet to insert fixed template data --%>

<h1>
Hello <%= name %>, <br />
Welcome to JavaServer Pages!
</h1>

<% // continue scriptlet

} // end if
else {

%> <%-- end scriptlet to insert fixed template data --%>

<form action = "welcome.jsp" method = "get">


<p> Type your first name and press Submit</p>

<p><input type = "text" name = "firstName" />


<input type = "submit" value = "Submit" />
</p>
</form>

<% // continue scriptlet

} // end else

Topic6.doc Page 49
ICT337 Advanced Software Development
Murdoch University Topic 6

%> <%-- end scriptlet --%>


</body>

</html>

JSP example 3: VisitCounter.jsp


This JSP counts how many times a particular user visits a page. It uses the
Session object.
1. get the value of the session variable - visitcounter
2. if the session variable (visitcounter) is null, set the session variable to 0 and
welcome the visitor.
3. if the session variable is not null (after step 2), increment the session
varaible and display the number of visits.

<html>
<head>
</head>
<body>
<% // get the value of the session variable - visitcounter

Topic6.doc Page 50
ICT337 Advanced Software Development
Murdoch University Topic 6
Integer totalvisits = (Integer)session.getValue("visitcounter");
// if the session variable (visitcounter) is null
if (totalvisits == null) {
// set session variable to 0
totalvisits = new Integer(0);
session.putValue("visitcounter", totalvisits);
// print a message to out visitor
%>
<H1>Welcome, visitor</H1>
<%
}
else {
// if you have visited the page before then add 1 to the
// visitcounter
totalvisits = new Integer(totalvisits.intValue() + 1);
session.putValue("visitcounter", totalvisits);
out.println("<H1>You have visited this page " +
totalvisits + " time(s)!</H1>");
}
%>
</body>
</html>

Topic6.doc Page 51
ICT337 Advanced Software Development
Murdoch University Topic 6

Current use of Servlets/JSP


 The current practice involves using a combination of servlets and JSP’s rather
than any one by itself.
 The servlet would do all of the processing, read/write to/from database/file,
invoke web services, parse input, process order, etc, etc. After the servlet
finishes processing, it sends only the results to the JSP to display.
 Why this works well
o Servlets are compiled once and stay in memory as long as the webserver
is running. JSP’s are compiled into servlets each time they are requested,
so there is performance benefits in using servlets over JSP’s.
o Output in Servlets requires writing java code, whereas in JSP’s small
pieces of java code are inserted into html code.
o Clear separation of processing and presentation. Keeping servlets as pure
code will help stop the web-development spaghetti code mentality of
programmers when they write web programs.
o Allows programmers to focus on the real processing without having to
worry about the often tedious job of displaying the output.

Topic6.doc Page 52
ICT337 Advanced Software Development
Murdoch University Topic 6
o This separation also allows real programmers to do the real
programming, the results can be stored in beans or sessions which less
experienced web-developers (not programmers) are able to incorporate
into their html pages.
o Less likelihood that web developers will remove vital code when
formatting the web pages.
o Simple to do. Client posts to the servlet, the servlet does the processing
and then redirects the HttpServletResponse to the JSP.

Topic6.doc Page 53
ICT337 Advanced Software Development
Murdoch University Topic 6

Further reading:
See textbook “Advanced Java 2 Platform – How to
Program” by Deitel, Deitel, Santry:
 For servlets: Chapters 9
 For JSPs: Chapter 10, pages 593-605. Optional:
see examples from pages 606-636.
 Optional: “Case Study: Servlet and JSP
Bookstore”, Chapter 11.
.

Topic6.doc Page 54
ICT337 Advanced Software Development
Murdoch University Topic 6

Objectives
At the end of this topic, you should be able to
 describe why server side programming is necessary for
certain applications
 describe the advantages of servlets over CGI
 describe how web servers handle HTTP requests for
servlets
 describe why session tracking is necessary for certain
applications and use the appropriate Java classes for
session tracking.
 outline a few guidelines for servlet-driver webs
 describe why JSPs are sometimes more appropriate to use
than servlets
 describe how web servers process JSPs
 give a simple example (in Java) of a servlet and a simple
example (in HTML/Java) of a JSP

Topic6.doc Page 55

You might also like