SlideShare a Scribd company logo
1 of 33
Download to read offline
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

Introduction to JSP
Introduction to JSPIntroduction to JSP
Introduction to JSP
Geethu Mohan
 
JAVA EE DEVELOPMENT (JSP and Servlets)
JAVA EE DEVELOPMENT (JSP and Servlets)JAVA EE DEVELOPMENT (JSP and Servlets)
JAVA EE DEVELOPMENT (JSP and Servlets)
Talha Ocakçı
 
Java EE 與 雲端運算的展望
Java EE 與 雲端運算的展望 Java EE 與 雲端運算的展望
Java EE 與 雲端運算的展望
javatwo2011
 

What's hot (20)

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

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

Java web programming
Java web programmingJava web programming
Java web programming
Ching Yi Chan
 
J2EE : Java servlet and its types, environment
J2EE : Java servlet and its types, environmentJ2EE : Java servlet and its types, environment
J2EE : Java servlet and its types, environment
joearunraja2
 

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

Servlets intro
Servlets introServlets intro
Servlets intro
 
Java web programming
Java web programmingJava web programming
Java web programming
 
Servlets
ServletsServlets
Servlets
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/Servlet
 
Servlet
Servlet Servlet
Servlet
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
 
Web Technologies -- Servlets 4 unit slides
Web Technologies -- Servlets   4 unit slidesWeb Technologies -- Servlets   4 unit slides
Web Technologies -- Servlets 4 unit slides
 
Http Server Programming in JAVA - Handling http requests and responses
Http Server Programming in JAVA - Handling http requests and responsesHttp Server Programming in JAVA - Handling http requests and responses
Http Server Programming in JAVA - Handling http requests and responses
 
servlets
servletsservlets
servlets
 
Basics Of Servlet
Basics Of ServletBasics Of Servlet
Basics Of Servlet
 
Java servlets
Java servletsJava servlets
Java servlets
 
J2EE : Java servlet and its types, environment
J2EE : Java servlet and its types, environmentJ2EE : Java servlet and its types, environment
J2EE : Java servlet and its types, environment
 
Servlet
ServletServlet
Servlet
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
 Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4... Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
 
Day7
Day7Day7
Day7
 
Knowledge Sharing : Java Servlet
Knowledge Sharing : Java ServletKnowledge Sharing : Java Servlet
Knowledge Sharing : Java Servlet
 
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B KuteJava Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
 
Bt0083 server side programing
Bt0083 server side programing Bt0083 server side programing
Bt0083 server side programing
 
Servlet ppt by vikas jagtap
Servlet ppt by vikas jagtapServlet ppt by vikas jagtap
Servlet ppt by vikas jagtap
 

More from IMC Institute

More from IMC Institute (20)

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

Recently uploaded

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 

Recently uploaded (20)

08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 

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