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

What's hot (20)

PDF
Lecture 3: Servlets - Session Management
Fahad Golra
 
PDF
Lap trinh web [Slide jsp]
Tri Nguyen
 
PDF
J2EE jsp_01
Biswabrata Banerjee
 
PDF
RESTEasy
Massimiliano Dessì
 
ODP
RESTing with JAX-RS
Ezewuzie Emmanuel Okafor
 
PDF
Lecture 5 JSTL, custom tags, maven
Fahad Golra
 
PDF
JAX-RS 2.0: RESTful Web Services
Arun Gupta
 
PPTX
Introduction to JSP
Geethu Mohan
 
KEY
MVC on the server and on the client
Sebastiano Armeli
 
PDF
Java EE 7 in practise - OTN Hyderabad 2014
Jagadish Prasath
 
PPT
Java Server Faces (JSF) - Basics
BG Java EE Course
 
PPTX
Javatwo2012 java frameworkcomparison
Jini Lee
 
ODP
Spring 4 final xtr_presentation
sourabh aggarwal
 
PDF
Lecture 4: JavaServer Pages (JSP) & Expression Language (EL)
Fahad Golra
 
PDF
JAVA EE DEVELOPMENT (JSP and Servlets)
Talha Ocakçı
 
PPT
Data Access with JDBC
BG Java EE Course
 
PDF
Lecture 2: Servlets
Fahad Golra
 
DOCX
TY.BSc.IT Java QB U5&6
Lokesh Singrol
 
PDF
Java EE 與 雲端運算的展望
javatwo2011
 
ODP
Spring 4 advanced final_xtr_presentation
sourabh aggarwal
 
Lecture 3: Servlets - Session Management
Fahad Golra
 
Lap trinh web [Slide jsp]
Tri Nguyen
 
J2EE jsp_01
Biswabrata Banerjee
 
RESTing with JAX-RS
Ezewuzie Emmanuel Okafor
 
Lecture 5 JSTL, custom tags, maven
Fahad Golra
 
JAX-RS 2.0: RESTful Web Services
Arun Gupta
 
Introduction to JSP
Geethu Mohan
 
MVC on the server and on the client
Sebastiano Armeli
 
Java EE 7 in practise - OTN Hyderabad 2014
Jagadish Prasath
 
Java Server Faces (JSF) - Basics
BG Java EE Course
 
Javatwo2012 java frameworkcomparison
Jini Lee
 
Spring 4 final xtr_presentation
sourabh aggarwal
 
Lecture 4: JavaServer Pages (JSP) & Expression Language (EL)
Fahad Golra
 
JAVA EE DEVELOPMENT (JSP and Servlets)
Talha Ocakçı
 
Data Access with JDBC
BG Java EE Course
 
Lecture 2: Servlets
Fahad Golra
 
TY.BSc.IT Java QB U5&6
Lokesh Singrol
 
Java EE 與 雲端運算的展望
javatwo2011
 
Spring 4 advanced final_xtr_presentation
sourabh aggarwal
 

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

PDF
Servlets intro
vantinhkhuc
 
PPTX
Servlets
Geethu Mohan
 
ODP
Servlets
ramesh kumar
 
PPT
Servlets
Manav Prasad
 
PPTX
Servletarchitecture,lifecycle,get,post
vamsitricks
 
PPTX
Servletarchitecture,lifecycle,get,post
vamsi krishna
 
PPTX
SERVIET
sathish sak
 
PPTX
Servletarchitecture,lifecycle,get,post
vamsitricks
 
PPT
Servlet123jkhuiyhkjkljioyudfrtsdrestfhgb
shubhangimalas1
 
PPT
Servlet.ppt
MouDhara1
 
PPT
Servlet.ppt
kstalin2
 
PPT
Servlet1.ppt
KhushalChoudhary14
 
PPT
Servlet (1) also contains code to create it.ppt
juhishrivastava25
 
KEY
Java web programming
Ching Yi Chan
 
PPTX
Servlets-UNIT3and introduction to servlet
RadhikaP41
 
PPT
Servlet
Rajesh Roky
 
PPTX
Servlets
ZainabNoorGul
 
PPTX
SCWCD : The servlet model CHAP : 2
Ben Abdallah Helmi
 
PDF
HTTP, JSP, and AJAX.pdf
Arumugam90
 
Servlets intro
vantinhkhuc
 
Servlets
Geethu Mohan
 
Servlets
ramesh kumar
 
Servlets
Manav Prasad
 
Servletarchitecture,lifecycle,get,post
vamsitricks
 
Servletarchitecture,lifecycle,get,post
vamsi krishna
 
SERVIET
sathish sak
 
Servletarchitecture,lifecycle,get,post
vamsitricks
 
Servlet123jkhuiyhkjkljioyudfrtsdrestfhgb
shubhangimalas1
 
Servlet.ppt
MouDhara1
 
Servlet.ppt
kstalin2
 
Servlet1.ppt
KhushalChoudhary14
 
Servlet (1) also contains code to create it.ppt
juhishrivastava25
 
Java web programming
Ching Yi Chan
 
Servlets-UNIT3and introduction to servlet
RadhikaP41
 
Servlet
Rajesh Roky
 
Servlets
ZainabNoorGul
 
SCWCD : The servlet model CHAP : 2
Ben Abdallah Helmi
 
HTTP, JSP, and AJAX.pdf
Arumugam90
 
Ad

More from IMC Institute (20)

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

Recently uploaded (20)

PPTX
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PDF
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PDF
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
PDF
From Code to Challenge: Crafting Skill-Based Games That Engage and Reward
aiyshauae
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PPTX
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
PDF
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
PDF
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PDF
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
PDF
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
PDF
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
PDF
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
PDF
Python basic programing language for automation
DanialHabibi2
 
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
From Code to Challenge: Crafting Skill-Based Games That Engage and Reward
aiyshauae
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
Python basic programing language for automation
DanialHabibi2
 

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 [email protected] www.facebook.com/imcinstitute www.imcinstitute.com 33