; Java Servlets Presentation
Learning Center
Plans & pricing Sign in
Sign Out
Your Federal Quarterly Tax Payments are due April 15th Get Help Now >>

Java Servlets Presentation


  • pg 1

• Understand the Servlet Architecture.
• Compare Servlet & Other Similar
• 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
         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,
  t. This interface
  consists of three
  main methods:
• init()
• service()
• destroy()
   and two ancillary
• getServletConfig()
• getServletInfo()
                Servlet Life Cycle (contd)

                                 Main Process
Request for Servlet1          Thread JVM
Request for Servlet2                  Thread

                                   Thread Servlet2

Servlet initialized once; reused until destroyed and
Request for Servlet1
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
• The servlet interface defines the life cycle methods :
 init()
 service()
 destroy()
                  init() Method

• Called by server immediately after servlet is
• Called only once
• Servlet creates and initializes the resources
  needed for handling requests

• public void init(ServletConfig config) throws

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,
               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
• Public void destroy();
         Servlet Life Cycle (contd)
            Servlet loaded on demand (first time
            user accesses the servlet). Once loaded the
            servlet is in memory
Client requests
                     Unloaded on closing server;
                     manual unloading
                         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        GenericServlet subclass



  KEY :                   implemented by subclass

          A generic servlet handling a request
      A Http Servlet Handling a Request

 HTTP request                 HttpServlet subclass
                 Web Server
  GET request                               doGet()
  POST request                               doPost()
    response                   service()
 HEAD request                               doHead()
Implementation of doGet() doPost()… is to
return an error to the calling client if
servlet does not override these methods.
        KEY :        implemented by subclass
      Generic servlet vs httpservlet

   init                                   service
                Generic Servlet


          doGet(...)                doOptions(…)

  doPost(...)                             doDelete(…)
                       HttpServlet          doTrace(…)
         What does the Server Receive
             Found www.mcp.com
             Searching for www.mcp.com

             GET /index.html HTTP/1.0
Server receives only one
of the HTTP request
methods (Get/Post)


         Servlet programmers must provide
         implementations for these requests
                Web server recieves
                GET /servlet/myHelloServlet
                                            HttpServlet subclass
                          Check request type
                   Web Server
                              it is “GET”
                           hence call doGet()    doGet()
                                       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 )
   java.io            javax.servlet                 Servlet
InputStream              ServletInputStream
OutputStream           ServletOutputStream
  Object                  GenericServlet

  Exception             ServletException      UnavailableException

KEY Class       ABSTRACT CLASS   Interface     extends    implements
   javax.servlet.*       GenericServlet            ServletConfig
                     service(req, res)

        ServletRequest                 ServletResponse

    ServletInputStream                    ServletOutputStream

Class   ABSTRACT CLASS     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             Serializable

javax.servlet.http.*     HTTPServlet

Class   ABSTRACT CLASS   Interface        extends     implements
      Servlet Architecture

                   Methods for
 Servlet       managing a servlet and
                communicating with


Interface      class      extends
       Encapsulates communication
         from client to server


