Why Build Web Pages Dynamically?
Java Servlet • The Web page is based on data submitted by the
user
– E.g., results page from search engines and order-
confirmation pages at on-line stores
• The Web page is derived from data that changes
frequently
– E.g., a weather report or news headlines page
• The Web page uses information from databases or
other server-side sources
– E.g., an e-commerce site could use a servlet to build a Web
page that lists the current price and availability of each
item that is for sale.
Server-Side Java Java Applet and Java Servlet
• Big applets require long download time
• Applets do not have access to all the
system resources
• Server-side Java solves problems that
applets face
– Code executed on the server side and only the
results sent to client
– Servlets can access legacy applications and
data sources
Java Applet and Java Servlet, contd. Advantages of Servlets
• Efficiency
– More efficient – uses lightweight java threads as
opposed to individual processes
• Persistency
– Servlets remain in memory
– Servlets can maintain state between requests
• Portability
– Since servlets are written in Java, they are platform
independent
• Robustness
– Error handling, Garbage collector to prevent problems
with memory leaks
– Large class library – network, file, database, distributed
object components, security, etc.
1
Advantages of Servlets Java Servlet Basics
• Extensibility
– Creating new subclasses that suite your needs • The Java Servlet is a server-side web component that
• Inheritance, polymorphism, etc. takes a HTTP request from a client, handles it, talks
• Security to a database, talks to a JavaBean component, and
– Security provided by the server as well as the Java Security responds with a HTTP response or dispatches the
Manager
request to other Servlets or JSP components.
– Eliminates problems associated with executing cgi scripts using
operating system “shells” • Servlets can dynamically produce text-based HTML
• Powerful markup contents and binary contents as well
– Servlets can directly talk to web server contents based on the client’s request.
– Facilitates database connection pooling, session tracking etc.
• Convenient
– Parsing and decoding HTML form data, reading and setting
HTTP headers, handling cookies, etc.
Java Servlet Basics Execution of Java Servlet
• A Servlet component can delegate the requests to its back- Web Web Request
Browser Server Servlet
end tier such as a database management system, RMI, EAI,
or other Enterprise Information System (EIS). Response
• A Servlet is deployed as a middle tier just like other web
components such as JSP components. • Applications of Java Servlets
• The Servlet components are building block components, – Building e-commerce store fronts
which always work together with other components such as • Servlet builds an online catalog based on the
JSP components, JavaBean components, Enterprise Java contents of a database
Bean (EJB) components, and web service components. • Customer places an order, which is processed by
• A Servlet component is also a distributed component, another servlet
which can provide services to remote clients and also – Servlets as wrappers for legacy systems
access remote resources. – Servlets interacting with EJB applications
Support Environments for Java Servlets Web Server Configuration
• A Java Servlet application is supported by its • An XML format file called server.xml is used to
Servlet container. control and configure the behavior and setting
• The Apache Tomcat web server is the official of the Tomcat web server.
reference implementation of Servlet • This file is located in the conf subdirectory of
containers, supporting Servlets and JSP. the Tomcat installation directory.
2
Web Server Configuration, contd. Java Servlet Alternatives
• 1. Reset the server port number where the • CGI – Common Gateway Interface
– New process for every cgi request
Servlet class or other web component will • Slow response time
listen for requests. • If cgi program terminates before responding to web server, the
browser just waits for a response until it times out
• 2. Turn on Servlet reloading so that you don’t • Proprietary APIs
need to reload the recompiled Servlet. – NSAPI – Netscape Server API
– ISAPI – IIS Server API
• Dynamic link libraries
• Server-Side JavaScript
– Embedding javascript into precompiled HTML pages – only
few servers support it
CGI and Java Servlets Technology Java Servlet Architecture
• Two packages make up the servlet architecture
– javax.servlet
• Contains generic interfaces and classes that are implemented
and extended by all servlets
– javax.servlet.http
• Contains classes that are extended when creating HTTP-
specific servlets
• The heart of servlet architecture is the interface
class javax.servlet.Servlet
• It provides the framework for all servlets
• Defines five basic methods – init, service, destroy,
getServletConfig and getServletInfo
Object model of Servlet Framework
<<Interface>>
javax.servlet.Servlet
<<Interface>>
javax.io.Serializable
<<Interface>>
javax.servlet.ServletConfig
GenericServlet & HttpServlet
init( ) getInitParameter( )
getServletConfig( ) getServletContext( )
service( )
getServletInfo( )
destroy( ) javax.servlet.GenericServlet
getInitParameterNames( )
getServletName( )
• HttpServlet class is extended from GenericServlet
init( )
getServletConfig( )
class
service( )
getServletInfo( )
destroy( )
• GenericServlet.service() method has been defined as
getInitParameter( )
getServletContext( )
an abstract method
getInitParameterNames( )
getServletName( )
log( )
• The two objects that the service() method receives
are ServletRequest and ServletResponse
javax.servlet.http.HttpServlet
doDelete( )
• ServletRequest Object
doGet( )
doOptions( ) – Holds information that is being sent to the servlet
doPost( )
doPut( )
doTrace( )
• ServletResponse Object
getLastModified( )
service( ) – Holds data that is being sent back to the client
Basic Servlet
3
GenericServlet & HttpServlet Life Cycle of a Servlet
• Applet life cycle methods: init( ), start( ), paint( ),
• Unlike the GenericServlet, when extending stop( ), and destroy( ) – appropriate methods
HttpServlet, don’t have to implement the service() called based on user action
method. It is already implemented for you • Similarly, servlets operate in the context of a
• When HttpServlet.service( ) is invoked, it calls doGet( request and response model managed by a
) or doPost( ), depending upon how data is sent from servlet engine
the client • The engine does the following
• HttpServletRequest and HttpServletResponse classes – Loads the servlet when it is first requested
are just extensions of ServletRequest and – Calls the servlet’s init( ) method
ServletResponse with HTTP-specific information – Handles any number of requests by calling the servlet’s
stored in them service( ) method
– When shutting down, calls each servlet’s destroy( )
method
The Lifecycle of a Servlet Life Cycle – init( ) method
• Request for a servlet received by the servlet engine
• Checks to see if the servlet is already loaded
• If not, uses a class loader to get the required servlet class
and instantiates it by calling the constructor method
• After the servlet is loaded, but before it services any
requests, the init ( ) method is called
• Inside init( ), the resources used by the servlet are
initialized. E.g: establishing database connection
• This method is called only once just before the servlet is
placed into service
• The init( ) method takes a ServletConfig object as a
parameter
• Most common way of doing this is to have it call the
super.init( ) passing it the ServletConfig object
Life Cycle – service( ) method
Life Cycle – destroy( ) method
• The service( ) method handles all requests sent by a client • This method signifies the end of a servlet’s life
• It cannot start servicing requests until the init( ) method has been • The resources allocated during init( ) are released
executed
• Only a single instance of the servlet is created and the servlet • Save persistent information that will be used the next
engine dispatches each request in a single thread time the servlet is loaded
• The service( ) method is used only when extending GenericServlet • The servlet engine unloads the servlet
class
• Calling destroy( ) yourself will not acutally unload the
• Since servlets are designed to operate in the HTTP environment, servlet. Only the servlet engine can do this
the HttpServlet class is extended
• The service(HttpServletRequest, HttpServletResponse) method
examines the request and calls the appropriate doGet() or doPost()
method.
• A typical Http servlet includes overrides to one or more of these
subsidiary methods rather than an override to service()
4
Processing of HTTP Requests and Processing of HTTP Requests and
Responses Responses, contd.
The prototypes of doGet() and doPost() • HttpServletRequest and HttpServletResponse
• void doGet( HttpServletRequest request, are the two interfaces that provide the Servlet
HttpServletResponse response) with full access to all information from the
throws ServletException, IOException; request and the response sent back to the
client.
• void doPost( HttpServletRequest request,
HttpServletResponse response ) • When the doGet() or doPost() is called, the
Servlet container passes in the
throws ServletException, IOException; HttpServletRequest and HttpServletResponse
objects.
Simple Servlet Template
Compiling and Invoking Servlets import java.io.*;
import javax.servlet.*;
• Set your CLASSPATH import javax.servlet.http.*;
– Servlet JAR file (e.g., install_dir\lib\common\servlet.jar). public class ServletTemplate extends HttpServlet {
– Top of your package hierarchy public void doGet(HttpServletRequest request,
HttpServletResponse response)
• Put your servlet classes in proper location throws ServletException, IOException {
– Locations vary from server to server. E.g., // Use "request" to read incoming HTTP headers
• tomcat_install_dir\webapps\examples\WEB-INF\classes // (e.g. cookies) and HTML form data (query data)
• jrun_install_dir\servers\default\default-app\WEB-INF\classes
// Use "response" to specify the HTTP response status
– Invoke your servlets // code and headers (e.g. the content type, cookies).
– http://host/servlet/ServletName
– Custom URL-to-servlet mapping (via web.xml) PrintWriter out = response.getWriter();
// Use "out" to send content to browser
}
}
A Simple Servlet That Generates Summary
import java.io.*;
Plain Text
• Servlets are efficient, portable, powerful, and
import javax.servlet.*;
import javax.servlet.http.*; widely accepted in industry
• Regardless of deployment server, run a free
public class HelloWorld extends HttpServlet { server on your desktop for development
public void doGet(HttpServletRequest request,
HttpServletResponse response) • Getting started:
throws ServletException, IOException { – Set your CLASSPATH
PrintWriter out = response.getWriter(); • Servlet JAR file
• Top of your package hierarchy
out.println("Hello World");
– Put class files in proper location
} • .../WEB-INF/classes
}
– Use proper URL, usually
http://host/servlet/ServletName
5
Summary (Continued)
• Main servlet code goes in doGet or doPost:
– The HttpServletRequest contains the incoming
information
– The HttpServletResponse lets you set outgoing
information
• Call setContentType to specify MIME type
• Call getWriter to obtain a Writer pointing to client
• One-time setup code goes in init
– Servlet gets initialized and loaded once
– Servlet gets invoked multiple times
– Initialization parameters set in web.xml