You are on page 1of 52

Java Servlets:

A QuickStart for CS Educators

Dawn Wilkins and Kathy Gates


The University of Mississippi
Workshop Description
 This workshop is designed to give CS educators,
who have a working knowledge of Java, a good
introduction to Java servlets. The servlet
architecture and life cycle will be explained, and
examples will be provided to demonstrate the use
of the Java Servlet API. Advanced features
including accessing databases through a servlet
and session tracking will be covered. Setting up
Java servlet development environment for students
will also be addressed.
Contents
 Background  Servlet Basics: A
 Java Servlet Basics Closer Look
 A Comparison of Servlets  Servlets & JDBC
& CGI  Session Tracking
 The Servlet Architecture  Java Server Pages
 A Few Example Servlets  Practical Applications
 IDE’s & Server Options  Resources
Software Demonstration Setup

 Windows NT
 Internet Explorer
 Borland Jbuilder
 Apache with Tomcat
 Mysql Database
– www.mysql.com
 PHP &
phpMyAdmin
A Historical Perspective
 First efforts at
dynamic Web content
– Common Gateway
Interface (CGI)
– Fast CGI
 Proprietary Solutions
– Microsoft’s Active
Server Pages
– Netscape’s Javascript
CGI: What is it?
Common Gateway  A standard interface
Interface (CGI) between a Web server
programs can be and an application.
written in many  One of the first
languages, including practical ways for
Java. Perl is the most generating dynamic
common language for content.
CGI's, due to its
 Runs as a separate
advanced text
process from the Web
processing capabilities.
server.
Interaction with CGIs

(From Developing Java Servlets: The


Authoritative Solution by James Goodwill, p. 8)
An Example CGI Program
 Hello World
– See demonstration.
Common Gateway Interface
 Advantages  Disadvantages
– Easy to get started – New process is started
– Simple programming for each CGI call
interface – Separate process
– Popular scripting means limited
languages such as Perl interaction with Web
offer powerful way to server and possible
quickly develop new loss of communication
applications – May hit operating
– Widely used system limits on
number of processes
Java Servlet Basics
 First there was the  So, what is a servlet?
applet -- high hopes, – Java embedded in a Web server
to extend the Web server's
but probably did not capabilities.
reach expected – Whereas applets run in the Web
potential. browser, servlets run in the Web
server.
– Slow to load
 Terms to Note:
– Not operable on all – Container vs. Engine
browsers – Filtering vs. Chaining
– Security issues – Contexts vs. Zones
Interaction with Servlets

(From Developing Java Servlets: The


Authoritative Solution by James Goodwill, p. 6)
Advantages of Servlets
 Efficient  Adds Persistence to a
– Servlets are loaded Stateless Web
once instead of each – The servlet's thread
time they are executed. doesn't have to
– The servlet is first terminate once it sends
loaded via the init() back a response.
method and can  Platform Independent
perform potentially
– Servlets port easily to
costly start-up
other systems with
functions once.
JVM.
More Advantages

 Built-in Support for  Function as Direct


Many Server Features Extensions of the Web
– The developer can be Server
free of certain server – Supports interaction
details. with the server itself
 Extensible  Gaining Wide-Spread
– Object-oriented Acceptance
approach facilitates
new development.
Disadvantages of Servlets
 Servlets can be more complicated to set up.
 Servlets must be recompiled whenever a
change is made.
 On their own, servlets do not provide a way to
embed code into HTML documents such as
with ColdFusion or PHP; however, this is
addressed with JSP.
Guidelines for Choosing
When  Nature of the Application
– What is the hardware/software
should platform?
you use – How long-term is it?
Servlets – How much development time is
available?
instead of – Who will maintain the application?
CGI? – What other information systems
does it interface with?
– How many hits do you anticipate?
A Review of HTTP
 Simple & Stateless
Hypertext  The client makes a request and
Transfer the Web server responds.
Protocol  The client request includes:
(HTTP) – an HTTP command or “method”
that tells what action to perform
– a URL
– the version of the HTTP protocol
it is using.
HTTP Responses
 The server processes the request For example,
and sends back a response. 200 means
successful.
 The first line of the response The server
