* The preview only display some random pages of manuals. You can download
full content via the form below.
Objectives • Understand the Servlet Architecture. • Compare Servlet & Other Similar technologies. • Understand the Servlet Life Cycle. • Handle Request & Response. • Generate Dynamic HTML. • Handle Sessions.
Evolution of Dynamic Content Tech.
• • • • • • •
Common Gateway Interface (CGI) ColdFusion (Allaire) Active Server Pages (ASP) Server-Side JavaScript (SSJS) Personal Home Page tools (PHP) Java Servlets JavaServer Pages
The CGI Life Cycle Main Process Request for CGI 1
Child Process for CGI 1
Request for CGI 2
Child Process for CGI 2
Request for CGI 3
Child Process for CGI 3
CGI-Based Web Server
Java Servlet A Java program that extends the functionality of a Web server, generating dynamic content and interacting with Web clients using a request response paradigm.
J2EE 1.2 Architecture
An extensible Web technology that uses template data, custom elements, scripting languages, and server-side Java objects to return dynamic content to a client. Typically the template data is HTML or XML elements. The client is often a Web browser.
Advantages of Servlets • Java™ objects which extend the functionality of a HTTP server(a big plus). • Dynamic customization of content • Platform and server independent • No CGI limitations • better performance • Easier to write than CGI code no need to parse headers and get info (all that is done by the HttpServlet class ) • No Networking restrictions (like applets) • Do not create a new process (or Servlet for every request) • Servlets can persist over time
Server Extensions Enhance or Change the base functionality of the server, allowing the server to handle tasks that were once relegated to external CGI programs.
The Power of Servlets • • • • • • •
Portability Power Efficiency and Endurance Safety Elegance Integration Extensibility and Flexibility
The Servlet Life Cycle • A web server communicates with a Servlet through a simple interface, javax.servlet.Servle t. This interface consists of three main methods: • init() • service() • destroy() and two ancillary methods: • getServletConfig() • getServletInfo()
Servlet Life Cycle (contd)
Request for Servlet1
Request for Servlet2
Main Process Thread JVM Servlet1 Thread Thread Servlet2
Request Servlet1 Servletforinitialized once; reused until destroyed and
garbage collected.
Java Servlet-based Web Server
Servlet Life Cycle (contd)
Life Cycle Of A Servlet (contd) • A servlet is constructed and initialized. It then services zero or more requests until the service that it extends shuts down • Initialized only once, stays resident in memory while servicing requests • Multiple threads of execute service(), one for each client connection • The servlet interface defines the life cycle methods : init() service() destroy()
init() Method • Called by server immediately after servlet is instantiated • Called only once • Servlet creates and initializes the resources needed for handling requests
• public void init(ServletConfig config) throws ServletException; ServletException - thrown when servlet cannot initialize necessary resources
service() Method • It is the heart of the servlet. • It handles all requests sent by a client. • Each request message from a client results in a single call to the servlet's service() method. • It reads the request and produces the response message • public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException;
destroy() Method • This signifies the end of a servlet’s life. • It’s also a good place to save any persistent information that will be used the next time the servlet is loaded. • It is called to allow the servlet to clean up any resources. • Public void destroy();
Servlet Life Cycle (contd) Servlet loaded on demand (first time user accesses the servlet). Once loaded the servlet is in memory init() Client requests arrive service() Unloaded on closing server; manual unloading
destroy() each client request creates a new thread with service
Servlet Interface
• Servlets Classes / Interfaces are available in packages (in java servlet development kit) – javax.servlet.http – javax.servlet
Servlet Interface (contd)
GenericServlet Class Server
request
GenericServlet subclass
service()
response
KEY :
implemented by subclass
A generic servlet handling a request
A Http Servlet Handling a Request HTTP request
HttpServlet subclass
Web Server
GET request response POST request response HEAD request response
doGet()
service()
doPost() doHead()
Implementation of doGet() doPost()… is to return an error to the calling client if servlet does these KEY : not override implemented by methods. subclass
Generic servlet vs httpservlet service
init Generic Servlet
doGet(...) doPost(...) doPut(…)
extends
destroy
doOptions(…)
HttpServlet
doDelete(…) doTrace(…)
What does the Server Receive server
Searching Found www.mcp.com for www.mcp.com
client GET /index.html HTTP/1.0
Server receives only one of the HTTP request methods (Get/Post)
http://www.mcp.com/index.html
Servlet programmers must provide implementations for these requests
Web server recieves GET /servlet/myHelloServlet HttpServlet subclass Check request type Web Server it is “GET” doGet() hence call doGet()
GET/servlet/ myHelloServlet HTTP/1.0
service()
doPost()
Web server uses logic: doHead() myHelloServlet is loaded. If not , then load the servlet. call service method (already implemented in HttpServlet) (it checks the request type and correspondingly calls the doGet() or doPost() method )
javax.servlet
java.io InputStream
ServletInputStream
OutputStream
Servlet ServletConfig
ServletOutputStream
ServletContext Serializable ServletRequest java.lang
ServletResponse Object
GenericServlet SingleThreadModel
Exception
KEY Class
ServletException
ABSTRACT CLASS
Interface
UnavailableException extends
implements
Servlet javax.servlet.*
GenericServlet
service(req, res)
ServletRequest
ABSTRACT CLASS
Serializable
ServletResponse
ServletInputStream
Class
ServletConfig
ServletOutputStream
Interface
implements
ServletContext / ServletConfig • ServletConfig – used to get initialization parameters • getServletContext() • String getInitParameter(String) • Enumeration getInitParameterNames() • ServletContext – useful for logging & finding out about the other servlets • Servlet getServlet(String) • Enumeration getServlets() • Enumeration getServletNames() • void log(String) • void log(Exception, String)
GenericServlet
javax.servlet.http.*
HTTPServlet
Class
Interface
ABSTRACT CLASS
Serializable
extends
implements
Servlet Architecture Servlet
Methods for managing a servlet and communicating with clients
HTTPServlet
Interface
class
extends
Encapsulates communication from client to server ServletRequest
GET request Servlet
response ServletResponse Encapsulates communication from server to client
package codecamp; A Simple Code Example import javax.servlet.*; import javax.servlet.http.*; import java.io.*; Public class ServletGet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("
First Servlet"); out.println("
Hello Code Camp! "); } }
Example Write the following html file: mydisplay.html
calling servlets
Click on the button “call servletGet” and note that the earlier servlet is called.
NOTE:User clicked on button, and the browser then Eg: mydisplay.html generated the GET method based on “action” settings.
Generating GET by clicking a button on browser server
Searching Found localhost for localhost
client GET /servlet/servletGet /mydisplay.html HTTP/1.0 HTTP/1.0
http://localhost…/…/mydisplay.html
call servletGet
Example Modify only the following line in html file: mydisplay.html