Transcript Document

Servlet
• How can a HTML page, displayed using a
browser, cause a program on a server to be
executed?
1
Server side processing
• Traditionally use the CGI (Common Gateway Interface)
mechanism or a server side scripting language.
– CGI - calls an executable program on the server which takes
information passed to it from the browser, processes it and returns
a result (which can take the form of HTML sent to the browser).
Common languages used to write programs called via CGI are:
PERL, C, C++.
– Server Side Scripting/ Includes - takes the request for the page,
runs the page (which contains embedded instructions) through a
program attached to the server to fill in the ‘blanks’ (the scripting
instructions) and sends the completed page back to the browser.
Common languages: asp, php, shtml, jsp.
2
Servlets
•
There is a way for a Java program to respond to a call
from a HTML page. This also solves two of the major
problems associated with client side Java namely:
1.
2.
Not everyone is happy to download Java applets as it takes more
time than a simple HTML page and some users feel that applets
can carry a virus (an urban myth).
Not all browsers have VMs attached. If they do the VM may not
be up to date (for example it may not be able to use SWING
UIs). Microsoft introduced a policy of not packaging a VM with
their browser (unlike AOL/ Netscape) to ‘discourage’ java.
3
Servlets
• A Browser can cause a Java program to be
executed on a server if that Java program is
written in the form of a ‘Servlet’.
• A Servlet does not have a conventional GUI (like
an applet) but sends output to and receives results
from a browser
• The Browser calls or starts the Servlet via a web
server which is configured to know when a web
server is required to perform a task. Recognition is
usually via part of the URL (/servlet/,/jsp/,/jsv/)
4
Servlet execution steps
Step 1: User gives URL to browser
http://www.ucc.ie/servlet/MyServlet
5
Step 2: WebServer realises URL
is not an ordinary file request
www.ucc.ie
/servlet/MyServlet
6
Step 3: WebServer starts VM which loads
Servlet class file
MyServlet.class
VM
7
Step 4: Servlet object created, runs, sends
output back to browser via WebServer
html
html
VM
MyServlet object
8
Servlet Entry Points
• Two methods:
– doGet – called if browser submitted a ‘get
information’ request to the web server (e.g. the
user typed in a URL)
– doPost – called if the browser submitted data to
the web server, for example sent it the results of
a HTML form.
• Note that both methods are protected and
‘throw’ two exceptions
9
How does a servlet communicate
with the browser
• Two objects are passed to the relevant
method in the servlet:
– HttpServletRequest – object contains
information sent to the servlet from the browser
– HttpServletResponse – object to facilitate
transmission of information back to browser
10
Using the response object you can
• Redirect the browser (the redirection does not have to be to
a particular type of web resource)
response.sendRedirect("http://www.ucc.ie/php/go.php?flag=true");
• Open a connection to the browser for transmission of html
response.setContentType("text/html"); // Tell the browser whats coming
java.io.PrintWriter out = response.getWriter(); // Connect to the browser
• Once a connection is open and the browser is aware of what is being
transmitted, can send html to the browser for rendering.
out.println("<html>");
11
Writing a Servlet class
• Have the class extend HttpServlet
• Import javax.servlet.*, javax.servlet.http.*
and java.io.*
• Write an init method which takes a
parameter of type ServletConfig. This init
method is executed only once when the
servlet starts
(Question: Why is there an x in javax.servlet?)
12
Servlet characteristics
• When a web server causes a servlet to start, a new unique
servlet object is automatically created (like an applet)
• A servlet object has all the security clearance of an application
therefore it can communicate with other computers, access
databases, create/ alter files, start programs written in other
languages (via RunTime object), etc. THIS makes servlets
unpopular with sysadmins and allows languages like php to
flourish on basic ISPs
• When the servlet object is finished processing it is not
destroyed. It remains alive so the web server does not have to
wait for a new servlet object to be created and initialised when a
new user sends a request to the server.
• If more that one request is received for a servlet then the
browser queues the eldest request. Queueung and loadbalancing
13
can pose major problems for popular servlets.
Dynamic Server Reloading
• NOTE the above, if you change and recompile a servlet in
an IDE or a deployment environment you must start and
stop the web server so that it erases the old servlet object
and picks up the new code.
• The exception to this rule is if your IDE or deployment
environment (web server) is told to scan servlet directories
for new code then they automatically destroy the old
objects and load the new ones. You must never assume
this happens automatically – always check dynamic
checking is switched on
14
How can many different browsers
use the same servlet object?
• The web server associates a session id with each
browser. The session id is available to the servlet
object so that it can tell if a visiting browser has
used the servlet object during the lifetime of this
servlet object (so for example it can maintain a
shopping cart).
• One or more session objects can be associated
with each session id so data can be kept regarding
each session. This data is usually discarded when
the session is finished. Though you can specify
that data is to be saved in a destroy method.
15
Session - Using
• The command
HttpSession session = request.getSession(true);
will create an object called session which identifies
each individual browser.
• To tell if a browser has visited the servlet before
use:
session.isNew()
which returns true if the visit is the first one.
16
Session - Using
• To store information for a particular session:
session.setAttribute(tag,object);
• Where a tag (key) is a String and object is a
reference to an object (often a String).
Example
session.setAttribute(“username”,”jim”);
17
Session - Using
• To obtain information associated with a browser:
session.getAttribute(tag)
• Which will return the reference to the object
stored (i.e. an address of type Object). Therefore
the result of the call must be cast.
Example
String result = (String) session.getAttribute("username");
or
String result = “”+ session.getAttribute("username");
This returns the String “jim”
18
Example
• servletSession.java
19
HTML Forms
• A user can fill in an HTML form on a
browser.
• The browser can send the HTML form to a
servlet which can extract the contents of the
form.
20
HTML Forms (Hard Wired)
• The easiest way to prepare a form is to use a HTML editor (e.g.
FrontPage) and copy and paste the output into the servlet.
• You must make sure the action associated with a form is the servlet:
out.println("<FORM ACTION=\""+servletURL+"\"
METHOD=\"POST\">");
• You can have the servlet automatically fill in its URL:
out.println("<FORM ACTION=\""+ request.getRequestURI()
+"\" METHOD=\"POST\">");
21
HTML Forms (Hard Wired)
• Each form element should be named:
out.println("<input type=\"submit\"
value=\"buttonName\"
name=\""+buttonName+"\">");
• The contents of the form element can then be
extracted by the servlet using the elements name:
String val=request.getParameter(“username")
If (val==null) val= “”;
• If the element is empty then this returns null
22
Example
• processFormServlet.java
23