SlideShare a Scribd company logo
Module 2: Servlet Basics


 Thanisa Kruawaisayawan
  Thanachart Numnonda
  www.imcinstitute.com
Objectives
 What is Servlet?
 Request and Response Model
 Method GET and POST
 Servlet API Specifications
 The Servlet Life Cycle
 Examples of Servlet Programs



                                 2
What is a Servlet?

   Java™ objects which extend the functionality of a
    HTTP server
   Dynamic contents generation
   Better alternative to CGI
      Efficient
      Platform and server independent
      Session management
      Java-based


                                                        3
Servlet vs. CGI
Servlet                      CGI
 Requests are handled by     New process is created
  threads.                     for each request
 Only a single instance       (overhead & low
  will answer all requests     scalability)
  for the same servlet        No built-in support for
  concurrently (persistent     sessions
  data)


                                                         4
Servlet vs. CGI (cont.)
Request CGI1
                                   Child for CGI1

Request CGI2         CGI
                    Based          Child for CGI2
                   Webserver
Request CGI1
                                   Child for CGI1

Request Servlet1
                       Servlet Based Webserver

Request Servlet2                       Servlet1
                      JVM
Request Servlet1                       Servlet2


                                                    5
Single Instance of Servlet




                             6
Servlet Request and Response
           Model
                                   Servlet Container
                                              Request




   Browser
             HTTP       Request
                                          Servlet
                        Response


               Web                 Response
               Server

                                                        7
What does Servlet Do?
   Receives client request (mostly in the form of
    HTTP request)
   Extract some information from the request
   Do content generation or business logic process
    (possibly by accessing database, invoking EJBs,
    etc)
   Create and send response to client (mostly in the
    form of HTTP response) or forward the request to
    another servlet or JSP page
                                                        8
Requests and Responses

   What is a request?
      Informationthat is sent from client to a server
         Who made the request

         Which HTTP headers are sent

         What user-entered data is sent

   What is a response?
      Information   that is sent to client from a server
         Text(html, plain) or binary(image) data
         HTTP headers, cookies, etc
                                                            9
HTTP

   HTTP request contains
       Header
       Method
         Get: Input form data is passed as part of URL
         Post: Input form data is passed within message body

         Put

         Header

       request data
                                                                10
Request Methods
   getRemoteAddr()
      IP address of the client machine sending this request
   getRemotePort()
      Returns the port number used to sent this request
   getProtocol()
      Returns the protocol and version for the request as a string of the form
       <protocol>/<major version>.<minor version>
   getServerName()
      Name of the host server that received this request
   getServerPort()
      Returns the port number used to receive this request



                                                                                  11