GET request


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,
                     response) throws ServletException,
                             IOException {

            PrintWriter out = response.getWriter();
            out.println("<big>Hello Code Camp!
 Write the following html file: mydisplay.html
         <HTML> <HEAD>
         <TITLE> calling servlets </TITLE> </HEAD>
         <form method=get
         <input type=submit value="call servletGet">
         </BODY> </HTML>
 Click on the button “call servletGet” and note that the
 earlier servlet is called.

NOTE:User clicked on button, and the browser then
               Eg:method based on “action” settings.
generated the GET
         Generating GET by clicking a
         button on browser
             Found localhost
             Searching for localhost

               /servlet/servletGet HTTP/1.0
           GET /mydisplay.html HTTP/1.0


                          call servletGet
  Modify only the following line in html file:
         <form method=post
  Click on the button “call servletGet” and note what

NOTE:User clicked on button, and the browser then
generated the POST method based on “action” settings.

NOTE: the servlet servletGet did not contain a doPost
method and hence got the error. Rename doGet() to
doPost() and it would then work.
Transferring info from browser to Servlets
 • Generally in web pages, users fill up a form
   with fields.
 • Browser communicates with server (servlets)
   through GET and POST methods
 • GET requests :
 • – Getting information
 • – Appended to the URL in a query string ( limited
 • amount of data)
 • –
 • – Can be bookmarked and emailed
 • POST requests:
 • – Sending information
 • – Send any amount of data
 • – .../servlet/PlaceOrderProcess
 • – Can Not be bookmarked and emailed.
 • – Use POST for things like placing an order.
     Common Requests: GET and POST

• – Getting information
• – Appended to the URL in a query string ( limited
  amount of data)
• .../servlet/ViewCourse?name=servlets_codecamp
• – Can be bookmarked and emailed
• POST requests:
• Sending information
• – Send any amount of data
• – .../servlet/PlaceOrderProcess
• – Can Not be bookmarked and emailed.
• – Use POST for things like placing an order.

Write a html with three text fields for name, id and location,
with a submit button. Set the form method as „GET‟, and
action as „servlet/servletGetParam‟

        Eg: servlet_get_HTML.html
 Write a servlet with doGet() method. In the doGet() method
 read the parameters and then send it back to the browser for

          Eg: servletGetParam.java

Write a html with three text fields for name, id and location,
with a submit button. Set the form method as „POST‟, and
action as „servlet/servletGetParam‟

       Eg: servlet_post_HTML.html
Write a servlet with doPost() method. In the doPost() method
read the parameters and then send it back to the browser for

               Eg: servletPost.java
       Interface ServletRequest
– information about the client
   • name of the host and the IP address of client
   • parameters sent from the client browser
   • scheme used by the browser to communicate
     to servlet (eg. http; https; ftp;…..)
   • protocol used by client (eg. ftp)
   • access to the ServletInputStream (which
     allows servlet to read binary data from the
     client )
– information about server
   • name of the server
   • port used by the server

• Subclass ServletRequest to provide protocol specific

• Example: HTTPServletRequest (extends ServletRequest
  )supports methods to retrieve more protocol specific
  headers (getMethod() to identify the type of request)

class Name    ServletRequest
     public   String getContentType()
              ServletInputStream getInputStream()
   abstract   String getParameter(String)
   methods    Enumeration getParameterNames()
              String getProtocol()
              BufferedReader getReader()
              String getRemoteAddr()
              String getServerName()
              int getServerPort()
              String getScheme()
              String getRealPath()
              String getCharacterEncoding()
              Object getAttribute()
           interface HTTPServlet
• Information from client
    additional path info (sent along with request)
      • eg /servlet/myservlet/dict/defn.txt
      • “/dict/defn.txt” is the additional info to the servlet
      • within your servlet use getPathInfo() (null if no such
        data is available)
    what was requested (file/ servlet/)
    HTTP headers sent by the client
      • Connection, User-Agent, host, Accept, Accept-
        language, Accept-Charset
                 HTTP Headers

• General : Information not related to Client, Server or
  HTTP protocol.
• Request : Preferred Document formats and server
• Response : Information about the server.
• Entity : Information on the data that is being sent
  between the client and server.

Class Name    HTTPServletRequest extends ServletRequest
              Enumeration getHeaderNames()
   abstract   long getDateHeader(String)
   methods    String getPathInfo()
              String getQueryString()
              String getRemoteUser()
              String getAuthType()
              Cookie[ ] getCookies()
              String getRequestURI()
              String getServletPath()
              String getSession()
              boolean isRequestedSessionIdFromCookie()
              boolean isRequestedSessionIdFromUrl()

Write a servlet that implements the doGet() method. Capture the
information encapsulated in the request object (in ServletRequest
and HTTPServletRequest), and send this info back to the client.

               Eg: helloservletGet.java
         ServletResponse Interface

• Allows the servlet to reply to the client
• Allows the servlet to set the content length and MIME
• Provides a handle to ServletOutputStream (or Writer)
  to send data to the client
• Subclass HTTPServletResponse supports methods to
  set more protocol specific headers

Class Name ServletResponse

    public void setContentLength(int)
  abstract void setContentType(String);
           ServletOutputStream getOutputStream()
           PrintWriter getWriter()
           String getCharacterEncoding(String)
Class Name    HTTPServletResponse
              void addCookie(http.Cookie)
   abstract   boolean containsHeader(String);
   methods    String encodeURL(String)
              String encodeRedirectURL(String)
              String encodeUri(String)
              String encodeRedirectUri(String)
              void setHeader(String,String)
              void setIntHeader(String,int)
              void setDateHeader(String,long)
              void setStatus(int,String)
              void sendError(int,String)
              void sendRedirect(String)
                      Redirecting …

• Redirection can be set using the following methods in the
  HttpServletResponse class
   – setStatus(status code)
      • status codes available in the HttpServletResponse class as
        static variables
   – setHeader(“Location”, “ give new site location here”)
      • the new location must be an absolute url path
   – setHeader(“Refresh”, “3”) will tell the browser for 3 seconds
     before refreshing the page
   – setHeader(“Refresh”, “3; URL=…..”) will tell the browser for 3
     seconds before going to the new location specified in the
             Generating HTML

• Hardcoded in the program (servletGet.java)
• Using an HTML generator (require additional
  software; html generation classes)
• Using an HTML generator creatively

        Eg : ServletGet.java
           Redirecting a Request

• Servlet can use status codes and headers to inform a
  client to use another URL. It is useful when
    document (html file) has moved.
    load balancing is required. (one machine can
      distribute the load to many machines)
          Abstract class HTTPServlet
class Name HTTPServlet extends GenericServlets implements
           void doGet(HttpServletRequest, HttpServletResponse)
  methods long getLastModified(HttpServletRequest);
         void doPost(HttpServletRequest, HttpServletResponse)
         void method supports HttpServletResponse)
The service doPut(HttpServletRequest, HTTP 1.0
         void doDelete(HttpServletRequest, HttpServletResponse)
           This method dispatches each request
protocol.void doOptions(HttpServletRequest, HttpServletResponse)
to the method designed to handle it.
         void doTrace(HttpServletRequest, HttpServletResponse)
         void service(HttpServletRequest, HttpServletResponse)
         public void service(ServletRequest, ServletResponse)

 All methods throws ServletException and IOException
             Overriding Methods

• Servlet writer who wants to handle the GET and the
  HEAD (HTTP protocol) must override the doGet()
  method in the servlet.
• Similarly override
   – doPost() method to handle POST request
   – doPut() method to handle PUT requests
   – doDelete() method to handle DELETE requests

• Servlets are fundamentally multithreaded, hence can
  run multiple service() methods.
• Therefore the code for service method must be thread
• If you do not want a multithreaded server then one
  must implement the SingleThreadedModel interface.

Write a counter servlet that counts the number of clients

                       Eg: MyCounterServ.java

Modify the above servlet so that if many users are accessing
the variable count, it should be synchronized.

                     Eg: MyCounterServSyn.java

Write a servlet that informs the client that the site has moved,
and allow let the browser go to the new url automatically after
9 seconds.

            Eg: RelocateServlet.java
              Request Dispatcher

• The basic use of a RequestDispatcher:
One can effectively use the RequestDispatcher to call a JSP
  from a servlet or a servlet from another servlet.
RequestDispatcher rd =


rd.include(request, response);
         Sending Multimedia Content

• To send an image that is available with the server to the
    open a stream to the client browser
    open the local image file
    read block of bytes/ or byte by byte of image
    send information to server by writing to the stream

 Write a serlvet that sends an image to the browser.
 Image file must be on the server system.

                  Eg: servletImage.java
Problem: If we write 2 images to the
application, it will read only the first one.
Hence, one can send only one image at a

Write a serlvet that sends 2 <img src=“……”> tags to the
client. The client would load one image after another and
display both of them.

         Eg: servletImageHTML.java
Solution: the data to be sent<img src=“…”>, and the
Note: All send the html tag is stored in a
byteArrayOutputStream and sent all the information
browser will open connection and get at once. This is
buffering but could slow down when images can be
from server. This way any number oflot of information is
being sent
passed. to the client.
             User Authentication

• Specify in the resource list
   • servlet resource/ and what type of authentication
   • once set, then the browser gives a dialog box and
     then sends the name and password to the servlet

           Eg: secureServlet.java
               Session Tracking

• Mechanism to maintain a state about a series of
  requests from the same user (request originating from
  same browser)
• Sessions are shared across servlets
• HttpSession Object
    Can Store (name, value) Pairs.
    Persistence and disk swapping through Object
    Works across protocols (HTTP/HTTPS).
    Session validity, Creation time etc.
          Session Tracking (contd)

procedures in session tracking
• get a HttpSession object for a user
    HttpSession ss = new HttpSession(true)
   true means that if it a new session create a new
   session object, otherwise get session id.
• store/get data from the HttpSession object
    void ss.putValue(String name, Object val)
    Object ss.getValue(String name)
    void ss.removeValue(String name)
• Invalidate the session
    ss.invalidate();
          Count Example using Session

Write a servlet that uses session api to track the number of
times a user has visited the site.

            Eg: SessionDemo.java
        Ways of Session-Tracking

• Hidden Form Fields
• Persistent Cookies
• Servlet API
              Security Issues

• The Servlet Sandbox
• Access Control Lists (ACLs)
                Servlet Sandbox

• It is an area where Servlets are given restricted
  authority on the server.
• They may not have access to the file system or
  network, or they may have been granted a more
  trusted status.
• It is up to the web server administrator to decide
  which servlets are granted this status.
              Access Control Lists

• An ACL is a list of users who are allowed to perform a
  specific function in the server.
  The list specifies:
 What kind of access is allowed
 What object the access applies to
 Which users are granted access
           Servlet Environment

• Inter-Servlet Communication
   How to call a method of another Servlet
        Servlet Environment (contd)

• Communication with Active Server Resources
    How to call another Servlet (or any other kind of
     active resource) to process a request
• Accessing Passive Server Resources
    How to access a resource in the server's document
• Accessing Servlet Resources
    How to access resources which belong to a Servlet
• Sharing Data Between Servlets
    How to share data between Servlets
Invoking a Servlet From an Applet

           HTTP Request thru DataOutput created by
           URLCorrection object

Formatted results thru DataInputStream object
created by URLConnection object
                                                SQL Query
                           ResultSet Object
                Exercise (contd..)

• 20. Due to the implementation of the application on the
  AWT framework it is required to install the JRE software
  & the required application components on each machine
  which needs to communicate with the application. A better
  alternative would be to implement the same in a http based
  server architecture,(repeat exercises 1 to 5 here)[20]

To top