Topic 6 Servlets and JSPS: Ict337 Advanced Software Development Murdoch University Topic 6
Topic 6 Servlets and JSPS: Ict337 Advanced Software Development Murdoch University Topic 6
Topic 6 Servlets and JSPS: Ict337 Advanced Software Development Murdoch University Topic 6
Topic 6
Servlets and JSPs
HTTP Basics
Session tracking
Servlet output
Topic6.doc Page 1
ICT337 Advanced Software Development
Murdoch University Topic 6
Topic6.doc Page 2
ICT337 Advanced Software Development
Murdoch University Topic 6
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
Topic6.doc Page 4
ICT337 Advanced Software Development
Murdoch University Topic 6
HTTP/1.0 200 OK
Topic6.doc Page 5
ICT337 Advanced Software Development
Murdoch University Topic 6
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
Topic6.doc Page 7
ICT337 Advanced Software Development
Murdoch University Topic 6
Topic6.doc Page 8
ICT337 Advanced Software Development
Murdoch University Topic 6
Topic6.doc Page 9
ICT337 Advanced Software Development
Murdoch University Topic 6
Topic6.doc Page 10
ICT337 Advanced Software Development
Murdoch University Topic 6
HTTPSession getSession()
String getParameter(String name)
Topic6.doc Page 11
ICT337 Advanced Software Development
Murdoch University Topic 6
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
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
Topic6.doc Page 13
ICT337 Advanced Software Development
Murdoch University Topic 6
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).
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.
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
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 ];
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>" );
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
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.)
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.
Topic6.doc Page 22
ICT337 Advanced Software Development
Murdoch University Topic 6
SessionEg1
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
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();
SessionEg2
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.Enumeration;
response.setContentType( "text/html" );
output = response.getWriter();
Topic6.doc Page 27
ICT337 Advanced Software Development
Murdoch University Topic 6
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
output.println( "</BODY></HTML>" );
output.close(); // close stream
}
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 ];
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
<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>
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.
Topic6.doc Page 35
ICT337 Advanced Software Development
Murdoch University Topic 6
Servlet output
Topic6.doc Page 36
ICT337 Advanced Software Development
Murdoch University Topic 6
Topic6.doc Page 38
ICT337 Advanced Software Development
Murdoch University Topic 6
Topic6.doc Page 40
ICT337 Advanced Software Development
Murdoch University Topic 6
Topic6.doc Page 41
ICT337 Advanced Software Development
Murdoch University Topic 6
<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
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
Topic6.doc Page 45
ICT337 Advanced Software Development
Murdoch University Topic 6
Topic6.doc Page 46
ICT337 Advanced Software Development
Murdoch University Topic 6
Topic6.doc Page 47
ICT337 Advanced Software Development
Murdoch University Topic 6
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>
} // end if
else {
} // end else
Topic6.doc Page 49
ICT337 Advanced Software Development
Murdoch University Topic 6
</html>
<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
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