specifies: also sends
the client info
– the version of the HTTP protocol the telling what
server is using, kind of
software it is
– a status code, and running and
– a description of the status code. the content of
the response.
HTTP Methods

The two most  GET is generally used by


a client to request a
popular resource from the server.
HTTP
methods are  POST is normally used to
GET & POST. pass user input to the
server.
The GenericServlet Request

(From Developing Java Servlets: The Authoritative


Solution by James Goodwill, p. 13)
Generic Servlet API Methods
 The interface  * service()
javax.servlet.Servlet – Receives two objects:
provides the framework ServletRequest and
ServletResponse
for all servlets through
five methods.  getServletInfo()
– Provides the servlet user with
information about the servlet
itself.
 * init()
– Servlet is constructed and  * destroy()
initialized. – Signifies the end of the
servlet’s life.
 getServletConfig()
– Returns startup configuration
and initialization parameters. * Life cycle methods
Servlet Requests & Responses
The service()  ServletRequest allows access
method accepts two to names of parameters
parameters: passed by the client, the
protocol, etc.
ServletRequest
 ServletResponse allows the
ServletResponse.
servlet to set the content
length & MIME type of the
reply and provides a means
by which the servlet can send
the reply data.
Generic vs. HTTP Servlets
 The HttpServlet Class  HttpServlets override
is extended from doGet() to handle GET
GenericServlet. requests and doPost()
 Generic servlets to handle POST
should override the requests.
service() method;  Other HttpServlet
however, service() is methods are also
already implemented available.
in HttpServlet.
The HttpServlet Request

(From Developing Java Servlets: The Authoritative


Solution by James Goodwill, p. 14)
An Example Servlet
 Hello World
– See demonstration.
Skeleton Servlet
public class skeletonServlet extends HttpServlet

{
// declaration of instance variables

public void init (ServletConfig config)


throws ServletException
{
super.init (config);
// initialize resources here
}
Skeleton Servlet, part 2

public void doGet (HttpServletRequest request,


HttpServletResponse response)
throws IOException, ServletException
{ ... }

public void doPost (HttpServletRequest request,


HttpServletResponse response)
{…}
Skeleton Servlet, part 3
public String getServletInfo ()
{
return “The purpose of this servlet is …”
}

public void destroy () {


{
// free resources here
}

} // skeletonServlet
Servlets & HTML
 Creating HTML Documents
– setContentType()
– getWriter()
 Retrieving Form Data
– getParameterNames()
– getParameter()
– getParameterValues()
 Invoking the Servlet
More Servlet Examples
 Vacation Example
– See demonstration.
 Quiz #1
– See demonstration.
Java IDE’s & Servlets
 IDE
– Integrated Development
Environment
 Examples
– Borland Jbuilder
– IBM Visualage
 Servlet Aids
– Automatic Code
Generation
– Test Environment
Servlet-Enabled Web Servers

 Apache with
Tomcat
 iPlanet
 IBM Websphere
 Other

See http://java.sun.com/products/servlet/industry.html
for a more comprehensive list.
The Servlet Specification
Created from  Newest servlet specification includes:
a Sun- – Concept of a Web Application (Servlets,
sponsored JSP, HTML, Classes, other resources) with
open process conventions for the directory structure
to develop – Web Application Archive (WAR) files
and revise – Filtering
 Allows on-the-fly transformations of HTTP
JavaTM content (request or response); for example,
technology to transform XML content
specifications – Other

http://java.sun.com/aboutJava/communityprocess/first/jsr053/index.html
Servlet Basics: A Closer Look
 The ServletRequest  The ServletResponse
Interface Interface
– Defines an object used – Defines an object for
to encapsulate sending MIME data
information about the back to the client from
client’s request. the servlet’s service()
– Includes information method.
about parameter
name/value pairs.
HttpServletRequest Interface
 A Few Methods
– getPathInfo()
– getAuthType()
– getPathTranslated()
– getCookies()
– getQueryString()
– getDateHeader() – getRemoteUser()
– getHeader() – getRequestedSessionId()
– getHeaderNames() – getRequestedURI()
– getIntHeader() – getServletPath()
– getMethod() – getSession()
HttpServletResponse Interface
 Static Final Variables  A Few Methods
– For example, SC_OK – addCookie()
represents a status code – encodeURL()
of 200, and – sendError()
SC_NOT_FOUND
represents a status code – sendRedirect()
of 404. – setDateHeader()
– setHeader()
– setStatus()
Servlet Tips
 Place costly functions in init().
 Let doGet() call doPost() or vice versa:
public void doPost(HttpServletRequest
req, HttpServletResponse res) throws
ServletException, IOException {
doGet(req, res);
}
 Be careful with multiple threads;
SingleThreadModel may be necessary.
JDBC
 Java Database Connectivity
 Relational Databases
 SQL Refresher
– CREATE
– INSERT
– UPDATE
– DELETE
– SELECT
JDBC Features
 A Java API for:  Easy Object to
– Opening a connection Relational Mapping
to a database  Database
– Executing a SQL Independence
statement
 Distributed
– Processing the results
Computing
– Closing the connection
to the database
Basic JDBC Methods
 Establishing a connection with getConnection()
 Creating SQL Statements
– CreateStatement()
 executeQuery()
 executeUpdate()