HttpRequestInfo.java
public class HttpRequestInfo extends HttpServlet {{
 public class HttpRequestInfo extends HttpServlet
    ::
    protected void doGet(HttpServletRequest request,
     protected void doGet(HttpServletRequest request,
   HttpServletResponse response)throws ServletException, IOException {{
    HttpServletResponse response)throws ServletException, IOException
            response.setContentType("text/html");
             response.setContentType("text/html");
            PrintWriter out == response.getWriter();
             PrintWriter out    response.getWriter();

              out.println("ClientAddress: "" ++ request.getRemoteAddr() ++
               out.println("ClientAddress:       request.getRemoteAddr()
     "<BR>");
      "<BR>");
              out.println("ClientPort: "" ++ request.getRemotePort() ++ "<BR>");
               out.println("ClientPort:       request.getRemotePort()    "<BR>");
              out.println("Protocol: "" ++ request.getProtocol() ++ "<BR>");
               out.println("Protocol:       request.getProtocol()    "<BR>");
              out.println("ServerName: "" ++ request.getServerName() ++ "<BR>");
               out.println("ServerName:       request.getServerName()    "<BR>");
              out.println("ServerPort: "" ++ request.getServerPort() ++ "<BR>");
               out.println("ServerPort:       request.getServerPort()    "<BR>");

              out.close();
               out.close();
      }}
      ::
}}


                                                                                12
Reading Request Header
   General
     getHeader
     getHeaders
     getHeaderNames
   Specialized
     getCookies
     getAuthType  and getRemoteUser
     getContentLength
     getContentType
     getDateHeader
     getIntHeader
                                       13
Frequently Used Request Methods

   HttpServletRequest   methods
     getParameter()      returns value of named
      parameter
     getParameterValues() if more than one value
     getParameterNames() for names of parameters




                                                    14
Example: hello.html
<HTML>
  :
  <BODY>
     <form action="HelloNameServlet">
            Name: <input type="text" name="username" />
            <input type="submit" value="submit" />
     </form>
  </BODY>
</HTML>




                                                          15
HelloNameServlet.java


public class HelloNameServlet extends HttpServlet {{
 public class HelloNameServlet extends HttpServlet
     ::
     protected void doGet(HttpServletRequest request,
      protected void doGet(HttpServletRequest request,
               HttpServletResponse response)
                HttpServletResponse response)
                        throws ServletException, IOException {{
                         throws ServletException, IOException
          response.setContentType("text/html");
           response.setContentType("text/html");
          PrintWriter out == response.getWriter();
           PrintWriter out    response.getWriter();
          out.println("Hello "" ++ request.getParameter("username"));
           out.println("Hello       request.getParameter("username"));
          out.close();
           out.close();
     }}
     ::
}}




                                                                         16
Result




         17
HTTP GET and POST
   The most common client requests
       HTTP GET & HTTP POST
   GET requests:
     User entered information is appended to the URL in a query string
     Can only send limited amount of data
            .../chap2/HelloNameServlet?username=Thanisa
   POST requests:
     User entered information is sent as data (not appended to URL)
     Can send any amount of data



                                                                       18
TestServlet.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class TestServlet extends HttpServlet {
  public void doGet(HttpServletRequest request,
                     HttpServletResponse response)
               throws ServletException, IOException {

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        out.println("<h2>Get Method</h2>");
    }
}




                                                        19
Steps of Populating HTTP
                Response
   Fill Response headers
 Get an output stream object from the response
 Write body content to the output stream




                                                  20
Example: Simple Response
    Public class HelloServlet extends HttpServlet {
     public void doGet(HttpServletRequest request,
                         HttpServletResponse response)
                        throws ServletException, IOException {

        // Fill response headers
        response.setContentType("text/html");

        // Get an output stream object from the response
        PrintWriter out = response.getWriter();

        // Write body content to output stream
        out.println("<h2>Get Method</h2>");
    }
}




                                                             21
Servlet API Specifications
http://tomcat.apache.org/tomcat-7.0-doc/servletapi/index.html




                                                                22
Servlet Interfaces & Classes
                      Servlet



                 GenericServlet             HttpSession



                     HttpServlet


ServletRequest                  ServletResponse



HttpServletRequest              HttpServletResponse

                                                      23
CounterServlet.java


::
public class CounterServlet extends HttpServlet {{
 public class CounterServlet extends HttpServlet
    private int count;
     private int count;
          ::
    protected void doGet(HttpServletRequest request,
     protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {{
 HttpServletResponse response) throws ServletException, IOException
        response.setContentType("text/html");
         response.setContentType("text/html");
        PrintWriter out == response.getWriter();
         PrintWriter out    response.getWriter();
        count++;
         count++;
        out.println("Count == "" ++ count);
         out.println("Count          count);
        out.close();
         out.close();
    }}
          ::
}}




                                                                        24
Servlet Life-Cycle
                      Is Servlet Loaded?


           Http
         request
                                           Load          Invoke
                             No



           Http
         response            Yes
                                                          Run
                                                         Servlet
                                     Servlet Container

Client              Server
                                                                   25
Servlet Life Cycle Methods
                       service( )




    init( )                                 destroy( )
                        Ready
Init parameters




            doGet( )            doPost( )
                  Request parameters                     26
The Servlet Life Cycle
   init
     executed  once when the servlet is first loaded
     Not call for each request
     Perform any set-up in this method
              Setting up a database connection

   destroy
     calledwhen server delete servlet instance
     Not call after each request
     Perform any clean-up
              Closing a previously created database connection


                                                                  27
doGet() and doPost() Methods
             Server           HttpServlet subclass

                                                doGet( )
Request



                             Service( )



Response                                        doPost( )



           Key:       Implemented by subclass
                                                            28
Servlet Life Cycle Methods
   Invoked by container
     Container   controls life cycle of a servlet
   Defined in
     javax.servlet.GenericServlet   class or
         init()
         destroy()

         service() - this is an abstract method

     javax.servlet.http.HttpServlet class

         doGet(), doPost(), doXxx()
         service() - implementation
                                                     29
Implementation in method service()
protected void service(HttpServletRequest req, HttpServletResponse
   resp)
       throws ServletException, IOException {
       String method = req.getMethod();
    if (method.equals(METHOD_GET)) {
         ...
           doGet(req, resp);
         ...
       } else if (method.equals(METHOD_HEAD)) {
           ...
           doHead(req, resp); // will be forwarded to doGet(req,
   resp)
       } else if (method.equals(METHOD_POST)) {
           doPost(req, resp);
       } else if (method.equals(METHOD_PUT)) {
           doPut(req, resp);
       } else if (method.equals(METHOD_DELETE)) {
           doDelete(req, resp);
       } else if (method.equals(METHOD_OPTIONS)) {
           doOptions(req,resp);
       } else if (method.equals(METHOD_TRACE)) {
           doTrace(req,resp);
       } else {
         ...
       }                                                         30
     }
Username and Password Example




                                31
Acknowledgement
Some contents are borrowed from the
presentation slides of Sang Shin, Java™
Technology Evangelist, Sun Microsystems,
Inc.




                                           32
Thank you

   thananum@gmail.com
www.facebook.com/imcinstitute
   www.imcinstitute.com



                                33

More Related Content

PDF
Java Web Programming [5/9] : EL, JSTL and Custom Tags
PDF
Java Web Programming [8/9] : JSF and AJAX
PDF
Java Web Programming [3/9] : Servlet Advanced
PDF
Java Web Programming [6/9] : MVC
PDF
Java Web Programming [4/9] : JSP Basic
PDF
Java Web Programming [9/9] : Web Application Security
PPTX
Rest with Java EE 6 , Security , Backbone.js
PDF
Java Web Programming [7/9] : Struts2 Basics
Java Web Programming [5/9] : EL, JSTL and Custom Tags
Java Web Programming [8/9] : JSF and AJAX
Java Web Programming [3/9] : Servlet Advanced
Java Web Programming [6/9] : MVC
Java Web Programming [4/9] : JSP Basic
Java Web Programming [9/9] : Web Application Security
Rest with Java EE 6 , Security , Backbone.js
Java Web Programming [7/9] : Struts2 Basics

What's hot (20)

PDF
Lecture 3: Servlets - Session Management
PDF
Lap trinh web [Slide jsp]
PDF
J2EE jsp_01
PDF
ODP
RESTing with JAX-RS
PDF
Lecture 5 JSTL, custom tags, maven
PDF
JAX-RS 2.0: RESTful Web Services
PPTX
Introduction to JSP
KEY
MVC on the server and on the client
PDF
Java EE 7 in practise - OTN Hyderabad 2014
PPT
Java Server Faces (JSF) - Basics
PPTX
Javatwo2012 java frameworkcomparison
ODP
Spring 4 final xtr_presentation
PDF
Lecture 4: JavaServer Pages (JSP) & Expression Language (EL)
PDF
JAVA EE DEVELOPMENT (JSP and Servlets)
PPT
Data Access with JDBC
PDF
Lecture 2: Servlets
DOCX
TY.BSc.IT Java QB U5&6
PDF
Java EE 與 雲端運算的展望
ODP
Spring 4 advanced final_xtr_presentation
Lecture 3: Servlets - Session Management
Lap trinh web [Slide jsp]
J2EE jsp_01
RESTing with JAX-RS
Lecture 5 JSTL, custom tags, maven
JAX-RS 2.0: RESTful Web Services
Introduction to JSP
MVC on the server and on the client
Java EE 7 in practise - OTN Hyderabad 2014
Java Server Faces (JSF) - Basics
Javatwo2012 java frameworkcomparison
Spring 4 final xtr_presentation
Lecture 4: JavaServer Pages (JSP) & Expression Language (EL)
JAVA EE DEVELOPMENT (JSP and Servlets)
Data Access with JDBC
Lecture 2: Servlets
TY.BSc.IT Java QB U5&6
Java EE 與 雲端運算的展望
Spring 4 advanced final_xtr_presentation
Ad

Similar to Java Web Programming [2/9] : Servlet Basic (20)

PDF
Servlets intro
KEY
Java web programming
PPTX
SERVLETS (2).pptxintroduction to servlet with all servlets
PPTX
Servlets
PPT
Jsp/Servlet
DOCX
Servlet
PPT
Lecture 2
PPT
Web Technologies -- Servlets 4 unit slides
PPTX
Http Server Programming in JAVA - Handling http requests and responses
PDF
servlets
PPT
Basics Of Servlet
PPTX
Java servlets
PPTX
J2EE : Java servlet and its types, environment
PPT
Servlet
PPT
Java Servlets
PDF
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
PPTX
PPT
Knowledge Sharing : Java Servlet
PDF
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
PDF
Bt0083 server side programing
Servlets intro
Java web programming
SERVLETS (2).pptxintroduction to servlet with all servlets
Servlets
Jsp/Servlet
Servlet
Lecture 2
Web Technologies -- Servlets 4 unit slides
Http Server Programming in JAVA - Handling http requests and responses
servlets
Basics Of Servlet
Java servlets
J2EE : Java servlet and its types, environment
Servlet
Java Servlets
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
Knowledge Sharing : Java Servlet
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Bt0083 server side programing
Ad

More from IMC Institute (20)

PDF
นิตยสาร Digital Trends ฉบับที่ 14
PDF
Digital trends Vol 4 No. 13 Sep-Dec 2019
PDF
บทความ The evolution of AI
PDF
IT Trends eMagazine Vol 4. No.12
PDF
เพราะเหตุใด Digitization ไม่ตอบโจทย์ Digital Transformation
PDF
IT Trends 2019: Putting Digital Transformation to Work
PDF
มูลค่าตลาดดิจิทัลไทย 3 อุตสาหกรรม
PDF
IT Trends eMagazine Vol 4. No.11
PDF
แนวทางการทำ Digital transformation
PDF
บทความ The New Silicon Valley
PDF
นิตยสาร IT Trends ของ IMC Institute ฉบับที่ 10
PDF
แนวทางการทำ Digital transformation
PDF
The Power of Big Data for a new economy (Sample)
PDF
บทความ Robotics แนวโน้มใหม่สู่บริการเฉพาะทาง
PDF
IT Trends eMagazine Vol 3. No.9
PDF
Thailand software & software market survey 2016
PPTX
Developing Business Blockchain Applications on Hyperledger
PDF
Digital transformation @thanachart.org
PDF
บทความ Big Data จากบล็อก thanachart.org
PDF
กลยุทธ์ 5 ด้านกับการทำ Digital Transformation
นิตยสาร Digital Trends ฉบับที่ 14
Digital trends Vol 4 No. 13 Sep-Dec 2019
บทความ The evolution of AI
IT Trends eMagazine Vol 4. No.12
เพราะเหตุใด Digitization ไม่ตอบโจทย์ Digital Transformation
IT Trends 2019: Putting Digital Transformation to Work
มูลค่าตลาดดิจิทัลไทย 3 อุตสาหกรรม
IT Trends eMagazine Vol 4. No.11
แนวทางการทำ Digital transformation
บทความ The New Silicon Valley
นิตยสาร IT Trends ของ IMC Institute ฉบับที่ 10
แนวทางการทำ Digital transformation
The Power of Big Data for a new economy (Sample)
บทความ Robotics แนวโน้มใหม่สู่บริการเฉพาะทาง
IT Trends eMagazine Vol 3. No.9
Thailand software & software market survey 2016
Developing Business Blockchain Applications on Hyperledger
Digital transformation @thanachart.org
บทความ Big Data จากบล็อก thanachart.org
กลยุทธ์ 5 ด้านกับการทำ Digital Transformation

Recently uploaded (20)

PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPTX
Big Data Technologies - Introduction.pptx
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
cuic standard and advanced reporting.pdf
PDF
KodekX | Application Modernization Development
PPTX
Cloud computing and distributed systems.
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PPTX
A Presentation on Artificial Intelligence
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
The Rise and Fall of 3GPP – Time for a Sabbatical?
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
Per capita expenditure prediction using model stacking based on satellite ima...
Advanced methodologies resolving dimensionality complications for autism neur...
Big Data Technologies - Introduction.pptx
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Network Security Unit 5.pdf for BCA BBA.
Building Integrated photovoltaic BIPV_UPV.pdf
The AUB Centre for AI in Media Proposal.docx
Review of recent advances in non-invasive hemoglobin estimation
Mobile App Security Testing_ A Comprehensive Guide.pdf
CIFDAQ's Market Insight: SEC Turns Pro Crypto
cuic standard and advanced reporting.pdf
KodekX | Application Modernization Development
Cloud computing and distributed systems.
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
A Presentation on Artificial Intelligence

Java Web Programming [2/9] : Servlet Basic

  • 1. Module 2: Servlet Basics Thanisa Kruawaisayawan Thanachart Numnonda www.imcinstitute.com
  • 2. Objectives  What is Servlet?  Request and Response Model  Method GET and POST  Servlet API Specifications  The Servlet Life Cycle  Examples of Servlet Programs 2
  • 3. What is a Servlet?  Java™ objects which extend the functionality of a HTTP server  Dynamic contents generation  Better alternative to CGI  Efficient  Platform and server independent  Session management  Java-based 3
  • 4. Servlet vs. CGI Servlet CGI  Requests are handled by  New process is created threads. for each request  Only a single instance (overhead & low will answer all requests scalability) for the same servlet  No built-in support for concurrently (persistent sessions data) 4
  • 5. Servlet vs. CGI (cont.) Request CGI1 Child for CGI1 Request CGI2 CGI Based Child for CGI2 Webserver Request CGI1 Child for CGI1 Request Servlet1 Servlet Based Webserver Request Servlet2 Servlet1 JVM Request Servlet1 Servlet2 5
  • 6. Single Instance of Servlet 6
  • 7. Servlet Request and Response Model Servlet Container Request Browser HTTP Request Servlet Response Web Response Server 7
  • 8. What does Servlet Do?  Receives client request (mostly in the form of HTTP request)  Extract some information from the request  Do content generation or business logic process (possibly by accessing database, invoking EJBs, etc)  Create and send response to client (mostly in the form of HTTP response) or forward the request to another servlet or JSP page 8
  • 9. Requests and Responses  What is a request?  Informationthat is sent from client to a server  Who made the request  Which HTTP headers are sent  What user-entered data is sent  What is a response?  Information that is sent to client from a server  Text(html, plain) or binary(image) data  HTTP headers, cookies, etc 9
  • 10. HTTP  HTTP request contains  Header  Method  Get: Input form data is passed as part of URL  Post: Input form data is passed within message body  Put  Header  request data 10
  • 11. Request Methods  getRemoteAddr()  IP address of the client machine sending this request  getRemotePort()  Returns the port number used to sent this request  getProtocol()  Returns the protocol and version for the request as a string of the form <protocol>/<major version>.<minor version>  getServerName()  Name of the host server that received this request  getServerPort()  Returns the port number used to receive this request 11
  • 12. HttpRequestInfo.java public class HttpRequestInfo extends HttpServlet {{ public class HttpRequestInfo extends HttpServlet :: protected void doGet(HttpServletRequest request, protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {{ HttpServletResponse response)throws ServletException, IOException response.setContentType("text/html"); response.setContentType("text/html"); PrintWriter out == response.getWriter(); PrintWriter out response.getWriter(); out.println("ClientAddress: "" ++ request.getRemoteAddr() ++ out.println("ClientAddress: request.getRemoteAddr() "<BR>"); "<BR>"); out.println("ClientPort: "" ++ request.getRemotePort() ++ "<BR>"); out.println("ClientPort: request.getRemotePort() "<BR>"); out.println("Protocol: "" ++ request.getProtocol() ++ "<BR>"); out.println("Protocol: request.getProtocol() "<BR>"); out.println("ServerName: "" ++ request.getServerName() ++ "<BR>"); out.println("ServerName: request.getServerName() "<BR>"); out.println("ServerPort: "" ++ request.getServerPort() ++ "<BR>"); out.println("ServerPort: request.getServerPort() "<BR>"); out.close(); out.close(); }} :: }} 12
  • 13. Reading Request Header  General  getHeader  getHeaders  getHeaderNames  Specialized  getCookies  getAuthType and getRemoteUser  getContentLength  getContentType  getDateHeader  getIntHeader 13
  • 14. Frequently Used Request Methods  HttpServletRequest methods  getParameter() returns value of named parameter  getParameterValues() if more than one value  getParameterNames() for names of parameters 14
  • 15. Example: hello.html <HTML> : <BODY> <form action="HelloNameServlet"> Name: <input type="text" name="username" /> <input type="submit" value="submit" /> </form> </BODY> </HTML> 15
  • 16. HelloNameServlet.java public class HelloNameServlet extends HttpServlet {{ public class HelloNameServlet extends HttpServlet :: protected void doGet(HttpServletRequest request, protected void doGet(HttpServletRequest request, HttpServletResponse response) HttpServletResponse response) throws ServletException, IOException {{ throws ServletException, IOException response.setContentType("text/html"); response.setContentType("text/html"); PrintWriter out == response.getWriter(); PrintWriter out response.getWriter(); out.println("Hello "" ++ request.getParameter("username")); out.println("Hello request.getParameter("username")); out.close(); out.close(); }} :: }} 16
  • 17. Result 17
  • 18. HTTP GET and POST  The most common client requests  HTTP GET & HTTP POST  GET requests:  User entered information is appended to the URL in a query string  Can only send limited amount of data  .../chap2/HelloNameServlet?username=Thanisa  POST requests:  User entered information is sent as data (not appended to URL)  Can send any amount of data 18
  • 19. TestServlet.java import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class TestServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<h2>Get Method</h2>"); } } 19
  • 20. Steps of Populating HTTP Response  Fill Response headers  Get an output stream object from the response  Write body content to the output stream 20
  • 21. Example: Simple Response Public class HelloServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Fill response headers response.setContentType("text/html"); // Get an output stream object from the response PrintWriter out = response.getWriter(); // Write body content to output stream out.println("<h2>Get Method</h2>"); } } 21
  • 23. Servlet Interfaces & Classes Servlet GenericServlet HttpSession HttpServlet ServletRequest ServletResponse HttpServletRequest HttpServletResponse 23
  • 24. CounterServlet.java :: public class CounterServlet extends HttpServlet {{ public class CounterServlet extends HttpServlet private int count; private int count; :: protected void doGet(HttpServletRequest request, protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {{ HttpServletResponse response) throws ServletException, IOException response.setContentType("text/html"); response.setContentType("text/html"); PrintWriter out == response.getWriter(); PrintWriter out response.getWriter(); count++; count++; out.println("Count == "" ++ count); out.println("Count count); out.close(); out.close(); }} :: }} 24
  • 25. Servlet Life-Cycle Is Servlet Loaded? Http request Load Invoke No Http response Yes Run Servlet Servlet Container Client Server 25
  • 26. Servlet Life Cycle Methods service( ) init( ) destroy( ) Ready Init parameters doGet( ) doPost( ) Request parameters 26
  • 27. The Servlet Life Cycle  init  executed once when the servlet is first loaded  Not call for each request  Perform any set-up in this method  Setting up a database connection  destroy  calledwhen server delete servlet instance  Not call after each request  Perform any clean-up  Closing a previously created database connection 27
  • 28. doGet() and doPost() Methods Server HttpServlet subclass doGet( ) Request Service( ) Response doPost( ) Key: Implemented by subclass 28
  • 29. Servlet Life Cycle Methods  Invoked by container  Container controls life cycle of a servlet  Defined in  javax.servlet.GenericServlet class or  init()  destroy()  service() - this is an abstract method  javax.servlet.http.HttpServlet class  doGet(), doPost(), doXxx()  service() - implementation 29
  • 30. Implementation in method service() protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String method = req.getMethod(); if (method.equals(METHOD_GET)) { ... doGet(req, resp); ... } else if (method.equals(METHOD_HEAD)) { ... doHead(req, resp); // will be forwarded to doGet(req, resp) } else if (method.equals(METHOD_POST)) { doPost(req, resp); } else if (method.equals(METHOD_PUT)) { doPut(req, resp); } else if (method.equals(METHOD_DELETE)) { doDelete(req, resp); } else if (method.equals(METHOD_OPTIONS)) { doOptions(req,resp); } else if (method.equals(METHOD_TRACE)) { doTrace(req,resp); } else { ... } 30 }
  • 31. Username and Password Example 31
  • 32. Acknowledgement Some contents are borrowed from the presentation slides of Sang Shin, Java™ Technology Evangelist, Sun Microsystems, Inc. 32
  • 33. Thank you thananum@gmail.com www.facebook.com/imcinstitute www.imcinstitute.com 33