Upload
others
View
21
Download
0
Embed Size (px)
Citation preview
Suggested readingSuggested reading
Department of Electronic Engineering 1
Course contentCourse content
• How to write distributed and networked applications• Client server programming – browsers and web servers
• Servlets & JSPs
• Client server programming – specialised clients and serversservers
• Peer to peer programs• JavaScript for client side manipulation
• Ajax
Department of Electronic Engineering 2
Suggested readingSuggested reading
Department of Electronic Engineering 3
Suggested readingSuggested reading
• Heads First Servlets and JSPPassing the Sun Certified Web Component Developer
ExamBryan Basham, Kathy Sierra & Bert BatesO’R ill A t 2004O’Reilly August 2004
Department of Electronic Engineering 4
How to install TomcatHow to install Tomcat
Look at Resource Lecture Karen Shoopalso in Heads First book
http://www.moreservlets.com/Using-Tomcat-4.htmlp g
Department of Electronic Engineering 5
Java Servlets and the HTTP Protocoland the HTTP Protocol
• What are servlets and why are they useful?• Basic servlet structure and lifecycley• Handling request data• HTTP request headersq• Generating the HTTP response• Session trackingSession tracking
Department of Electronic Engineering 6
A general purpose Web Server –e g Apachee.g. Apache
Uses environment variables
Function call
URL & Web Server cgi program
request container e.g Apache
HTTP request
Tomcat container/plug in
response page
HTTP response
Uses java method call on an object page
php container/plug in
p call on an object of type Servlet
Department of Electronic Engineering 7
php scriptStill HTTP
Calling (or browsing) the servlet/cgi/scriptservlet/cgi/script
How to findIt is a servlet
• e.g. http://localhost:8080/servlet/myhelloservlet.HelloServlethttp://localhost:8080/servlet/myhelloservlet.HelloServlet
• calling servlets/cgis/scripts differs from page browsing because you're executing a method of a servlet class instance not just looking at a page. • i.e. you are executing a program .... that usually returns a page
• The servlets/CGI/script handle form input calculations and• The servlets/CGI/script handle form input, calculations and database queries.• JSP is often used to format the results when using servlets.
Department of Electronic Engineering 8
g• Note: The above URL is simplified and only indictive
Why are dynamic pages useful?Why are dynamic pages useful?
• The response web page is based on data submitted by the user, or derived from data that changes frequentlyfrequently• Can use information from corporate databases or other
server-side sources• In principle, servlets could be used for requests
other than via HTTP, though this is not common tyet.
• But e.g SIP servlets are becoming (a little) more common
Department of Electronic Engineering 9
UUses
C ti “ h f t”• Creating an e-commerce “shop front”• programmers use servlets in conjunction with JSP to create
clearer and simpler applications.clearer and simpler applications.
• Providing web interfaces to legacy and data base systemsy• Avoids re-engineering existing system architecture
• Can obtain access through firewalls by “HTTP g ytunnelling”
• c.f. RMI
Department of Electronic Engineering 10
Data is collected and submitted by using an HTML formusing an HTML form
• Each element of a form can have a name and a value• This includes a submit button
• When the submit button is pressed the name value pairs are• When the submit button is pressed the name value pairs are sent to the web server at the URL named in the action part of the form• If a name is not provided the name value pair is not sent• If a name is not provided the name value pair is not sent• Names and values are just strings of characters
• AJAX allows data to be sent using a JavaScript function• Not dealt with in this part of the course – later• So for the moment data is only submitted using a form
• Or a hyperlink, where the name value pairs are hard coded
Department of Electronic Engineering 11
The entire HTML file downloaded so that data can be submittedso that data can be submitted
<HTML><HEAD>… <TITLE> </TITLE.</HEAD><BODY><BODY>
<FORM….>
/ O</FORM></BODY><HTML>
Department of Electronic Engineering 12
<HTML>
ExampleExample
<FORM METHOD=“GET” ACTION=“http://www.eecs.qmul.ac.uk/cgi-bin/cgiprogram”><P> E mail<P> E-mail<INPUT TYPE=“text” NAME=“visitor-email”><P>ComputerP Computer<INPUT TYPE=“radio” NAME=“computer”
value=“Mac”>Macintosh<INPUT TYPE=“radio” NAME=“computer” value=“PC”>Windows<INPUT TYPE=“submit” NAME=“submit” value=“Send Info”>
/FORM
Department of Electronic Engineering 13
</FORM>
If the method is a GET methodIf the method is a GET methodA domain name that has been
registered using DNS
The URL
http://www.eecs.qmul.ac.uk/cgi-bin/cgiprogramis modified by adding the name value pairs
http://www.elec.qmw.ac.uk/cgi-bin/[email protected]&computer=Mac&submit=Send+InfoIf POST th l i dd d ft th t h dIf POST the name value pairs are added after the request header ……………..later The server
determines the
Department of Electronic Engineering 14
interpretation of the path field and beyond
How CGI worksHow CGI works
• Browser requests a cgi program by giving the CGI program’s URLBrowser requests a cgi program by giving the CGI program s URL• started by submitting a form or clicking a link
• Web server checks whether URL refers to a CGI program• usually identified by the path (e.g. contains cgi-bin) or • filename extension (e.g. .cgi or .pl)
• Server executes CGI program as a separate process and passes any• Server executes CGI program as a separate process and passes any data included in the URL to the program (or in the POST body)
• Output is returned to the Web server which is passed to the browser
CGIserverURL request data of request
Department of Electronic Engineering 15
browserCGI program
outputresponse
Request stored in Environment VariablesVariables
• All cgi programs can receive data from web servers via environment variables
• Used to define an environment for a program’s execution• are global with respect to the program• around 20 of them, e.g.
• PATH INFO• PATH_INFO• QUERY_STRING stores the name value pairs
Department of Electronic Engineering 16
Summary: The GET method and CGICGI
• If cgi URL is:• If cgi URL is:http://www.elec.qmw.ac.uk/cgi-bin/cgiprogram
the name value pairs are url encoded and appended to the URL and sentthe name value pairs are url encoded and appended to the URL and sent to the server ashttp://www.eecs.qmul.ac.uk/cgi-bin/cgiprogram?visitor-email=John Bigham@elec qmul ac uk&computer=Mac&[email protected]&computer=Mac&submit=Send+Info
• The server then sets the QUERY STRING environment variable for the Q _process running the cgi program to the name value pairs• the cgi program accesses this variable and parses it
Department of Electronic Engineering 17
An HTTP GET message requestDoesn’t want to use
i
An HTTP GET message request
persistent connectionsGET /somedir/index.html HTTP/1.1
Host: www.chamelion.elec.qmw.ac.ukqConnection: closeUser-agent: Mozilla/4.0
A Netscape browserg
Accept-language:frextra carriage return and line feed
browser
Prefer to receive a
extra carriage return and line feed
Department of Electronic Engineering 18
French version if such a version exists
HTTP t f t
If HEAD , then similar to POST, but
HTTP request message formatserver omits requested object in
response
method sp spURL version cr lf
H d
Request line
Header field name value cr lf:
Header lines
Header field name value cr lf:
……..
cr lffield name
Department of Electronic Engineering 19
Entity body: form name value pairs if POSTNot used if GET
A response messageServer is going to
close the TCP i
p g
HTTP/1 1 200 OKRequest succeeded and
the info is in the response
connection
HTTP/1.1 200 OKConnection : closeDate: Fri, 17th September 2010 12:01:14 GMT
the info. is in the response
Server: Apache/1.3.0 (Unix)Last-Modified: Thur, 16 September 2010 08:44:01 GMTC t t L th 5993Content-Length: 5993Content-Type: text/html Important for caching
(both client and network)C di i l GET
(d d d )
Conditional GETThe official indicator of type, not the file extension
Department of Electronic Engineering 20
(data data data…) entity body
F t f400 Bad
RFormat of response message
Status
Request:
version sp spStatus code phrase cr lf
Header l cr lf:
Status line
field name value cr lf:Header lines
……..Set-cookie12345
Header field name value cr lf:
12345
cr lf
Department of Electronic Engineering 21
Entity body
What are servlets?What are servlets?
• Servlets and JSPs are Java’s equivalent to CGI and• Servlets and JSPs are Java s equivalent to CGI and ASPs.• Are programs that run on web server acting as middle layerAre programs that run on web server acting as middle layer
between HTTP requests and databases or other applications.
• Used to generate dynamic web in response to client.
S l tRequest
Java
pages Tomc
Web
Serv
ServletResponse
Javacat b
ver
HTTP
Department of Electronic Engineering 22Web Browser
Web Server
With Apache and TomcatWith Apache and Tomcat
ServletHttpRequest
Java
Web
Serve
Tom
HTTP
ServletHttpResponse
b er
HTTPm
cat
Web BrowserWeb Server
Department of Electronic Engineering 23
Beans, JSP and Servlets
• Although a servlet can be a completely self-contained program, to ease server-side programming, generating content should be split into:into: • The business logic (content generation), which governs the relationship
between input, processing, and output • The presentation logic (content presentation or graphic design rules) which• The presentation logic (content presentation, or graphic design rules), which
determines how information is presented to the user • Typically,
• the servlet handles the HTTP protocol and coordination of which other servlets• the servlet handles the HTTP protocol and coordination of which other servlets & auxiliary class methods to call
• Java classes/ beans the business logic (model),• Java Server Pages the presentation logic (view)
Department of Electronic Engineering 24
• Java Server Pages the presentation logic (view)
Advantages of servlets over CGI (1)Advantages of servlets over CGI (1)
• Efficient• Servlets run in JVM. Each request is serviced using a thread rather
than a new process (lower overhead)than a new process (lower overhead)• Though some scripting languages e.g. PERL on certain web servers
do this now
• Convenient• Convenient• Provides infrastructure that parses and decodes HTML forms
• Powerful• Can communicate directly with web server• Multiple servlets can share database connections• Simplifies session tracking
Department of Electronic Engineering 25
• Simplifies session tracking
Advantages of servlets over CGI (2)Advantages of servlets over CGI (2)
• Portable• Written in Java and follow standard API
• Secure• CGI often executed using O/S shells, which can cause
many security breaches• Array checking & exception handling automatic in Java
I i• Inexpensive• Many Java web servers freely available
Department of Electronic Engineering 26
A general purpose Web Server –e g Apachee.g. Apache
Servlet URL W b S
service() methodcgi
servlet
& requestrequest request
response
Web Server container
servlet
response page
response
phppage
Department of Electronic Engineering 27
Servlet container, or engine app
Tomcat “plug in”
What servlets doWhat servlets do
R d d t t b th ( li it)• Read any data sent by the user (explicit)• Look up info embedded in HTTP request (implicit)• Generate results• Format results inside a document Format HTML or XML or GIF or Excel..
• Set appropriate HTTP response parameters• Send the document back to the client
Department of Electronic Engineering 28
Typical generic servlet codeTypical generic servlet code
public class AnyServlet extends GenericServlet {
public AnyServlet() {} // DO NOT write constructor –USE DEFAULT
bli id i it(S l tC fi fi ) th
ONLY creates an object.
ONLY becomes a “proper” servlet after init
public void init(ServletConfig config) throwsServletException;
// The method actually called by container when servlet is first created or loadedfirst created or loaded
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException;// called by a new thread in the container each time a //request is received
Department of Electronic Engineering 29
public void destroy();// called before servlet is to be destroyed
}
Servlet is “deployed” in a container which iscontainer, which is…..
• a program that receives (e.g. HTTP) requests to servlets p g ( g ) qfrom a web server application • finds the servlet (and loads, calls constructor & init if not ready)• creates or re-uses a thread which will call the service method ofcreates or re uses a thread which will call the service method of
chosen servlet• creates & passes request and response objects to the chosen servlet • passes the response (e.g. HTTP response) back to the web server p p ( g p )
app; kills servlet thread or recycles into thread pool; and deletes request and response objects
• More generally, manages the life cycle of its servlets• Calls constructor, init, service, destroy• also invokes methods of listening classes that a servlet implements
• It has a “main” and is working “all the time”
Department of Electronic Engineering 30
It has a main and is working all the time
Also providesAlso provides
• declarative security using settings in Deployment Descriptor
• JSP support
Department of Electronic Engineering 31
The servlet life cycle
Call constructor
The servlet life cycleat first request or
server start up (depending on web server
configuration)
Called once onlye.g. Can be used
Exists but not ready for
work
init(..)
doGet(..)
doDelete(..)configuration) g
for opening a DB connection
waiting for client requests
request
GET
doOptions(..)
i i
Should be thread safe
service(..) doPost(..)POST
doPut( )
on receiving request
doTrace(..)
doPut(..)
destroy(..)at server shutdowne.g. Can be used for closing a DB
Department of Electronic Engineering 32
closing a DB connection
can now be g.c.
If HTTPServlet
Mapping names using the DDMapping names using the DD
F h l t i th b <web-app ….><servlet>
<servlet-name> </servlet-name>
For each servlet in the web application
<servlet name>….</servlet name><servlet-class>…</servlet-class>
</servlet>< l t i >
maps internal name to fully qualified class name.
(except without .class)<servlet-mapping>
<servlet-name>….</servlet-name><url-pattern>…</url-pattern > maps internal name to public
URL name</servlet-mapping>………………….</web-app>
URL name
e.g. /makebooking
Department of Electronic Engineering 33
</web app>Internal name can be “anything”
following XML rules
Lots m
ore g
oes h
ere
A complete servletA complete servlet
import javax servlet *; GenericServleti ( )import javax.servlet. ;import javax.servlet.http.*;import java.io.*;
GenericServlet
HttpServlet
service(..)
service(..)
public class S1 extends HttpServlet{public void doGet(HttpServletRequest req
HttpServletservice(..)
public void doGet(HttpServletRequest req,HttpServletResponse res) throws IOException {
res.setContentType("text/html");PrintWriter out = res.getWriter();
out.println(“<html><body>Hello!</body></html>”);}}
Department of Electronic Engineering 34
}
Why we do not need to write a service method for an HttpServletservice method for an HttpServlet
serviceGenericServlet
Over rides
serviceHttpServlet
Class objects
service in GenericServlet
doGetS doGet
doPostS1
Department of Electronic Engineering 35instance
service(…)
Its DDIts DD<web-app xmlns=“http://java.sun.com/xml/ns/j2ee”
xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”xsi:schemaLocation=“http//java.sun.com/xml/ns/j2ee”web-app_2.4.xsd”version=“2.4” >
<servlet> <servlet-name>Hello World Servlet</servlet-name><servlet-class>S1</servlet-class>
</servlet><servlet-mapping>
This example is so simple
there is no <servlet-name>Hello World Servlet</servlet-name><url-pattern>/Hello</url-pattern >
</servlet-mapping>
input data
Department of Electronic Engineering 36
pp g</web-app> http://localhost:8080/Hello
Typical HTTPServlet codeTypical HTTPServlet code
import javax servlet http *;import javax.servlet.http.*;import javax.servlet.*;
public class AnyHttpServlet extends HttpServlet {public class AnyHttpServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)p p p
throws ServletException, IOException;// called when HTTP request uses GET
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException; // ll d h HTTP t POST
Department of Electronic Engineering 37
// called when HTTP request uses POST}
Handling the Client Request:HTML Form DataHTML Form Data
• Form data (or query data) is used to transfer information to the server-side program via POST or GET methodsor GET methods.
• Servlets have built-in features to parse this data• no need to extract attribute-value pairs AKA key-value pairsno need to extract attribute-value pairs• no need for URL-decoding (much nicer than CGI!).
• ServletRequest methods:
AKA key value pairs
q• String getParameter(String);• Enumeration getParameters();St i [] tP t V l (St i )
Department of Electronic Engineering 38
• String [] getParameterValues(String);
A Small FormA Small Form
Department of Electronic Engineering 39
Obtain single parametersSmallForm htmlSmallForm.html
<html><title>Sending Form Information to a Servlet</title>g<body>
<form action="http://localhost:8080/servlet/elem004 ProcessSmallForm"action="http://localhost:8080/servlet/elem004.ProcessSmallForm" method="post">
Please input your login: <br> NB. Can use absolute<input type="text" name="Login"><input type="submit" value="Login">
</form>
NB. Can use absolute or relative URLs or pre-configured names
</form></body></html>
Department of Electronic Engineering 40
Extract fromProcessSmallForm javaProcessSmallForm.java
public void doPost( ) {public void doPost(…) { …// obtain the login from the Request objectString loginName = req.getParameter("Login");
out.println("<html><head>");out.println("<title>Form Processed!</title></head>\n");out.println("<h1>Hello, ");
if(loginName != null)out.println(loginName);
elset i tl (" t ")out.println("mystery person");
out.println(“</h1></body></html>");out.close();
Department of Electronic Engineering 41
()} NB Almost but not complete –
need PrintWriter and need to setContentType
After form is processedAfter form is processed
Department of Electronic Engineering 42
Simple exampleSimple example
CounterServlet dproduces a page
displaying the number of requestsnumber of requests the servlet has processed since it pwas first created.
Department of Electronic Engineering 43
CounterServlet’s dutiesCounterServlet’s duties
• Must keep track of how many requests it has serviced, so …• when created must load previous value• when destroyed must save current value
• For each request, increment the counter.• Generate some HTML to display the results.• Will be in a file called CounterServlet.java
Department of Electronic Engineering 44
countVal is an instance variablecountVal is an instance variable
import javax.servlet.http.*;import javax.servlet.*;import java.io.*;
It is important that this is an int not e.g. a doubleimport java.io. ;
public class CounterServlet extends HttpServlet {i t tV l C it h d h
g
int countVal;
public void init() …….
Can use it here and here
public void doGet(HttpServletRequest req, HttpServletResponse resp) {..}
Department of Electronic Engineering 45
HttpServletResponse resp) {..}
CounterServlet java (1)CounterServlet.java (1)
public void init() throws ServletException {public void init() throws ServletException {
try { // to read in value of counter
BufferedReader countFile = Text open("count txt");BufferedReader countFile = Text.open( count.txt );
String valString = countFile.readLine();if(valString != null)
countVal = Integer parseInt(valString);countVal = Integer.parseInt(valString);else
countVal = -9999;System.out.println("Counter Servlet initialised, ");System out println(" countVal is " + countVal);System.out.println( countVal is + countVal);countFile.close();
}catch (..) { // ..etc }
}
Department of Electronic Engineering 46
}
CounterServlet java (2)CounterServlet.java (2)
public void doGet(HttpServletRequest req HttpServletResponse res)public void doGet(HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException {// just refer to doPost(..)doPost( req, res );
}}
public void doPost(HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException {
res.setContentType("text/html");
// obtain output stream (ie what will be displayed in browser)PrintWriter out = new PrintWriter(res getOutputStream());
Note default is plain text
PrintWriter out = new PrintWriter(res.getOutputStream());
out.println("<html>");out.println("<head><title>Request Counter Servlet</title>");out println("</head><body>");
Department of Electronic Engineering 47
out.println( </head><body> );
CounterServlet java (3)CounterServlet.java (3)
countVal++; // counter incremented if new sessioncountVal++; // counter incremented if new session
out.println("<b>This servlet has processed " + countVal+ " request(s)</b><br>");
out.println("</body></html>");out.close();
}
public void destroy() { // overrides GenericServlet.destroy(..)try { // save countVal back to file
PrintWriter countFile = Text.create("count.txt");countFile println(countVal);countFile.println(countVal);System.err.println("Request counter written to file");countFile.close();
}catch( ) { // etc }
Department of Electronic Engineering 48
catch(..) { // ..etc }}
Servlet initialisation & Servlet Configuration objectConfiguration object
NB. Need to prevent race conditions (or use single
th d d l d t d)• Only one servlet instance is created • each request serviced by a separate thread in container
• Prior to initialisation the ServletConfig object created by the container
thread model - deprecated)
container• One ServletConfig object per servlet• Container uses it to pass deploy time information to the servlet
• Facts you do not want to hard code into the servlet, e.g. DB name• The names are specified in the DD
• Parameters are set in a server-specific manner, e.g.• in Tomcat in a file called web.xml• in Resin in a file call resin config• in Resin in a file call resin.config
• Parameters do not change while servlet is deployed and running• Like constants• If change need to redeploy
Department of Electronic Engineering 49
Example of init parameters in a DD (web xml for tomcat)(web.xml for tomcat)
<servlet> <servlet-name>Hello World Servlet</servlet-name><servlet-class>S1</servlet-class>
<i it ><init-param> <param-name>lecturersEmail</param-name>< param-value >john@elec qmul ac uk</ param-value >< param value >[email protected]</ param value >
</ init-param ></servlet> Container reads these and gives to
Department of Electronic Engineering 50
gServletConfig object
Getting a parameter value from the ServletConfig objectthe ServletConfig object
out.println(getServletConfig().getInitParameter(“lecturersEmail”)g g() g ( )
Returns the servlet’s ServletConfig objectServletConfig object
All servlets have this method
Department of Electronic Engineering 51
You usually write an init method with no parameterswith no parameters
public void init() throws ServletException {
……………… YOU HAVE SEEN THIS
}• This is called when the system calls the inbuiltThis is called when the system calls the inbuilt
init method with one parameter
Department of Electronic Engineering 52
..but there is an old version of the init methodinit method
public void init(ServletConfig config) throws ServletException {
super.init(config); …………………………..}
• if you write this method must call super.init(…) firsty p ( )
• as you need to ensure the inbuilt init method with the corresponding parameter is invoked
• Was used as a way of getting out hands on the ServletConfig y g g gobject
• Not used much now as can get the ServletConfig object• by using getServletConfig().
Department of Electronic Engineering 53
by using getServletConfig().
Extracting initialisation variablesExtracting initialisation variables
• The ServletConfig object contains parameter’s• The ServletConfig object contains parameter s from the server’s configuration file • config object retrieved using getServletConfig()co g objec e eved us g getSe etCo g()
method
• Parameters are read from the configuration file and are stored by init method for later use • are extracted from config in a portable way by
S i i (S i )String getInitParameter(String)
Department of Electronic Engineering 54
Typically you would writeTypically you would write….
public void init() throws ServletException {String initPath= g
getServletConfig().getInitParameter(“count_file”);try { // to read in value of counter
BufferedReader countFile =Text.open(initPath);p ( );………
}
Department of Electronic Engineering 55
}
• In DD<servlet>
< l t >Th C ti S l t</ l t ><servlet-name>The Counting Servlet</servlet-name><servlet-class> CounterServlet </servlet-class>
<init-param> <param-name>count_file</param-name>
l / l< param-value >count.txt</ param-value ></ init-param ></servlet>
Department of Electronic Engineering 56
</servlet>
Location of servletsLocation of servlets
• Depends on the web server you’re using but for Tomcat and Resin, servlets should be put in:
/WEB-INF/classes
Department of Electronic Engineering 57
Department of Electronic Engineering 58
This is %CATALINA HOME%
Department of Electronic Engineering 59
This is %CATALINA_HOME%
Department of Electronic Engineering 60
Department of Electronic Engineering 61
All your web applications go in here
Department of Electronic Engineering 62
All your web applications go in here
Inside webappsInside webapps
• Here are two web applications• Usually many morey y
Department of Electronic Engineering 63
Department of Electronic Engineering 64
Inside the Chaining2005 web applicationapplication
Servlets go in the classes folder in
here
Department of Electronic Engineering 65
HTML & JSP files go here
What there is in the ITLWhat there is in the ITL
• You do not see webapps! It is shared by all students.
• You create a directory inside webapps. • I have called mine johnb – my user name
Path in webapps
• To invoke the downloading of an html file held in johnb directory
e.g. http://tomcat_stu.dcs.qmul.ac.uk/ johnb/Currency.htmlMust contain servlet
because of way Apache is configured
• To invoke a servlet
http://tomcat_stu.dcs.qmul.ac.uk/ johnb/servlet/CC
Y dd l f ld h l d j fil i j h b d di h i i b l
Apache is configured
Apache
• You can add a classes folder, html and jsp files in johnb and edit the existing web.xml
NB You cannot create subdirectories each with their own web.xml!
<servlet-mapping>
<servlet-name>My Servlet</servlet-name>
Department of Electronic Engineering 66
y
<url-pattern> /servlet/CC </url-pattern >
</servlet-mapping>
input htmlinput.html
It i l thi b f <html><head><title> Input book isbn </title> </head><body>
It is only this because of what I have in the
web,xml filey
<!-- <form method="POST" action= "introspection.jsp"> --><form method="POST" action=
"http://localhost:8080/Chaining2005/CH">
<input type="text" name="isbn" value=""><input type="submit" >
The name I have given for the
servletp yp</form></body></html> The web app
Department of Electronic Engineering 67
Inside WEB INFInside WEB-INF
Department of Electronic Engineering 68
The DD
N t f ll Note: full name starts from classes following package
structure
Department of Electronic Engineering 69
Inside classesInside classes
Department of Electronic Engineering 70
Inside chainInside chain
Department of Electronic Engineering 71
Inside classes/chain/webInside classes/chain/web
Department of Electronic Engineering 72
Inside classes/chain/modelInside classes/chain/model
Department of Electronic Engineering 73
Keep your servlet code in a similarly structured foldersimilarly structured folder
Department of Electronic Engineering 74
Where we keep the java source for compilationcompilation
h d f h
The corresponding folder
The code for the Chaining2005 web
app
Department of Electronic Engineering 75
The corresponding folder
Copy into tomcat class di tdirectory
Compile creates the directory structure
This has same structure as classes seen before but
with source code
Department of Electronic Engineering 76aide memoir
Remember - same structure
Department of Electronic Engineering 77
Department of Electronic Engineering 78
Compiling from Chaining2005 DLMDLM
javac -classpath C:/jakarta-tomcat-5.0.28/jakarta-tomcat-5.0.28/common/lib/servlet-api.jar;classes;.
-d classes src/chain/web/AddNameServlet.java
javac -classpath C:/jakarta-tomcat-5.0.28/jakarta-tomcat-j p j j5.0.28/common/lib/servlet-api.jar:classes:.
-d classes src/chain/model/BookBean.java
Department of Electronic Engineering 79
AddNameServlet.java – package namename
Department of Electronic Engineering 80
Do this whenever you change your recompile!recompile!
And start again!
Department of Electronic Engineering 81
g
Running a web serverRunning a web server
• To access Tomcat please refer to the instructions on student intranet under• Student Homepage → Computing → HOW TO... →
Use the Tomcat Java Web Server
If i l t d l d R i if• If using own laptop you can download Resin if you prefer from
http://www caucho com/download/http://www.caucho.com/download/
• Follow instructions for installation, set up and how to run the web server
Department of Electronic Engineering 82
to run the web server.
Extracting unknown parameters and multiple valuesand multiple values
d hNB. Case sensitive
• String getParameter(String) used when parameter name is known• returns null if unknown parameterreturns null if unknown parameter• returns "" (empty string) if parameter has no value
• Else use Enumeration getParameters() to obtain parameters
• Then String[] getParameterValues(String) t bt i f l f hto obtain an array of values for each one• returns null if unknown parameter• returns a single string (“”) if parameter has no values
Department of Electronic Engineering 83
etu s a s g e st g ( ) pa a ete as o va ues
A Big FormA Big Form
Department of Electronic Engineering 84
BigForm htmlBigForm.html<form action="http://localhost:8080/servlet/elem004.ProcessBigForm"
method="post">method= post >Please enter: <br><br>
Your login: <input type="text" name="Login"> <br><br>
Single value parameters
Your favourite colour:<input type="radio" name="Colour" value="blue">Blue<input type="radio" name="Colour" value="red">Red<input type="radio" name="Colour" value="green">Green <br><br><input type= radio name= Colour value= green >Green <br><br>
Which of these courses you are taking: <br><input type="checkbox" name="Course" value="elem001">ELEM001 <br><input type="checkbox" name="Course" value="elem002">ELEM002 <br><input type= checkbox name= Course value= elem002 >ELEM002 <br><input type="checkbox" name="Course" value="elem003">ELEM003 <br><input type="checkbox" name="Course" value="elem004">ELEM004 <br>
<input type="submit" value="Send to Servlet">
Department of Electronic Engineering 85
<input type= submit value= Send to Servlet ></form> Multiple value parameter
ProcessBigForm java (1)ProcessBigForm.java (1)
out.println("<table border=1>");
// obtain all the form’s parameters from the request objectEnumeration paramNames = req.getParameterNames();Enumeration paramNames req.getParameterNames();
while(paramNames.hasMoreElements()) {String paramName = (String) paramNames.nextElement();
//obtain values for this parameter and check how many there areString [] paramValues = req.getParameterValues(paramName);
if(paramValues.length == 1) { // a single valueif(paramValues.length 1) { // a single value
String paramVal = req.getParameter(paramName);out.println("<tr><td>" + paramName +"</td><td>"
+ paramVal + "</td></tr>");
Department of Electronic Engineering 86
+ paramVal + </td></tr> );}
ProcessBigForm java (2)ProcessBigForm.java (2)
else { // if several values print a list in the table
out.println("<tr><td>" + paramName +"</td><td><ul>");
for(int i = 0; i < paramValues.length; i++)out.println("<li>" + paramValues[i]);
out.println("</ul></td></tr>");out.println( </ul></td></tr> );}
}out.println("</table>");out.println( </table> );
Department of Electronic Engineering 87
After Big Form is processedAfter Big Form is processed
Department of Electronic Engineering 88
NB. getParameterNames() returns them in no particular order
HTTP Request Headers (1)HTTP Request Headers (1)
• As with form data, HTTP request headers can be extracted from the HTTPServletRequest object
• Usually use String getHeader(String)NB. not case sensitive
• Some common headers have their own methods• getContentLength()• getContentType()• getContentType()
• Can also access all headers using• Enumeration getHeaderNames()
Department of Electronic Engineering 89
g ()
HTTP Request Headers (2)HTTP Request Headers (2)
• Information on the main request line also has its own methods• getMethod()• getRequestURI()• getProtocol()g ()
• Servlet to extract all information:
Department of Electronic Engineering 90
ShowRequestHeaders outputShowRequestHeaders output
Department of Electronic Engineering 91
Generating the Server ResponseGenerating the Server Response
• Response typically consists of• a status line (containing version, status code + message)• some response headers• a blank line
Version
MessageStatus-code
• the document
• e.g., HTTP/1.1 200 OKContent Type: text/plain
Versionresponse header(s)
Content-Type: text/plain
Hello World!blank line
Department of Electronic Engineering 92document (here just one line of text)
HTTPServletResponseHTTPServletResponse
• Servlets can perform a variety of tasks by manipulating the status line and response headers, for example• tell user that a password is required
i di f h d d (i df h l)• indicate type of attached document (image, pdf, html)• forward user to other sites• etc• etc.
Department of Electronic Engineering 93
HTTP Status CodesHTTP Status Codes
• returned by the server to the client software to indicate the outcome of a request, e.g.
• 200 - OKThe request sent by the client was successful. 301 - Moved PermanentlyThe resource has permanently moved to a different URI.
• 303 See Other• 303 - See OtherThe requested response is at a different URI and should be accessed using a GET command at the given URI.
• 400 - Bad RequestqThe syntax of the request was not understood by the server.
• 403 - ForbiddenThe server has refused to fulfill the request.
Department of Electronic Engineering 94
Setting the status codeSetting the status code
• The servlet only needs to set the status code since the version is determined by the server and the message is associated with the status codemessage is associated with the status code.
• Usual method is simply to call response.setStatus(int)response.setStatus(int)
• If your response includes a special status code anda document you must call setStatus before returning any content via the PrintWriter. • This is because the document itself may not be buffered
but sent in pieces e g a large image file
Department of Electronic Engineering 95
but sent in pieces, e.g. a large image file.
Special status codesSpecial status codes
• Status codes are integers but it’s better to use the constants defined in HTTPServletResponse class
e g HTTPS l tR SC NOT FOUND• e.g., HTTPServletResponse.SC_NOT_FOUND
• Two common codes have special methodsStatus code 404
public void sendError(int sc, String message)
• this sets the status code plus a short messagepublic void sendRedirect(String url)
• generates a 301 response along with a Location header giving the URL of the new document that the browser should now request
Department of Electronic Engineering 96
SettingStatusCodes htmlSettingStatusCodes.html
Department of Electronic Engineering 97
Key part of formKey part of form
<input type="submit" name="non-file" value="Fetch a non-existent file">
<input type="submit" name="redirect" value="Redirect to homepage">
<input type="submit" name="censored" value="Fetch censored content">
Only used to generate cases, in practice we find out that the
Department of Electronic Engineering 98
practice we find out that the case has arisen by looking at
file system, etc.
Extract fromSetStatusCode javaSetStatusCode.java
bli id d P t(Htt S l tR t Htt S l tR )
Somehow know that file does not exist, so..
public void doPost(HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException {
// generate response according to submit button was pressedif( eq getPa amete ("non file") ! n ll)
fudge404 USED WHEN NOT FOUND
if(req.getParameter("non-file") != null)res.sendError(res.SC_NOT_FOUND,
"The file you requested does not exist!");
if(req getParameter("redirect") ! null) Explain later
FORMATTED & RENDERED BY BROWSER
if(req.getParameter("redirect") != null) res.sendRedirect(res.encodeURL("http://localhost:8080/"));
if(req.getParameter("censored") != null) res setStatus(res SC FORBIDDEN); i b li
p
res.setStatus(res.SC_FORBIDDEN);
res.setContentType("text/html");PrintWriter out = res.getWriter();out println(“<html>”);
Send content only after status code set;
May exist but client not allowed to read it, so..
Department of Electronic Engineering 99
out.println(“<html>”); code set;
RESPONSE OF SEVLET MAY NOT BE BUFFERED AND ORDER
MATTERS
After “redirect” button pressedAfter “redirect” button pressed
Department of Electronic Engineering 100
res.sendRedirect("http://localhost:8080/");;
• When a servlet decides request should go to a different URl• Calls sendRedirect(..) on response objectCalls sendRedirect(..) on response object
• Container sends response “302” status code with a location header containing the new URL as valueB d d l ti h d d k• Browser reads response and location header, and makes new request using the URL (might see this in the browser)
• “Original” request now goes to the new URL• Which could refer to another servlet (not in this example)
• MUST be called BEFORE any writing to the response object
Department of Electronic Engineering 101
object
• 301 moved permanently• 302 moved temporarilyp y
• Most browsers treat them the same
Department of Electronic Engineering 102
Request DispatchRequest Dispatch
• Servlet wants request to go to a different servlet or JSP in the web app
l ll• Servlet callsRequestDispatcher
view=request getRequestDispatcher(“display jsp”);view=request.getRequestDispatcher( display.jsp );view.forward(request, response);• Now the JSP is invoked as if it were invoked directly• Now the JSP is invoked as if it were invoked directly
by the client• The client will only see the URL of the original servlet
Department of Electronic Engineering 103
Setting Response HeadersSetting Response Headers
• Response headers are are set using the methodres.setHeader(String header, String value);
• Examples include:• Allow, Content-Encoding (e.g., gzip), Content-Language (e g en en-us)Content-Language (e.g., en, en-us), Content-Length, Content-Type, Date, Expires, Last-Modified, Location, Refresh, Set-Cookie, WWW-Authenticate
Department of Electronic Engineering 104
Support methodsSupport methods
• Setting some headers is so common that special support methods exist:setDateHeader(String header,long msecs)setIntHeader(String header, int value)
( i )setContentType(String type)setContentLength(int length)addCookie(String cookie)addCookie(String cookie)sendRedirect(String encodedURL)
Department of Electronic Engineering 105
Setting the Refresh headerSetting the Refresh header
• Indicates how soon (in seconds) the browser should ask for an updated page
res setHeader(“Refresh” “30”);res.setHeader(“Refresh”, “30”);
• specifies next update (not continual) so need to set header each time
• sending status code 204 (NO_CONTENT) stops browser reloading further
• 204 - No ContentThe request was successful but does not require the return of an entity-body.
• can also be used to redirect to another page
Department of Electronic Engineering 106
res.setHeader(“Refresh”, “5; URL=http:/host/path”);
Does not mean reload every 5 seconds
RefreshClock javaRefreshClock.java
Department of Electronic Engineering 107
extractextract
res.setContentType("text/html");res.setHeader("Refresh", "1");
PrintWriter out = res.getWriter();
t i tl ("<ht l><h d>")out.println("<html><head>");out.println("<title>Telling the Time</title>");out.println("</head><body><h1>");
……
out println(new Date());
Department of Electronic Engineering 108
out.println(new Date());
Setting the Content Type headerSetting the Content-Type header
• Content-Type tells browser what sort of document is being sent.S f ’ l d l• So far we’ve only used only text/html
• Generally of form maintype/subtype e.g., t t/ l i t t/ht l t t/• text/plain, text/html, text/css
• image/gif, image/png, image/jpeg, image/tiff• application/pdf, application/mswordpp p , pp• video/mpeg, video/quicktime
• Must be set before writing to the OutputStream.
Department of Electronic Engineering 109
The browser does not render this like html
Is any content type acceptable?Is any content-type acceptable?
May need to check which types browser supports• use String req.getHeader(“Accept”) and check
that output string contains the format you wish to send
String types = req.getHeader(”Accept”);
if(Utilities.contains(types, “image/jpeg”)) {res.setContentType(“image/jpeg”);// send a jpeg file
} } else {
res.setContentType(“image/gif”);// send a gif file
}
Department of Electronic Engineering 110
}
Creating an Excel spreadsheetCreating an Excel spreadsheet
• As well as sending back html, servlets can dynamically create and send back more specialised content.
• The following example shows a servlet that l d h i f d icreates an Excel spreadsheet using form data input
by the user to format and fill the cells.
Department of Electronic Engineering 111
MakeTable htmlMakeTable.html
Department of Electronic Engineering 112
Extract from CreateSpreadSheet javaCreateSpreadSheet.java
tC t tT (" li ti / d l")res.setContentType("application/vnd.ms-excel");PrintWriter out = res.getWriter();
out.println("<table>");fo (int 0 < o s ++) {for(int r = 0; r < rows; r++) {
out.println("<tr>");for(int c = 0; c < cols; c++) {
out.println("<td bgcolor=\"" + colour + "\" >" + chars charAt(next++) + "</td>");+ chars.charAt(next++) + "</td>");
next %= mod;}out.println("</tr>");
}}out.println("</table>");out.close();
Department of Electronic Engineering 113
Output from CreateSpreadSheetOutput from CreateSpreadSheet
Department of Electronic Engineering 114
ServletContext object is created for a web appfor a web app
• One per web app• A web app normally has several servlets (& JSPs)
• Used to access web app parameters that need to be seen by all servlets (& JSPs) in the application• Held as parameters in the ServletContext object• A misnomer as relates not to a servlet but the set of
servlets and JSPsin the web appservlets and JSPsin the web app
Department of Electronic Engineering 115
The DD of the web app specifies the context parametersthe context parameters
<web-app …>……<servlet>
<servlet-name>… </servlet-name><servlet-class>… </servlet-class><init-param><param-name>….</param-name>p p p
<param-value>….</param-value> </init-param></servlet> … + other servlets
Note: Not inside any servletServletContext object created
<context-param><param-name>HOD_Email</param-name><param-value>[email protected]</param-value>
and set up when web app
is deployedparam value [email protected] /param value
</context-param>..</web-app>
Department of Electronic Engineering 116
</web app>These are parameter name value pairs:
both are strings
To access parameters in servlet codecode …
ServletContext ctx = getServletContext()out.println(ctx.getInitParameter(“HOD Email”)p ( g ( _ )); Note: Same name for get
method as when accessing ServletConfig
• Context parameters generally more commonly used
accessing ServletConfig object
Context parameters generally more commonly used than Config• Typical use (of former) a DB lookup name
Department of Electronic Engineering 117
Can access ServletContext()Can access ServletContext()….
• directlygetServletContext().getInitParameter(….)g () g ( )• from ServletConfiggetServletConfig().getServletContext().getInitParamter(…..)g g() g () g ( )
Latter useful if in a method of an auxiliary class, e.g. a bean,Latter useful if in a method of an auxiliary class, e.g. a bean, and only the ServletConfig object has been passed as a parameter
Department of Electronic Engineering 118
ServletContext also has AttributesServletContext also has Attributes
• Parameters are name value pairs, where both name and value are strings
• Attributes are name value pairs where the name is a string, but the value is an object (that may not be
i )a String)• Accessed by getAttribute(String)
S t b tAtt ib t (St i Obj t)• Set by setAttribute(String, Object)
Department of Electronic Engineering 119