Java
Servlets
Every servlet has to implement the Servlet interface.
Most servlets
will implement this interface indirectly
by extending Servlet implementation classes,
either
GenericServlet or HttpServlet.
GenericServlet is extended when developing a
protocol-
independent servlet, while HttpServlet is normally extended
for an HTTP dependent
servlet. Because the Web is based
on HTTP, HttpServlet is the more commonly used class.
Servlets are a Hosted Form Like Applets
Servlet are like applets in that they work in
a runtime
context provided by a hosting
application. In the case
of servlets,
this application is the web server. Instead
of using a main( ) method, the servlets
have a 'life cycle'
of methods that are called in association
with the request
and response behaviour being executed by
the web
server.
The service( ) method
We look at the servlet life cycle later. At
the heart of the
life cycle of a generic servlet is the
service( ) method.
The service
method is called when the server delegates
the handling a request to a servlet. A
generic servlet
normally overrides the service( ) method
to handle a
request.
Diagram of a servlet response
// adapted from 'Java Servlet
Programming', (see refs.)
request --> |
Web |
--> |
Servlet's |
response <-- | Server
| <-- | service( ) |
Using doGet( ) and doPost( ) with an HTTP servlet
Using an HTTP servlet a different approach is
taken. The
service( ) method is not overidden.
Instead the doGet( )
doPost( ) methods are overidden. In this
variation, the
service method calls all the
doXXX( ) methods and so
is normally not modified in any way.
Diagram of a HTTP Servlet
Response Either GET or POST
// from ' Java Servlet Programming'
GET <-> Web <->
HTTPServlet
service( ) calls doGet( )
//request/response
POST <-> Web <->
HTTPServlet
service( )calls doPost( )
// request/response
An HTTP servlet has methods for the less
commonly used
HTTP methods, including doPut( ),
doDelete( ), doHead( ),
doTrace( ) and doOptions.
Jason Hunter in his book, 'Java Servlet
Programming' figures
this is a good point to introduce 'Hello
World' so we do the same.
If
we may speak, casually, Jason Hunter is
sort of the 'first guru'
to Servlets,
something like what Danny Goodman is to
JavaScript,
Dave Flanagan is to Java. (Dave
Flanagan is the writer of 'Java
in a Nutshell'). Jason Hunter is certainly
the most vocal supporter
of servlets.
// Marty Hall is the 'other first guru' for servlets and JSPs.
Jason Hunter maintains the servlet site at
www.servlets.com
and also has a newletter you can
subscribe to. Back to Hello
World.
Hello World in a Servlet
// from 'Java Servlet
Programming', Jason Hunter & William Crawford
// or HelloWorldExample in Tomcat
// trivia courtesy of Jason
Hunter: The first 'HelloWorld' was written by Brian
// Kernighan in 1973 while
working at Bell on the B programming language.
// B was the precursor to the
C programming language. (So was there an A?)
A Quick Technique to Run the 'Hello
World'
Servlet
Later we will
look at standards that have been developed to package
web applications. For now we just want to find a directory where we
can put our servlet to run it. Assuming you are running Apache's 'Tomcat',
install the servlet source code and class file under the following
directory.
Example \tomcat\jakarta-tomcat-3.2\webapps\examples\WEB-INF\classes
Open a browser on the servlet.
Example
http://localhost:8080/examples/servlet/HelloWorld
Processing Form Data With Servlets
Servlets become more meaningful when we begin to use
them to process
form data. Incoming client data is carried
in an HttpServlet in a
HttpServletRequest object.
HttpServletRequest is in the first case an interface that
itself
extends the ServletRequest interface. ServletRequest defines
the methods needed to
extract form data. Following are the
signatures of the set of methods that can
be used to process
form data.
The simplest to use and most popular are getParameter( )
and getParameterValues( ), the latter which returns a String
array which is easy to process.
ServletRequest getParameter Methods
// HttpServletRequest is a
sub-interface of
ServletRequest
String
getParameter (String name) |
returns parameter as a String or null if non-existent |
java.util.Map getParameterMap( ) |
returns a Map object of parameters |
java.util.Enumeration
getParameterNames( ) |
returns an
Enumeration of String objects containing the names of the parameters contained in this request. |
String[] getParameterValues (java.lang.String name) |
Returns an array
of String objects containing all of the values the given request parameter has, or null if the parameter does not exist. |
HTML with a
Simple Form
Following is an HTML page that allows a user to enter some
text and
press a submit button to have it processed. The
process is set to send the
data to the Hello_Form servlet.
In this form a GET method is specified.
HTML Page with a FORM Element Using the GET Form
<HTML>
<HEAD>
<TITLE>Hello Form</TITLE>
</HEAD>
<BODY>
<H2>Hello!</H2>
<HR/>
<FORM METHOD=GET ACTION="Hello_Form">
Hello! May I ask, who are you?
<INPUT TYPE=TEXT NAME="name"<P>
<INPUT TYPE=SUBMIT>
</FORM>
Data Transfer With Get The GET Form
Because the GET method is used the data is appended
to the URL that
will be sent to the server. If we are running
local host the url that is
sent will be something like the
following.
Example of a URL sent with a GET
http://localhost:8080/examples/servlet/Hello_Form?name=Billy+the+Kid
Back
to HelloWorld To Capture Data
The HelloWorld Servlet can be enhanced to provide a
dynamic response
to the form submission. The only
consequential changes are highlighted
in red. The key
call is getParameter( ) which retrieves the parameter
that
was appended to the client's GET request.
Hello_Form, A Servlet With a Response to a Form Submission
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Hello_Form extends HttpServlet{
public void
doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException{
res.setContentType("text/html");
PrintWriter out=res.getWriter( );
String name=req.getParameter("name");
out.println("<HTML>");
out.println("<HEAD><TITLE>Hello_Form</TITLE></HEAD>");
out.println("<BODY>");
out.println("<BIG>Hello " + name + "! </BIG>");
out.println("</BODY></HTML>");
}
}
JSPs vs ASPs
JSPs and Active Server Pages are similar technologies.
So what are
the differences? The biggest difference is
that JSPs are cross platform and are
portable across
web servers. Microsoft's ASPs are only supported in
Microsoft IIS or
Personal Web Server.
While Java Server Pages may utilize JavaBeans,
Enterprise
JavaBeans and custom tag libraries, ASP
may use Win32 COM components. JSPs can
use
Java and JavaScript while ASPs use VBScript and
JScript.
// JavaScript aka JScript
JSPs use JDBC to
access databases while ASPs use
ADO (or Active Data Objects). JSPs have
extensible
custom tag libraries while ASPs do not.
Servlets or Java Server Pages?
The Sun J2EE Blueprints strongly endorse the use of
JSP pages for
serving dynamic web content. They
relegate Servlets to roles that effectively
extend web
server extension technology. These roles may include
authentication
or validation. Aside from supporting the
use of JSPs as a rule for
providing dynamic content,
it is also recommended that they be used to replace
proprietary server-side technology like SSIs ( or Server
Side
Includes).
Dissenting View
To
temper this advise, I send you to
Servlet Guru, Jason
Hunter's site to see
the down side of using JSPs. You
have to keep in mind that Hunter
is zealously dedicated
to the use of Servlets. See 'The Problems With
JSPs',
at:
Jason Hunter's Criticism of Java Server
Pages
http://servlets.com/soapbox/problems-jsp.html
Java Server Pages
are Transformed into Servlets
While Java Server Pages provide a view or presentation-
centric means
of generating servlets ultimately, JSPs
execute
as servlets. When a JSP services a request, it
does so in it's translated
form, as a servlet.
It is not surprising then, that a discussion of JSP pages
still largely involves related Servlet technology.
JSP_Page .jsp --> on request is translated to a ---> Servlet
Components Parts of a Java Server Page
A Java Server Page is made up of a static
template
component usually written in HTML or XML. At any place
in the document JSP elements can be added which fall
into the four categories, directives, scriptlets, standard
and custom actions.
Parts
of a JSP Page
<HTML> <!-- Static Template Text ( HTML or XML ) -->
</HTML> . |
Directives provide instructions to the container application
in which
the JSP is being processed. Scriptlets allow Java
code to be evaluated
dynamically at runtime. The output of
the associated Java application is 'inlined' as part of the
HTML document.
JSPs are in
Part Written in XML
// JSP syntax is 'hybridized'
Standard
and custom actions in JSP pages are created
using XML syntax. Some of the 'vintage' Java Server Page
syntax, though used in the HTML, is not compatible with XML.
This is because some of
the JSP tags use characters that
are considered illegal in XML identifiers.
To accomodate
this, the JSP specification supplies a separate set of alternate
tags written
purely in XML to be used inside XML documents.
JSPs also use a set of elements referred to as 'standard actions',
which are also written in XML which serve in both HTML and XML
documents.
Brief
Description of Pertinent XML Points
We already reviewed XML, but supply the following example
just as a reminder.
Example of a Simple XML
Document
<?xml version="1.0" ?>
<Animals edition="third" >
<topic1> Fish </topic1>
<topic2> Birds </topics2>
<topic3> Mammals </topic3>
</Animals>
XML also allows different applications to define
namespaces to
prevent name clashes. A namespace
is created by assigning a url (uri) to a
prefix which is
then prefixed to elements belonging to that namespace.
Notice in the following example how a namespace is
defined to create a set of related elements.
Simple XML document with
Elements Namespace Qualified
//
Translation carried out by the JSP engine is instigated by a first
// request for the JSP page. The JSP 1.1 specification also
allows
// for JSP
page to be precompiled into class files to remove lag time
// at start-up.
The Translation Phase
We use the
'translation' term to describe translating
template source code into servlet source code. In this
process most of the static content will be enveloped in
out.println statements similar to the once
we we introduced
to in the servlet examples.
Example
out.println("<HTML>");
JSP expressions
that contain Java code that evaluates
directly to values that will be 'inlined' with the template
code ready to be evaluated by the
Java environment
when the code becomes an executing Java class object.
JSP directives
supply their instructions to the JSP engine
and will have their information exercised when appropriate.
For instance, the page directive that allows a Java package
to be imported will result in an
import statement being added
to the top of the servlet code that is being
created. Elements
that take the form <jsp:XXX
.../> such as standard actions will
be converted into method calls to JavaBean
components or
calls on other objects of the Java
Servlet API.
Translation Errors
The translation phase yields it's own sorts of
errors. For
instance an angle brace may have been inadvertantly left
out. This results in an
exception being thrown that is specific
to the translation phase, a ParseException is thrown. In this
case the servlet class,
source file will be empty or incomplete.
Once the JSP is translated into a Servlet, it
is compiled. If an
error occurs in the Java code during the
compilation
process,
a JasperException will be thrown. The Exception error message
will include
the JSP page servlet's name and the line at which
the error occurs.
Note that as with any other Java class, there
is still the potential
for Runtime Exceptions to be thrown that will only show up when
the page is invoked
to supply a response to a client request.
// ParseException
& JasperException,
// thrown at translation & compilation
respectively
JSP Servlet Instantiation
When a request is made and mapped to a JSP page
for a
response, a special helper servlet first checks
whether the servlet that is currently
associated with the
JSP page is older than the JSP page. If the page has
been
revised and so is newer than the servlet that is
currently associated with it, the
special helper servlet
translates the JSP into a new Servlet class and compiles
it.
// helper servlet keeps JSP up to date
If an instance of the JSP page servlet is not already
running, the
JSP container will load the JSP servlet
class, instantiate it, and intialize it by
calling it's jspInit( )
method. Then the container invokes the _jspService( )
method, passing
in a request and response object. If
the page instance needs to be removed,
the jspDestroy( )
method is called.
JSP Life Cycle Methods
Java Server Pages are extensions of the class HttpJspBase
which in
turn implements the Servlet interface. The JSP
implementation has many methods which
parallel those
of a regular servlet. For instance, the contents of the JSP
page is
rendered from inside the _jspService( ) method.
The _jspService( ) method cannot be
overridden, but the
developer can override the jspInit( ) and jspDestroy( )
methods within
their JSP pages.
Once loaded into the servlet container, the _jspService( )
method is
responsible for responding to client requests.
Once this class file is loaded within
the servlet container,
the _jspService( ) method is responsible for replying to a
client's
request. By default, the _jspService( ) method is
dispatched on a separate thread by the
servlet container
in order to process concurrent requests.
Table showing a JSP Life Cycle
Life Cycle Description | JSP Methods |
Init Event | jspInit( ) |
Service requests & responses | _jspService( ) |
Destroy Event | jspDestroy( ) |
JSP Access Models
The early JSP specifications advocated two
approaches, known as
Model 1 and Model 2
architectures, for applying JSP technology. The
approaches
differ in where they locate the bulk
processing of a request.
Model I Architecture
Following is a simple diagram of the approach
espoused by Model 1.
The browser exchanges
requests and responses with the JSP page which
in turn,
communicates with a JavaBean. The
JavaBeans interfaces the front end to 'Enterprise
Information Systems' (or EIS).
Diagram of Model I Architecture
Browser<->|JSP
<-> JavaBean |
|
servlet container |<->
EIS
// Enterprise Info System
Model II Architecture
Model I has problems when the JSP page becomes
complex, making it difficult for page
designers to work
with. A second
architecture, Model II more effectively
insulates the page designer from the complexities
of
Java. Model II implements the Model View
Controller
architecture as is shown in
the following diagram.
Diagram of Model II
Architecture
Browser
--request--> Controller Servlet
|
( instantiates bean)
|
v
Bean
Controller <--data access--> DataSource/EIS
|
v
Browser
<--response--- JSP
View
Variation of a Model II JSP Architecture
// different component accesses data source. Bean is more a 'result carrier' then a controller.
Browser --request--> Servlet/JSP
<-->
DataSource
|
v
Result Bean
|
v
Browser <--response--- JSP View
In Model II, processing is divided. Presentation components,
like
JSP pages generate HTML or XML responses that
determine the user interface which
will be rendered by the
browser. 'Front components', also known as
controllers',
just handle HTTP requests. In Model II they are also
responsible for
creating any beans or objects used by
the presentation components. The
Controller also decides
which presentation to forward to a request.
Model II keeps the processing logic out of the presentation
component. The presentation component simply retrieves
objects created by the
controller and extract from the objects
dynamic content, allowing for a clean
separation of
presentation from content. This model also supplies a
'single point of
entry' into the application making state,
security and presentation easier to
maintain.
2) Which of the following status code ranges used with the HTTP protocol
means everything is OK?
a) 200 +
b) 300 +
c) 400 +
d) 500
+
3) True or False?
In the HTTP servlet the doGet( ) and doPost( ) methods
are called by the service( ) method.
4) True or False? JSPs are restricted to adding Java Code to HTML
pages.
True \ False
5) True or False? JSPs are first compiled and then translated
into servlets.
True \ False
6) In both Model I and II JSP Architecture which of the following
serves as
the 'View'?
a) Browser
b) Servlet
c) Data Source
d)
JSP
7) True or False? Like JSPs Servlets need to be compiled in
advance
by the developer. True \ False
1 ) Either using Apache by itself as described above
or using Eclipse, create an HTML page with a form that
submits an argument to a Servlet.
Create a Servlet that does some processing to the
parameter. This might even be a Confirmation Page
which asks the user to confirm that the value is correct.
Have the Servlet create inline this page.
2) Create a HelloWorld Class in all three of the following
forms inside Eclipse. Screenshot the Output and include
the source code for each.
Notice the requirements of the assignment is quite minimal.
Please feel free to 'dice it up' in any areas where you have
more strength. ( HTML or Java).
Optional
While we would like to have the inline Servlet response
turned in as an excercise, you may wish to have a variation
where a servlet returns a JSP. This sort of thing is common
in the patterns we have discussed.
Following is a code snippet and the location from where
it was found.
Snippet to forward to a JSP
From a Servlet
String nextJSP = "/searchResults.jsp";
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher(nextJSP);
dispatcher.forward(request,response);
reference:
http://hermosaoceanviewproperty.com/blog/post/servlets/forwarding-from-servlet-jsp/
You may wish to use a simple JSP to do your confirmation.
We look at this sort of thing more next week however you
may wish to incorporate something like the following snippet
in your code to use a JSP