Taming Tomcat, Day 1: The Basics
Author and presenter: Simon Brooke.
The full text of this presentation is online at <URL:
http://www.weft.co.uk/library/tomcat/>
Written March-April 2006; $Revision: 1.9 $ of $Date:
2006-04-28$
Changes to the presentation since your
handouts were printed are highlighted like this.
Simon Brooke, 21 Main Street, Auchencairn, DG7 1QU,
Scotland.
Day 2: Development
and Adminsitration
Before we start...
- Fire drill
- Nearest WC
- Break timetable
Programme for Today
- This morning
- Before break
- What is Tomcat?
- Simple Install
- Drop in a webapp
- After break
- Basic configuration
- Integration
- This afternoon
- Before break
- More complex webapps
- Stress testing
- After break
- Building a webapp with JSP
In sh'Allah...
'Good teaching is one-fourth preparation and three-fourths
theater' - let's hope so!
What I'm trying to achieve today
- By the end of today you should...
- Understand what Tomcat is, why it's necessary and what
it's good for
- Be able to install Tomcat
- Be able to deploy webapps
- Have built a simple webapp
What is Tomcat
- A Servlet container
- The reference Servlet container
- Tomcat 4 implements Servlet Specification version
2.3
- Tomcat 5 implements Servlet Specification version
2.4 (330
page document!)
- A system for deploying Java server side components to
service HTTP requests over the Internet/Web
- Web applications or 'Webapps'
- Why?
- Why deliver applications over the Web?
- Why use Java to do so?
The Internet and the Web
Open, heterogenous network of networks, carrying distributed
hypertext
- Open:
- the standards are published, and are not protected by
patents, non-disclosure agreements, and so on - anyone can copy
them.
- Heterogenous:
- the standards are not based on the facilities of any one
proprietary sort of computer - any computer can be
connected
- Networks of networks:
- not every computer everywhere has to be able to connect to
the same network standards, provided that the networks
themselves can intercommunicate.
A brief history of Distributed Hypertext
or 'none of this is new' part one
- Project
Xanadu, Ted Nelson 1960
-
Distributed hypertext over heterogenous networks
- TCP/IP, Xerox PARC, 1970s
-
Transmission of data over unreliable networks of
networks
- HTML, Tim
Berners-Lee, CERN, 1990
-
Distributed hypertext over heterogenous networks - much
simpler than Xanadu
Forms in HTML
- As well as pages of text, HTML provides mechanisms for
forms
- Containing INPUT elements
- Associates a name with a
value
- So each form is a namespace
Cheap Client-Server Lego
- Ubiquitous, standardised client
- Available everywhere on a pervasive network
- All we need are the applications to drive it!
This is new!
Java
or 'none of this is new' part two
- A bit about programming languages
- A bit about the Common Gateway Interface
- A bit about server-side Java
A brief history of programming languages
- LISP, John McCarthy, 1959
- BCPL: Martin Richards, Cambridge University, 1969
- C: Thompson & Richie, Bell Labs, 1972
- Smalltalk, Goldberg, Kay and others, Xerox PARC, 1973
- Oak: James Gosling, Sun Microsystems, 1990
- Java: James Gosling et al, Sun Microsystems 1995
- JDBC: Sun Microsystems 1996
LISP: John McCarthy, 1959
- Automatic memory management and Garbage Collection
BCPL: Martin Richards, Cambridge University, 1969
- low level typeless language
- compiled to compact interpreted ('CINT') code, hardware
independent.
- standard library
- CINT code interpreter is 'virtual machine'.
C: Thompson & Richie, Bell Labs, 1972
- derived directly from BCPL but compiles to machine
code
- used to write the UNIX operating system
- became widely used
- [horrible] 'object oriented' extensions - C++ and Objective
C.
Smalltalk: Goldberg, Kay and others, Xerox PARC, 1973
- Automatic memory management
- Everything is an object
- Class inheritance
- Interactive graphical user interface
- [later] Virtual Machine with 'Just In Time' native
compilation
Oak: James Gosling, Sun Microsystems, 1990
- Targeted at consumer electronics products
- Like LISP, memory management is automatic
- Like Smalltalk, (almost) everything is an object
- Unlike Smalltalk, primitive data items are not objects
(mistake?)
- Java JIT technology is directly from Smalltalk
- Like BCPL, compiles to hardware independent code
- Only the syntax is like C++
Java
- OAK plus Web browser renamed 'Java' and launched publicly
by Sun
Server-side Java
- Java was not conceived as a server-side language
- Java has substantial problems as a server-side
language
- Java is currently the most successful server-side
language
Java was not conceived as a server-side language
- Oak, designed for consumer electronics
- Small footprint
- Limited processing power
- Java, marketed for web-deliverable client-side
functionality
- Low bandwidth links
- Heterogenous environment client-side
Java has substantial problems as a server-side language
- About Web servers
- About CGI
- Performance of Java CGI
- What to do about it?
About Web servers
- 'HTTP Daemons' or HTTPDs
- Simple operation
- Listen for a request on a network port
- Read request headers
- Print response headers
- Print response content
HTTPD in 100 lines
- Here's an example in 100 lines of shell script
!/bin/bash
#########################################################################
# #
# Project: Gild #
# http #
# #
# Purpose: HTTP 0.9 handler for GILD. Handles http requests #
# reasonably accurately, considering it's under 100 lines #
# of shell-script. #
# #
# Author : Simon Brooke #
# Copyright: (c) Simon Brooke 1997 #
# Version : 0.1 #
# Created : 10th October 1997 #
# #
#########################################################################
SERVER_ROOT="/etc/local/etc/gild/httpd"
DOCUMENT_ROOT="$SERVER_ROOT/htdocs/"
AGENT_NAME="GILD_http_handler/0.1"
now=`date "+%a, %d %b %Y %k-%M-%S"`
read command file protocol
case $command in
"HEAD"|"Head"|"head") ;; # that's OK;
"GET"|"Get"|"get" ) ;; # So's that...
* ) cat $SERVER_ROOT/error/501.html;
echo "$now: $REMOTE_HOST: Unknown command [$command]" \
>> $SERVER_ROOT/logs/error_log;
exit 0;;
esac
rq_file=$file
if [ -n $file ]
then
file=`echo "$DOCUMENT_ROOT$file"`
if [ -d $file ] # if it's a directory, look for it's
# index...
then
file=`echo "$file/index.html"`
fi
if [ -r $file ]
then
length=`ls -l $file | awk '{print $5}'`
ftype=`file $file | sed 's/[^:]*: //' | awk '{ print $1}'`
case $ftype in
"HTML" ) type=text/html;;
"ascii" ) type=text/plain;;
"english" ) type=text/plain;;
"a" ) type=text/plain;; # probably a shell script!
"GIF" ) type=image/gif;;
"JPEG" ) type=image/jpeg;;
* ) type=x-unknown/unknown;;
esac
echo "HTTP/0.9 200 OK"
echo "Date: $now"
echo "Server: $AGENT_NAME"
echo "Content-Type: $type"
echo "Content-Length: $length"
echo ""
case $command in
"HEAD"|"Head"|"head") exit 0;;
"GET"|"Get"|"get" ) cat $file;;
esac
echo "$now: $REMOTE_HOST: $command: $rq_file" \
>> $SERVER_ROOT/logs/access_log
else # didn't find it; report and log
cat $SERVER_ROOT/error/404.html
echo "$now: $REMOTE_HOST: No such file [$rq_file]" \
>> $SERVER_ROOT/logs/error_log
fi
fi
exit 0 # yes, I know it _shouldn't_ be necessary
About CGI
- 'Common Gateway Interface'
- Standardised method for web servers to call programs to
deliver dynamic content
- HTTPD invokes CGI program in child process...
- ...prints request headers on CGIs standard input
- CGI program prints response headers on its standard
output
- CGI program prints response content on its standard
output
- CGI program exits
- Any programming platform
- Program needs to accept input in a standardised form, and
produce output in a standardised form
Java CGI: Performance
- Possible...
- But performance
dreadful. Tests I did back in 1997 when we were still
working out how to use Java server-side showed:
| Static file, requested from Apache: |
0.78 seconds |
| HelloWorldServlet, mod_java, large VM: |
6.40 seconds |
| HelloWorldServlet, mod_java, 'ns' VM: |
6.01 seconds |
| Bourne shell CGI script, test-cgi |
1.02 seconds |
| Perl shell CGI script, printenv |
1.46 seconds |
| Compiled C CGI script, test.cgi, stripped |
0.93 seconds |
Why was the performance so bad?
- Java is a slow language?
- Start-up costs of the virtual machine
| HelloWorldServlet, mod_java, large VM: |
6.40 seconds |
| HelloWorldServlet, mod_java, 'ns' VM: |
6.01 seconds |
| HelloWorldServlet, jserv 0.9.9: |
0.94 seconds |
- JServ kept a virtual machine permanently running, serviced
each request in the same VM
- Java is fast enough, provided the virtual machine is
already started!
Difference between Servlets and CGIs
- CGI is started in its own process, serves one request and
exits
- Very safe programming environment
- Servlet starts, serves requests as they occur, doesn't exit
- May serve multiple requests at the same time
- Must be 'thread safe' (e.g., cannot store request
data on instance variables)
- Must not horde resources
Why Tomcat?
- JServ and Servlets solved the performance problem
- What problem does Tomcat solve?
Why Tomcat
- Pluggability
- Complete web applications, pre-configured, delivered as
a single file
- Just drop it in and it works
- On any platform
Reprise: What is Tomcat
- The Internet provides a standardised, ubiquitous transport
layer for data communications in heterogenous networks
- The Web provides a standardised, ubiquitous client on
heterogenous platforms
- Java provides a standard language for developing
application binaries for heterogenous platforms
- Tomcat provides a mechanism for simply deploying
server-side application binaries on heterogenous platforms
- Cheap Client-Server Lego
Simple install: Windows
- On MS Windows
- Download installer from here
- Double click installer
- Agree to the licence
- Choose your options (advice: select all)
- Choose admin username and password (why?)
- Click more pretty buttons...
- And more...
Simple Install: Debian
- On Debian
- stable: apt-get install tomcat4
- Tomcat 5 not yet available in Debian stable
- testing: apt-get install tomcat5
Simple install: Debian (ii)
- But! Debian for political reasons won't install either
IBM's, Sun's or
Blackdown's Java
- Installs Kaffe instead
- which doesn't, really - very slow
- So you have to download your own Java SDK from Sun or
IBM or Blackdown
- And then edit /etc/default/tomcat5
- Which slightly detracts from the wonderful package
system...
Simple install
Exercise: Install Tomcat
- Choose the right installer for your operating system
- Copy one of these WAR files into your Tomcat webapps
directory
LearnBRL - the
Lisp (or rather, Scheme) equivalent of JSP!
VQWiki - a very easy
to use Wiki (collaborative Web editing tool)
[Break]
Basic Configuration
- server.xml - the main configuration file
- web.xml - default configuration for all
Webapps
- tomcat-users.xml - users, passwords,
roles
- OS dependent stuff
server.xml Brief highlights
- One or more Service elements containing
- A Connector element for each port Tomcat
listens on
- An Engine element for the engine which
routes request to appropriate virtual hosts, containing
- 0 or more Logger elements defining
loggers
- 1 or more Host elements defining
virtual hosts, containing
- 0 or more Realm elements defining
authentication zones
- 0 or more Logger elements defining
loggers
- 0 or more Context elements
defining Webapps
- But most Webapps are not defined this
way
Things you may want to change from the defaults
- Defaults are mostly good
- You may want to change
-
unpackWARs attribute of Host
element
- true if your Webapps may want to upload
files or store state in the file system (e.g.,
cache)
- false otherwise
-
autoDeploy attribute of Host
element
- true means you can install Webapps just
by dropping them into the webapps directory
- false means you can't
- Ports
- Default HTTP port for Tomcat is 8080
- Usually
- On Debian, Tomcat 3 uses 8080, Tomcat 4 and
5 use 8180
- This port is often also used by proxy
servers
- And by numerous trojans e.g. BrownOrifice
so often blocked
- If you are using Tomcat as you principal web
server you probably want to change that to 80
- Easy on Windows
- Hard on UN*X, because 80 is a privileged
port
- Can only be opened by root
- You don't want to run a web server as
root
- HOWTO here
- Default AJP13 port is 8009
- This port is also used by Novell Netware Http
Server
- Default Shutdown port is 8005
- I know of no other significant uses of this
port
- Any/all of these may be blocked by many
firewalls
Top-level web.xml
- Syntax I'll detail tomorrow
- Defines servlets:
- default: handles cases which nothing else
is defined to handle (knows how to handle static
content)
- invoker: handles Servlets which have not
been defined in a web.xml file (never seen this done in
practice)
- jsp: handles all Java Server Pages (JSP)
files, we'll talk about these this afternoon
-
ssi: handles Server Side Includes (but
Apache HTTPD does this better)
- Not enabled by default, you need to uncomment its
mapping to enable it
-
cgi: handles requests to external CGI
programs (but, again, Apache HTTPD does this better)
- Not enabled by default, you need to uncomment its
mapping to enable it
Integration
- Why integrate?
- Integration Strategies
- Integration with Apache
Why Integrate?
- Tomcat is a full featured Web server
- Can do everything a Web server should be able to do
- Including serve CGIs written in other languages
- Performance slightly less good for serving static content
- No need to integrate
- You can just use Tomcat as your front-end web server,
serving all your content
- Only problem is on UNIX you have to run as root to open
port 80
- There are solutions to this, e.g. here
- Or else run on a non-standard port (e.g. 8080)
Integration Strategies
- Side by side
- One in front of the other
- Connectors
Integration: Side-by-side
- Apache and Tomcat run on separate ports
- HTTPD serves pages with URLs pointing to where Tomcat
is
- No real integration
- Pros
- Very easy!
- Works with any HTTPD, not just Apache HTTPD and
IIS
- Cons
- May get blocked by firewalls
Exercise: Side by side
- Write an HTML page which links to a resource in your webapp
served on Tomcat's default port
- Tomcat normally serves on port 8080 (8180 on
Debian)
- Serve your page from Apache HTTPD
- Save it in Apache HTTPD's document space
- \Program Files\Apache Group\Apache2\htdocs on
Windows
- /var/www on Debian
Integration: One in front of the other
- HTTPD acts as a proxy in front of Tomcat
- Receives request from client by HTTP
- Passes request on to Tomcat by HTTP
- Receives response back by HTTP
- Sends response to client by HTTP
- Pros
- Won't get blocked by firewalls
- Works with many HTTPDs, not just Apache HTTPD and
IIS
- Cons
- Complex to configure
- Slower than connectors
Integration: Connectors
- HTTPD passes requests on to Tomcat by special protocol
(usually AJP13)
- Receives request from client by HTTP
- Passes it on to Tomcat using optimised protocol
- Receives response back by optimised protocol
- Sends response to client by HTTP
- Pros
- Won't get blocked by firewalls
- Faster than proxying
- Cons
- Works with Apache HTTPD and IIS only
- Quite complex to configure
Connectors: brief history
- There have been several generations of connector
software
- Current is mod_jk 1.2
- Several generations of connector protocol
- Current is AJP13
mod_jk: Configuring
- From the Apache HTTPD side: mod_jk not present
by default
- Getting and installing mod_jk
- httpd.conf or
apache2.conf
- workers.properties
- From the Tomcat side
Major Gotcha: Apache HTTPD 2.2
- Apache HTTPD 2.2 has recently been released
- It is the current recommended stable version
- It is not compatible with Apache HTTPD 2.0 modules
- There is as yet no mod_jk release for Apache HTTPD 2.2
From the Apache HTTPD side: getting and installing
mod_jk
- mod_jk is not part of the standard Apache 2
distribution
- mod_jk is not part of the standard Apache 1.3 distribution
(obsolete, but many people still use it)
- If your operating system has a package available, use
it!
- If not, download the source or an appropriate binary from
here
- Note that, contrary to what you'd expect, 1.2 is the
current version and 2.0 is obsolete!
- If you download the binary, all you get is usually just
the binary
- If you download the source, compiling Apache modules is
now something of a performance
This is not as straightforward as it could be!
From the Apache HTTPD side: httpd.conf or
apache2.conf
- Load the JK module
- e.g. LoadModule jk_module
/usr/lib/apache/1.3/mod_jk.so
- Exact path will vary!
- Declare the configuration
- e.g. JkWorkersFile
/etc/tomcat4/jk/workers.properties
- Exact path will vary!
- Can be in an <IfModule mod_jk.c>
block
- Mount the specific Webapps you want to mount
- e.g. JkMount /appname/*
ajp13
- appname is the name of the Webapp
- You can mount an arbitrary number by using this
directive repeatedly
- Can be in an <IfModule mod_jk.c>
block
- Can be in a <VirtualHost ...>
block
From the Apache HTTPD side: workers.properties
- Not included in the standard distribution!
- If your operating system has a mod_jk, it will probably be
included in that
- Here's a simple one:
# Tomcat and Java configuration
#
# Where Tomcat is installed
workers.tomcat_home=/usr/share/tomcat4
# Where the Java SDK is installed
workers.java_home=/usr/lib/j2se/1.4
# The path separator character used by the operating system
ps=/
# The list of workers defined in this file
worker.list=local
# Definition for local worker using AJP 1.3
#
# The protocol used. Should always be AJP13 - everything else is obsolete
worker.local.type=ajp13
# The host the worker runs on (does not need to be the same machine)
worker.local.host=localhost
# The port the worker listens on
worker.local.port=8009
# If more than one worker, define load balancing factor.
# Must be greater than 0, higher it is more work given to this worker
worker.local.lbfactor=1
- Note that:
- You can define more than one worker
- You can have workers on more than one host
From the Tomcat side
- Usually enabled by default
- In the server.xml file
- A Connector element with its
protocolHandlerClassName attribute set to
org.apache.jk.server.JkCoyoteHandler
- Example:
<Connector className="org.apache.coyote.tomcat4.CoyoteConnector"
port="8009" minProcessors="5" maxProcessors="75"
enableLookups="true" acceptCount="10" debug="0"
connectionTimeout="20000" useURIValidationHack="false"
protocolHandlerClassName="org.apache.jk.server.JkCoyoteHandler"/>
Digression: 'Apache'
- The Apache HTTPD
started life as a collection of patches for the NCSA HTTPD
- 'a patchy HTTPD'
- Now far and away the most successful HTTPD
- From the success of the
Apache HTTPD grew the Apache Software Foundation
- Not for profit body to own the IPR and supervise
development
- Apache Software Foundation now supervises lots of projects
- (including Tomcat, which is itself an
HTTPD)
- Not just the HTTPD
- So it's now misleading to call the HTTPD just
'Apache'
Exercise: One in front of the other
- Configure Apache and Tomcat so that Apache passes requests
for your Webapp to Tomcat using AJP13
[Lunch]
More complex Webapps
- Fisherman
- What I just happen to be working on just now
- Simple data driven application, with configurable
workflow.
- Licensing of commercial fishery
- PRES
- Content management, principally for news sites
- A more mature application
Exercise: installing more complex webapps
- Select the one you want to install
- Run the installer
- Configure Apache to connect
Stress testing
- Apache has a tool to stress-test servers
- Why doesn't this surprise you?
- JMeter, a
sub-project of Jakarta
- We'll use this.
Installing JMeter
- Download JMeter from here
- Doesn't have an installer
- You'll have to decide where to put it
- On UN*X
- On Windows
- c:\Program Files\Apache Software
Foundation
Starting JMeter
- On UN*X
- There's a shell script in the /bin
subdirectory called jmeter
- Run that
- On Windows
- Theres a batch script in the \bin
subdirectory called jmeter.bat
- Run that
Configuring JMeter
- Compex to configure
- One simple test plan recipe today
- Full documentation here
the Test Plan
- Create a Thread Group
- Add a Graph Results listener to the
Thread Group
- Add a Loop Controller to it
- Set Loop Count to
Forever
- Add an 'HTTP Request Sampler' to the
Loop Controller
- Configure it to point to a URL on your neighbours
machine
- Save your plan!
Exercise: Running JMeter
- Take turns to do this!
- Not a good idea to run test meter on the same processor
as the server it's testing!
- To start the test, select Start from the
Run menu
- To stop the test, select Stop from the
Run menu
- To clear the graph, choose Clear from the
Run menu
Things to do with JMeter
- Test a static page served by Apache HTTPD
- Test a static page served by Tomcat directly
- Test a static page served by Tomcat via Apache HTTPD
- Test a dynamic page served by Tomcat directly
- Test a dynamic page served by Tomcat via Apache HTTPD
- Compare the number of pages served per minute
(throughput)
- Compare the average time to serve a page in
milliseconds
- Should you serve static content with Tomcat?
- Should you put your Tomcat behind Apache HTTPD or beside
it?
- Did anyone get different results?
Break
Building a Webapp with JSP
Introduction to JSP
- (Yet another) standard way to use Java, promoted by
Sun
- Embedding program fragments into markup
- Java equivalent of PHP or ASP
- Quickest/simplest way to get dynamic content going with
Tomcat
- Probably the most popular way to write dynamic content with
Tomcat
Why I don't like/use JSP
- I think (and say) that JSP (and PHP, and ASP, and all the
other similar technologies) confound logic with presentation,
and so you should use Servlets which don't
- Interestingly, Hans Bergsten, who wrote the O'Reilly book
on Java Server Pages, claims Servlets confound logic with
presentation, and so you should use JSP which doesn't!
- Actually, badly written Servlets do confound logic with
presentation
- So do badly written JSP pages
- Most Servlets and most JSP pages (and most other things
which generate content for the Web) are atrociously
written.
Setting up the framework of your Webapp
- To get started quickly, just copy the
jsp-examples web-app
- Give it a new name
- firstjsp
- Create a simple HTML file in the root directory of the
webapp
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>First JSP page</title>
</head>
<body>
<h1>Hello, World!</h1>
</body>
</html>
A page which includes dynamic content
- Now, add a bit of Java to your page:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Second JSP page</title>
</head>
<body>
<h1>Hello, World!</h1>
<p>The time is now <%= new java.util.Date() %></p>
</body>
</html>
How's that?
- We can embed bits of Java into an ordinary HTML page, and
they just work!
- Note that the page is not valid HTML
- And it's not well formed XML either
Doing it right
Edit your page a little
- Note that every time you edit your page, it gets
recompiled
- Takes a little time
- But makes development very easy
A page which performs a calculation
<?xml version="1.0" encoding="iso-8859-1"?>
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page"
xmlns:html="http://www.w3.org/1999/xhtml"
version="1.2">
<jsp:text>
<html:html
xmlns:html="http://www.w3.org/1999/xhtml">
<html:head>
<html:title>Fourth JSP Page</html:title>
</html:head>
<html:body>
<!-- this is how we do imports in JSP -->
<jsp:directive.page import="java.util.*" />
<!-- this is how we declare variables -->
<jsp:declaration>
GregorianCalendar greg =
new GregorianCalendar();
</jsp:declaration>
<!-- this is how we embed arbitrary code -->
<jsp:scriptlet>
greg.add( Calendar.MONTH, 1);
</jsp:scriptlet>
<html:h1>Hello world!</html:h1>
<html:p>In one month it will be
<jsp:expression>greg.getTime()</jsp:expression>
</html:p>
</html:body>
</html:html>
</jsp:text>
</jsp:root>
In old syntax
-
You'll need to use the old syntax to
get this working under Tomcat4
<html>
<head>
<title>Fourth JSP Page</title>
</head>
<body>
<!-- this is how we do imports in old JSP -->
<%@ page import="java.util.*" %>
<!-- this is how we declare variables -->
<%! GregorianCalendar greg =
new GregorianCalendar(); %>
<!-- this is how we embed arbitrary code -->
<% greg.add( Calendar.MONTH, 1); %>
<h1>Hello world!</h1>
<p>In one month it will be
<%= greg.getTime() %>
</p>
</body>
</html>
About 'Beans'
- Are Java Beans magic?
- Would Jack think he'd done a good deal if he traded his
old cow for some?
- Unlikely!
- A 'Bean' is just any Java class which
- has a no-argument constructor
- has setter methods with names which conform to the
setVar( Type
value) convention
- has getter methods with names which conform to the
getVar( )
convention
A page which uses a 'Bean'
<?xml version="1.0" encoding="iso-8859-1"?>
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page"
xmlns:html="http://www.w3.org/1999/xhtml"
version="1.2">
<jsp:text>
<html:html
xmlns:html="http://www.w3.org/1999/xhtml">
<html:head>
<html:title>Fifth JSP Page</html:title>
</html:head>
<html:body>
<jsp:useBean id="clock" class="java.util.Date"/>
<html:h1>Hello World!</html:h1>
<html:p>The time is now</html:p>
<html:ul>
<html:li>
Hours:
<jsp:getProperty name="clock" property="hours"/>
</html:li>
<html:li>
Minutes:
<jsp:getProperty name="clock" property="minutes"/>
</html:li>
</html:ul>
</html:body>
</html:html>
</jsp:text>
</jsp:root>
In old syntax
Accessing passed parameters
<?xml version="1.0" encoding="iso-8859-1"?>
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page"
xmlns:html="http://www.w3.org/1999/xhtml"
version="1.2">
<jsp:text>
<html:html
xmlns:html="http://www.w3.org/1999/xhtml">
<html:head>
<html:title>Sixth JSP Page</html:title>
</html:head>
<html:body>
<jsp:directive.page import="java.util.*" />
<jsp:declaration>
GregorianCalendar greg =
new GregorianCalendar();
Integer month = new Integer( greg.get( Calendar.MONTH));
Integer offset = new Integer( 0);
String value = null;
</jsp:declaration>
<jsp:scriptlet>
value = request.getParameter( "offset");
if ( value != null)
{
try
{
offset = new Integer( Integer.parseInt( value));
}
catch ( NumberFormatException nfe)
{
System.out.println( value + " wasn't a number");
}
}
greg.add( Calendar.MONTH, offset.intValue());
</jsp:scriptlet>
<html:h1>Hello World!</html:h1>
<html:p>In
<jsp:expression>offset.toString()</jsp:expression>
months is will be
<jsp:expression>greg.getTime()</jsp:expression>
</html:p>
<html:form action="jsp6.jsp">
<html:label>Input a number</html:label>
<html:input name="offset"/>
</html:form>
</html:body>
</html:html>
</jsp:text>
</jsp:root>
In old syntax
<html>
<head>
<title>Sixth JSP Page</title>
</head>
<body>
<%@ page import="java.util.*" %>
<%! GregorianCalendar greg =
new GregorianCalendar();
Integer month = new Integer( greg.get( Calendar.MONTH));
Integer offset = new Integer( 0);
String value = null; %>
<%
value = request.getParameter( "offset");
if ( value != null)
{
try
{
offset = new Integer( Integer.parseInt( value));
}
catch ( NumberFormatException nfe)
{
System.out.println( value + " wasn't a number");
}
}
greg.add( Calendar.MONTH, offset.intValue());
%>
<h1>Hello World!</h1>
<p>In
<%= offset.toString() %>
months is will be
<%= greg.getTime() %>
</p>
<form action="jsp6.jsp">
<label>Input a number</label>
<input name="offset"/>
</form>
</body>
</html>
Exercise: build a simple Webapp with JSP
Questions and Suggestions for tomorrow
- Any questions or things I haven't been clear enough
about?
- Any things you would like to change about the programme for
tomorrow