 execute()

 Getting the results with ResultSet


 SQLExceptions
A Simple Servlet with JDBC
 HowFar
– See demonstration.
Session Tracking

 HTTP is stateless, so no inherent way to


determine that a series of requests all come
from the same client.

 Think about a shopping cart application


example.
Possible Solutions
 Traditional CGI Techniques
– User-authorization
– Hidden form fields
– URL rewriting
– Persistent cookies

 Servlet API Built-in Support


Session-tracking API support
 Uses persistent cookies where possible and
reverts to URL rewriting when cookies do not
work.

 Each user is associated with a


javax.servlet.http.HttpSession object.
Information about the user can be stored in the
session object, e.g. shopping cart contents or
database connection.
Session Tracking Example
 Quiz #2
– See demonstration.
Java Server Pages
 Supports embedded  Steps of a JSP Request
scripting and tags. – Client requests a JSP page.
These co-exist with – The JSP engine compiles
HTML. the JSP into a servlet.
 Provide a means for – The generated servlet is
separating content and compiled and loaded.
presentation. – The compiled services the
 Reuse and code sharing request and sends a
are enhanced when JSP response back to the client.
is used with JavaBeans.
from Pure JSP by Goodwill
JSP Directives
 Page  Scriptlets
– A global definition that is sent – Used to embed small code
to the JSP engine blocks.
Ex: <%@ page errorPage=“/error.jsp” %> <% scriptlet %>

 Include  Comments
– Allows the substitution of text – Two forms:
or code <!-- comments …-->
Ex: <%@ include file=“copyright.html” %> <%-- comments … --%>

 Declarations  Expressions
– Contains Java variables and – Scriptlet fragments whose
methods called from an results can be converted to
expression block. String objects.
Syntax: <%! Declaration(s) %> <%= expression %>
HowFar as a JSP file
 HowFar.jsp
– See demonstration.
JSP and JavaBeans
 Supports the creation of  Tags
dynamic content – jsp:useBean
 JavaBeans  Declares the JavaBean
object that you want to
– Reusable software
use within the JSP
components that can be
manipulated visually in a – jsp:getProperty
builder tool  Inserts the String type
of the object into the
– Minimum Requirements:
output stream
 Supports JDK 1.1 and later
Serialization Model – jsp:setProperty
 Uses Get/Set accessors to  Sets properties of the
expose its properties Bean
HowFar2 as a JSP file with a JavaBean

 HowFar2.jsp
– See demonstration.
Practical Applications
 Useful for serving as  University of
the “glue” to connect Mississippi IT
heterogeneous Applications
information systems – E-forms
 Requires data from
that require a web Cold Fusion/SQL
interface. Server and SAP via
Java Connector
 XML makes this – Web-to-SAP
scenario even more  Business Connector
attractive.  Java Connector
Servlet Resources
 See accompanying handouts.
For More Information

Dawn Wilkins Kathy Gates


Department of Computer Office of Information
Science Technology
University of Mississippi University of Mississippi
(662) 915-7309 (662) 915-7206
dwilkins@cs.olemiss.edu kfg@olemiss.edu

You might also like