SlideShare une entreprise Scribd logo
1  sur  33
Télécharger pour lire hors ligne
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

Contenu connexe

Tendances

Lecture 3: Servlets - Session Management
Lecture 3:  Servlets - Session ManagementLecture 3:  Servlets - Session Management
Lecture 3: Servlets - Session ManagementFahad Golra
 
Lap trinh web [Slide jsp]
Lap trinh web [Slide jsp]Lap trinh web [Slide jsp]
Lap trinh web [Slide jsp]Tri Nguyen
 
Lecture 5 JSTL, custom tags, maven
Lecture 5   JSTL, custom tags, mavenLecture 5   JSTL, custom tags, maven
Lecture 5 JSTL, custom tags, mavenFahad Golra
 
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 ServicesArun Gupta
 
Introduction to JSP
Introduction to JSPIntroduction to JSP
Introduction to JSPGeethu Mohan
 
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 clientSebastiano Armeli
 
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 2014Jagadish Prasath
 
Java Server Faces (JSF) - Basics
Java Server Faces (JSF) - BasicsJava Server Faces (JSF) - Basics
Java Server Faces (JSF) - BasicsBG Java EE Course
 
Javatwo2012 java frameworkcomparison
Javatwo2012 java frameworkcomparisonJavatwo2012 java frameworkcomparison
Javatwo2012 java frameworkcomparisonJini Lee
 
Spring 4 final xtr_presentation
Spring 4 final xtr_presentationSpring 4 final xtr_presentation
Spring 4 final xtr_presentationsourabh aggarwal
 
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)Fahad Golra
 
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çı
 
Lecture 2: Servlets
Lecture 2:  ServletsLecture 2:  Servlets
Lecture 2: ServletsFahad Golra
 
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&6Lokesh Singrol
 
Java EE 與 雲端運算的展望
Java EE 與 雲端運算的展望 Java EE 與 雲端運算的展望
Java EE 與 雲端運算的展望 javatwo2011
 
Spring 4 advanced final_xtr_presentation
Spring 4 advanced final_xtr_presentationSpring 4 advanced final_xtr_presentation
Spring 4 advanced final_xtr_presentationsourabh aggarwal
 

Tendances (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
 

Similaire à Module 2: Learn Servlet Basics

Java web programming
Java web programmingJava web programming
Java web programmingChing Yi Chan
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/ServletSunil OS
 
Web Technologies -- Servlets 4 unit slides
Web Technologies -- Servlets   4 unit slidesWeb Technologies -- Servlets   4 unit slides
Web Technologies -- Servlets 4 unit slidesSasidhar Kothuru
 
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 responsesbharathiv53
 
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, environmentjoearunraja2
 
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...WebStackAcademy
 
Knowledge Sharing : Java Servlet
Knowledge Sharing : Java ServletKnowledge Sharing : Java Servlet
Knowledge Sharing : Java ServletFahmi Jafar
 
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 KuteTushar B Kute
 
Bt0083 server side programing
Bt0083 server side programing Bt0083 server side programing
Bt0083 server side programing Techglyphs
 
Servlet ppt by vikas jagtap
Servlet ppt by vikas jagtapServlet ppt by vikas jagtap
Servlet ppt by vikas jagtapVikas Jagtap
 

Similaire à Module 2: Learn Servlet Basics (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
 

Plus de IMC Institute

นิตยสาร Digital Trends ฉบับที่ 14
นิตยสาร Digital Trends ฉบับที่ 14นิตยสาร Digital Trends ฉบับที่ 14
นิตยสาร Digital Trends ฉบับที่ 14IMC Institute
 
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 2019IMC Institute
 
บทความ The evolution of AI
บทความ The evolution of AIบทความ The evolution of AI
บทความ The evolution of AIIMC Institute
 
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.12IMC Institute
 
เพราะเหตุใด Digitization ไม่ตอบโจทย์ Digital Transformation
เพราะเหตุใด Digitization ไม่ตอบโจทย์ Digital Transformationเพราะเหตุใด Digitization ไม่ตอบโจทย์ Digital Transformation
เพราะเหตุใด Digitization ไม่ตอบโจทย์ Digital TransformationIMC Institute
 
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 WorkIMC Institute
 
มูลค่าตลาดดิจิทัลไทย 3 อุตสาหกรรม
มูลค่าตลาดดิจิทัลไทย 3 อุตสาหกรรมมูลค่าตลาดดิจิทัลไทย 3 อุตสาหกรรม
มูลค่าตลาดดิจิทัลไทย 3 อุตสาหกรรมIMC Institute
 
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.11IMC Institute
 
แนวทางการทำ Digital transformation
แนวทางการทำ Digital transformationแนวทางการทำ Digital transformation
แนวทางการทำ Digital transformationIMC Institute
 
บทความ The New Silicon Valley
บทความ The New Silicon Valleyบทความ The New Silicon Valley
บทความ The New Silicon ValleyIMC Institute
 
นิตยสาร IT Trends ของ IMC Institute ฉบับที่ 10
นิตยสาร IT Trends ของ  IMC Institute  ฉบับที่ 10นิตยสาร IT Trends ของ  IMC Institute  ฉบับที่ 10
นิตยสาร IT Trends ของ IMC Institute ฉบับที่ 10IMC Institute
 
แนวทางการทำ Digital transformation
แนวทางการทำ Digital transformationแนวทางการทำ Digital transformation
แนวทางการทำ Digital transformationIMC Institute
 
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)IMC Institute
 
บทความ Robotics แนวโน้มใหม่สู่บริการเฉพาะทาง
บทความ Robotics แนวโน้มใหม่สู่บริการเฉพาะทาง บทความ Robotics แนวโน้มใหม่สู่บริการเฉพาะทาง
บทความ Robotics แนวโน้มใหม่สู่บริการเฉพาะทาง IMC Institute
 
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 IMC Institute
 
Thailand software & software market survey 2016
Thailand software & software market survey 2016Thailand software & software market survey 2016
Thailand software & software market survey 2016IMC Institute
 
Developing Business Blockchain Applications on Hyperledger
Developing Business  Blockchain Applications on Hyperledger Developing Business  Blockchain Applications on Hyperledger
Developing Business Blockchain Applications on Hyperledger IMC Institute
 
Digital transformation @thanachart.org
Digital transformation @thanachart.orgDigital transformation @thanachart.org
Digital transformation @thanachart.orgIMC Institute
 
บทความ Big Data จากบล็อก thanachart.org
บทความ Big Data จากบล็อก thanachart.orgบทความ Big Data จากบล็อก thanachart.org
บทความ Big Data จากบล็อก thanachart.orgIMC Institute
 
กลยุทธ์ 5 ด้านกับการทำ Digital Transformation
กลยุทธ์ 5 ด้านกับการทำ Digital Transformationกลยุทธ์ 5 ด้านกับการทำ Digital Transformation
กลยุทธ์ 5 ด้านกับการทำ Digital TransformationIMC Institute
 

Plus de 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
 

Dernier

Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 

Dernier (20)

Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 

Module 2: Learn Servlet Basics

  • 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