SlideShare a Scribd company logo
1 of 36
Download to read offline
01KPSBF
    Progettazione di applicazioni web


         Servlets in the J2EE platform

         Fulvio Corno
         Dipartimento di Automatica e Informatica
         Politecnico di Torino




PAW - HTTP Servlets                                 1
The J2EE Presentation tier
       Servlets
          Java  classes that handle requests by producing
            responses (e.g., HTTP requests and responses)
       JavaServer Pages (JSP)
          HTML-like pages with some dynamic content.
          Translated into servlets automatically
       JSP Standard Tag Library (JSTL)
          Set
             of standard components for JSP
          Used inside JSP pages.




                                                             2



PAW - HTTP Servlets                                              2
Organization of the platform
                            Your           Your application
                          web pages

                        JSTL

                      JavaServer Pages (JSP)

                        Java Servlet API


                         Java language


PAW - HTTP Servlets                                           3
A closer look at a servles
       A Java class that extends HttpServlet
       Compiled and placed in the appropriate directory
       When a request for a servlet arrives, the servlet
        container (a JVM):
          checks     if an instance of that servlet exists
          if not, it creates/loads an instance
          calls the servlet’s service() method (which in turn may
           call doGet()/doPost()/doXXX())




                                                                     5



PAW - HTTP Servlets                                                      4
Servlet life cycle
                         Java Servlet-based Web Server

                                 Main Process
        Request for
                                 Thread
                                          JVM
         Servlet 1
                                                Servlet1
                                                 Servlet1

        Request for              Thread
         Servlet 2
                                 Thread         Servlet2
                                                 Servlet2
        Request for
         Servlet 1




PAW - HTTP Servlets                                         5
SERVLET BASICS
       Java servlets are the first standard extension to Java,
        including two packages:
               javax.servlet
               javax.servlet.http



    http://java.sun.com/products/servlet/2.2/javadoc/




PAW - HTTP Servlets                                               6
SERVLET PACKAGE FRAMEWORK

                                          JAVAX

                                          Servlet

                                  GenericServlet

                                     HttpServlet

       Form           Admin      Cgi                 Error     File     ImageMap
      Servlet         Servlet   Servlet             Servlet   Servlet     Servlet




PAW - HTTP Servlets                                                                 7
SERVLET INTERFACE
    Servlet interface
    {

        void init(ServletConfig sc) throws ServletException;

        void service(ServletRequest req, ServletResponse res);
                     throws ServletException, IOException;

        void destroy();

    }




PAW - HTTP Servlets                                              8
Structure of a servlet
       A servlet does not have a main() method.
       Certain methods of a servlet are invoked by the server
        in the process of handling requests.
       Each time the server dispatches a request to a servlet,
        it invokes the servlet's service() method.




PAW - HTTP Servlets                                               9
Request / response
       The service() method accepts two parameters:
         a  request object: tells the servlet about the request
          a response object: the response object is used to return
           a response

    Check:
    http://java.sun.com/products/servlet/2.2/javadoc/




PAW - HTTP Servlets                                                   10
HttpServlet class
       Servlet is a simple Java class which must implement
        javax.servlet.Servlet interface.
       GenericServlet class provides a default
        implementation of this interface so that we don't have
        to implement every method of it.
       HttpServlet class extends GenericServlet to provide
        an HTTP protocol specific implementation of Servlet
        interface.




PAW - HTTP Servlets                                              11
AN HTTP SERVLET HANDLING GET AND
    POST REQUEST

                      Server            HttpServlet subclass
    Get request

    response                                            doGet( ))
                                                        doGet(

    Post request                          service( ))
                                          service(

    response                                            doPost( ))
                                                        doPost(




       Any subclass overrides the doGet()/doPost method(s),
       not the service() method
                                                                     13



PAW - HTTP Servlets                                                       12
SERVLET LIFE CYCLE

                      Java Servlet-based Web Server

                                   Main Process
        Request for                         JVM          Init()
         Servlet 1                 Thread
                       service()              Servlet1
                                              Servlet1
        Request for                Thread
         Servlet 2
                                   Thread     Servlet2
        Request for                           Servlet2
         Servlet 1
                                                         14



PAW - HTTP Servlets                                               13
HttpServlet methods (1/2)
       init()
          Called     only once during the initialization of the Servlet.
       destroy()
          Called  only once when Servlet instance is about to be
            destroyed.
       service()
          Do     not override this method!!.
       doGet(), doPost(), doPut(), doDelete(), doOptions(),
        doTrace()
          These  methods are called according to the type of
            HTTP request received. Override them to generate your
            own response.
       log()
          Writes     messages to the Servlet's log files.
PAW - HTTP Servlets                                                         14
HttpServlet methods (2/2)
       getLastModified()
          Override  this method to return your Servlet's last
            modified date.
       getServletInfo()
          Override this method to provide a String of general info
            about your Servlet such author, version, copyright etc.
       getServletName()
          Override     this method to return name of the Servlet.
       getInitParameter(), getInitParameterNames()
          Return     value(s) of initialization parameter(s)
       getServletConfig()
          Returns     a reference to ServletConfig object.
       getServletContext()
          Returns     reference to ServletContext object.
PAW - HTTP Servlets                                                   15
Do not override...
       service()
       getServletConfig()
       getServletContext()

    The three methods which stated above should not be
    overridden as their default implementation is more than
    enough to suffice.




PAW - HTTP Servlets                                           16
A “HELLO WORLD” SERVLET

       public class HelloServlet extends HttpServlet {

       public void doGet(HttpServletRequest request,
                   HttpServletResponse response)
           throws ServletException, IOException {

           response.setContentType("text/html");
           PrintWriter out = response.getWriter();
           out.println("CIAO MONDO!");

       }

       }


                                                         18



PAW - HTTP Servlets                                           17
A “HELLO WORLD” HTML SERVLET
  protected void doGet(HttpServletRequest request, HttpServletResponse
  response) throws ServletException, IOException {
  response.setContentType("text/html");
  PrintWriter out=response.getWriter();
  String docType="<!DOCTYPE HTML PUBLIC "-//W3C/ /DTD HTML 4.0 "+
    "Transitional //IT" > n";
  out.println(docType);
  out.println(
  "<HTML>n" +
  "<HEAD><TITLE> CIAO MONDO HTML </TITLE><HEAD> n" +
  "<BODY>n" +
  "<H1> CIAO MONDO </H1> n" +
  "</BODY>" +
  "</HTML>");
  }

                                                                         19



PAW - HTTP Servlets                                                           18
Servlet input processing
       protected void doGet(
          HttpServletRequest request,
          HttpServletResponse response
          ) throws ServletException, IOException


       A servlet may access the HTTP request information
        trough the request object

       See: http://java.sun.com/javaee/5/docs/api/
          HttpServletRequest
          ServletRequest




PAW - HTTP Servlets                                         19
Request parameters
       String getParameter(String name)
          Returns     the value of a request parameter as a String, or
            null if the parameter does not exist.
       Map getParameterMap()
          Returns     a java.util.Map of the parameters of this
            request.
       Enumeration getParameterNames()
          Returns an Enumeration of String objects containing the
            names of the parameters contained in this request.
       String[] getParameterValues(String name)
          Returns   an array of String objects containing all of the
            values the given request parameter has, or null if the
            parameter does not exist.

PAW - HTTP Servlets                                                       20
HTTP headers information (1/2)
       String getHeader(String name)
          Returns    the value of the specified request header as a
            String.
       Int getIntHeader(String name)
          Returns    the value of the specified request header as an
            int.
       Enumeration getHeaderNames()
          Returns  an enumeration of all the header names this
            request contains.
       Enumeration getHeaders(String name)
          Returns all the values of the specified request header as
            an Enumeration of String objects.


PAW - HTTP Servlets                                                     21
HTTP headers information (2/2)
       long getDateHeader(String name)
          Returns   the value of the specified request header as a
            long value that represents a Date object.
       String getMethod()
          Returns  the name of the HTTP method with which this
            request was made, for example, GET, POST, or PUT.
       String getQueryString()
          Returns  the query string that is contained in the request
            URL after the path.
       String getRemoteUser()
          Returns  the login of the user making this request, if the
            user has been authenticated, or null if the user has not
            been authenticated.

PAW - HTTP Servlets                                                     22
HTTP session handling
       Cookie[] getCookies()
          Returns   an array containing all of the Cookie objects the
            client sent with this request.
       String getRequestedSessionId()
          Returns    the session ID specified by the client.
       HttpSession getSession()
          Returns   the current session associated with this
            request, or if the request does not have a session,
            creates one.
       boolean isRequestedSessionIdValid()
          Checks     whether the requested session ID is still valid.



PAW - HTTP Servlets                                                      23
Other interesting information
       String getRemoteAddr()
          Returns    the Internet Protocol (IP) address of the client
            or last proxy that sent the request.
       String getRemoteHost()
          Returns  the fully qualified name of the client or the last
            proxy that sent the request.
       int getRemotePort()
          Returns    the Internet Protocol (IP) source port of the
            client or last proxy that sent the request.
       String getServerName()
          Returns  the host name of the server to which the
            request was sent.
       int getServerPort()
          Returns    the port number to which the request was sent.
PAW - HTTP Servlets                                                      24
HttpSession class (1/3)
       getAttribute(), getAttributeNames(), setAttribute(),
        removeAttribute()
          These   methods are used to set, get and remove objects
            from a user session.
       getId()
          Every   session created by the server has a unique 'id'
            associated with it in order to identify this session from
            other sessions. This method returns the 'id' of this
            session.
       getCreationTime()
          Simple   returns a long value indicating the date and time
            this session was created, meaning there by that you get
            the time this user first accessed your site.

PAW - HTTP Servlets                                                     25
HttpSession class (2/3)
       getLastAccessedTime()
          Returns a long value indicating the last time user
            accessed any resource on this server.
       getMaxInactiveInterval(), setMaxInactiveInterval()
          Return and set the maximum inactive interval in
            seconds for this session respectively. Every session has
            a maximum inactive interval during which if user doesn't
            make request to the server, the session is invalidated.
       isNew()
          Returns     a boolean value indicating if the session is new.
            Either it is the first page of the site user has hit so his
            session is new and has just been created or that user is
            not accepting cookies required for managing sessions
            so this value will then always return true.
PAW - HTTP Servlets                                                        26
HttpSession class (3/3)
        invalidate()
          Simply   invalidates a session. You can use this method
            on a 'logout' page allowing user to end his session. If
            after invalidation of his session user accesses some
            resource on the site then a new session will be created
            for it.




PAW - HTTP Servlets                                                   27
ServletConfig class
       ServletConfig object is used to pass information to the
        Servlet during its initialization
          Inistialization   information is stored in web.xml
       Servlet can obtain information regarding initialization
        parameters and their values
       using different methods of ServletConfig class.




PAW - HTTP Servlets                                               28
ServletConfig methods
     getInitParameter(String paramName)
       Returns  value of the given parameter. If value of
        parameter could not be found in web.xml file then a null
        value is returned.
     getInitParameterNames()
       Returns    an Enumeration object containing all the names
        of initialization parameters provided for this Servlet.
     getServletContext()
       Returns  reference to the ServletContext object for this
        Servlet. It is similar to getServletContext() method
        provided by HttpServlet class.
     getServletName()
       Returns         name of the Servlet as provided in the web.xml
           file or if none is provided then returns complete class
PAW - HTTP Servlets to the Servlet.
           path                                                          29
A “hello world” servlet with init


public void init(ServletConfig config) throws ServletException {
      super.init(config);
      String sRipetizioni =
             config.getInitParameter("ripetizioni");
      Ripetizioni = Integer.parseInt(sRipetizioni);
}




                                                              31



PAW - HTTP Servlets                                                30
How To... JSP vs Servlet
       Useful JSP constructs
          <%@page    pageEncoding=”text/html” %>
          <jsp:forward page=”a.jsp” %>
          <jsp:useBean … scope=”request” />
          <jsp:useBean … scope=”session” />
       How to translate them into Servlet instructions?




PAW - HTTP Servlets                                        31
HOW TO... output HTML
       response.setContentType("text/html");
       PrintWriter out = response.getWriter();
       out.print("<html><head>...");




PAW - HTTP Servlets                               32
HOW TO... forward to another page
       request.getRequestDispatcher(url).forward(request,
        response);

       Step-by-step:
          //request is HttpServletRequest object
          RequestDispatcher rd;
          rd = request.getRequestDispatcher("pathToServlet");
          rd.forward(request, response);




PAW - HTTP Servlets                                              33
HOW TO... define and use a request Bean
       Create a new bean with request scope
          UserDataBean  userData = new UserDataBean() ;
          request.setAttribute("userData", userData);
       Retrieve a bean from the request scope
          UserDataBean  userData =
            ((UserDataBean)request.getAttribute("userData"));




PAW - HTTP Servlets                                             34
HOW TO... define and use a session Bean
       Linking to the current session
          HttpSession   session = request.getSession(true);
       Creating a new bean with session scope
          CounterBean    counter;
            if(session.isNew()) {
              counter = new CounterBean();
              session.setAttribute("counter", counter);
            }
       Retrieving an existing bean with session scope
          Counter  =
            ((CounterBean)session.getAttribute("counter"));



PAW - HTTP Servlets                                            35
For more info...
       http://www.unix.org.ua/orelly/java-
        ent/servlet/ch01_01.htm
       http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/se
        rvlet/




PAW - HTTP Servlets                                              36

More Related Content

What's hot (20)

Javax.servlet,http packages
Javax.servlet,http packagesJavax.servlet,http packages
Javax.servlet,http packages
 
Servlets
ServletsServlets
Servlets
 
Java Servlet
Java Servlet Java Servlet
Java Servlet
 
Servlet and JSP
Servlet and JSPServlet and JSP
Servlet and JSP
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technology
 
1 java servlets and jsp
1   java servlets and jsp1   java servlets and jsp
1 java servlets and jsp
 
Java servlet technology
Java servlet technologyJava servlet technology
Java servlet technology
 
Weblogic
WeblogicWeblogic
Weblogic
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Java EE 01-Servlets and Containers
Java EE 01-Servlets and ContainersJava EE 01-Servlets and Containers
Java EE 01-Servlets and Containers
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Java Servlets & JSP
Java Servlets & JSPJava Servlets & JSP
Java Servlets & JSP
 
Servlets
ServletsServlets
Servlets
 
An Introduction To Java Web Technology
An Introduction To Java Web TechnologyAn Introduction To Java Web Technology
An Introduction To Java Web Technology
 
Wt unit 3 server side technology
Wt unit 3 server side technologyWt unit 3 server side technology
Wt unit 3 server side technology
 
Web Tech Java Servlet Update1
Web Tech   Java Servlet Update1Web Tech   Java Servlet Update1
Web Tech Java Servlet Update1
 
Servlet 01
Servlet 01Servlet 01
Servlet 01
 
Jsp servlets
Jsp servletsJsp servlets
Jsp servlets
 
Servlets
ServletsServlets
Servlets
 

Similar to Introduction to Servlets

Similar to Introduction to Servlets (20)

Servlet
Servlet Servlet
Servlet
 
Java servlets
Java servletsJava servlets
Java servlets
 
WEB TECHNOLOGIES Servlet
WEB TECHNOLOGIES ServletWEB TECHNOLOGIES Servlet
WEB TECHNOLOGIES Servlet
 
Servlets
ServletsServlets
Servlets
 
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
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servlet
 
Wt unit 3
Wt unit 3 Wt unit 3
Wt unit 3
 
Java Servlet
Java ServletJava Servlet
Java Servlet
 
Chap4 4 1
Chap4 4 1Chap4 4 1
Chap4 4 1
 
gayathri.pptx
gayathri.pptxgayathri.pptx
gayathri.pptx
 
Lecture5
Lecture5Lecture5
Lecture5
 
Wt unit 3 server side technology
Wt unit 3 server side technologyWt unit 3 server side technology
Wt unit 3 server side technology
 
JAVA Servlets
JAVA ServletsJAVA Servlets
JAVA Servlets
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jsp
 
Servlets & jsp Overview
Servlets & jsp OverviewServlets & jsp Overview
Servlets & jsp Overview
 
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
 
S E R V L E T S
S E R V L E T SS E R V L E T S
S E R V L E T S
 
SERVER SIDE PROGRAMMING
SERVER SIDE PROGRAMMINGSERVER SIDE PROGRAMMING
SERVER SIDE PROGRAMMING
 
Servlet in java , java servlet , servlet servlet and CGI, API
Servlet in java , java servlet , servlet servlet and CGI, APIServlet in java , java servlet , servlet servlet and CGI, API
Servlet in java , java servlet , servlet servlet and CGI, API
 
J servlets
J servletsJ servlets
J servlets
 

Recently uploaded

Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxmarlenawright1
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxPooja Bhuva
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxPooja Bhuva
 
Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxUmeshTimilsina1
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - Englishneillewis46
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the ClassroomPooky Knightsmith
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxDr. Sarita Anand
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 

Recently uploaded (20)

Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 

Introduction to Servlets

  • 1. 01KPSBF Progettazione di applicazioni web Servlets in the J2EE platform Fulvio Corno Dipartimento di Automatica e Informatica Politecnico di Torino PAW - HTTP Servlets 1
  • 2. The J2EE Presentation tier  Servlets  Java classes that handle requests by producing responses (e.g., HTTP requests and responses)  JavaServer Pages (JSP)  HTML-like pages with some dynamic content.  Translated into servlets automatically  JSP Standard Tag Library (JSTL)  Set of standard components for JSP  Used inside JSP pages. 2 PAW - HTTP Servlets 2
  • 3. Organization of the platform Your Your application web pages JSTL JavaServer Pages (JSP) Java Servlet API Java language PAW - HTTP Servlets 3
  • 4. A closer look at a servles  A Java class that extends HttpServlet  Compiled and placed in the appropriate directory  When a request for a servlet arrives, the servlet container (a JVM):  checks if an instance of that servlet exists  if not, it creates/loads an instance  calls the servlet’s service() method (which in turn may call doGet()/doPost()/doXXX()) 5 PAW - HTTP Servlets 4
  • 5. Servlet life cycle Java Servlet-based Web Server Main Process Request for Thread JVM Servlet 1 Servlet1 Servlet1 Request for Thread Servlet 2 Thread Servlet2 Servlet2 Request for Servlet 1 PAW - HTTP Servlets 5
  • 6. SERVLET BASICS  Java servlets are the first standard extension to Java, including two packages:  javax.servlet  javax.servlet.http http://java.sun.com/products/servlet/2.2/javadoc/ PAW - HTTP Servlets 6
  • 7. SERVLET PACKAGE FRAMEWORK JAVAX Servlet GenericServlet HttpServlet Form Admin Cgi Error File ImageMap Servlet Servlet Servlet Servlet Servlet Servlet PAW - HTTP Servlets 7
  • 8. SERVLET INTERFACE Servlet interface { void init(ServletConfig sc) throws ServletException; void service(ServletRequest req, ServletResponse res); throws ServletException, IOException; void destroy(); } PAW - HTTP Servlets 8
  • 9. Structure of a servlet  A servlet does not have a main() method.  Certain methods of a servlet are invoked by the server in the process of handling requests.  Each time the server dispatches a request to a servlet, it invokes the servlet's service() method. PAW - HTTP Servlets 9
  • 10. Request / response  The service() method accepts two parameters: a request object: tells the servlet about the request  a response object: the response object is used to return a response Check: http://java.sun.com/products/servlet/2.2/javadoc/ PAW - HTTP Servlets 10
  • 11. HttpServlet class  Servlet is a simple Java class which must implement javax.servlet.Servlet interface.  GenericServlet class provides a default implementation of this interface so that we don't have to implement every method of it.  HttpServlet class extends GenericServlet to provide an HTTP protocol specific implementation of Servlet interface. PAW - HTTP Servlets 11
  • 12. AN HTTP SERVLET HANDLING GET AND POST REQUEST Server HttpServlet subclass Get request response doGet( )) doGet( Post request service( )) service( response doPost( )) doPost( Any subclass overrides the doGet()/doPost method(s), not the service() method 13 PAW - HTTP Servlets 12
  • 13. SERVLET LIFE CYCLE Java Servlet-based Web Server Main Process Request for JVM Init() Servlet 1 Thread service() Servlet1 Servlet1 Request for Thread Servlet 2 Thread Servlet2 Request for Servlet2 Servlet 1 14 PAW - HTTP Servlets 13
  • 14. HttpServlet methods (1/2)  init()  Called only once during the initialization of the Servlet.  destroy()  Called only once when Servlet instance is about to be destroyed.  service()  Do not override this method!!.  doGet(), doPost(), doPut(), doDelete(), doOptions(), doTrace()  These methods are called according to the type of HTTP request received. Override them to generate your own response.  log()  Writes messages to the Servlet's log files. PAW - HTTP Servlets 14
  • 15. HttpServlet methods (2/2)  getLastModified()  Override this method to return your Servlet's last modified date.  getServletInfo()  Override this method to provide a String of general info about your Servlet such author, version, copyright etc.  getServletName()  Override this method to return name of the Servlet.  getInitParameter(), getInitParameterNames()  Return value(s) of initialization parameter(s)  getServletConfig()  Returns a reference to ServletConfig object.  getServletContext()  Returns reference to ServletContext object. PAW - HTTP Servlets 15
  • 16. Do not override...  service()  getServletConfig()  getServletContext() The three methods which stated above should not be overridden as their default implementation is more than enough to suffice. PAW - HTTP Servlets 16
  • 17. A “HELLO WORLD” SERVLET public class HelloServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("CIAO MONDO!"); } } 18 PAW - HTTP Servlets 17
  • 18. A “HELLO WORLD” HTML SERVLET protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out=response.getWriter(); String docType="<!DOCTYPE HTML PUBLIC "-//W3C/ /DTD HTML 4.0 "+ "Transitional //IT" > n"; out.println(docType); out.println( "<HTML>n" + "<HEAD><TITLE> CIAO MONDO HTML </TITLE><HEAD> n" + "<BODY>n" + "<H1> CIAO MONDO </H1> n" + "</BODY>" + "</HTML>"); } 19 PAW - HTTP Servlets 18
  • 19. Servlet input processing  protected void doGet(  HttpServletRequest request,  HttpServletResponse response  ) throws ServletException, IOException  A servlet may access the HTTP request information trough the request object  See: http://java.sun.com/javaee/5/docs/api/  HttpServletRequest  ServletRequest PAW - HTTP Servlets 19
  • 20. Request parameters  String getParameter(String name)  Returns the value of a request parameter as a String, or null if the parameter does not exist.  Map getParameterMap()  Returns a java.util.Map of the parameters of this request.  Enumeration getParameterNames()  Returns an Enumeration of String objects containing the names of the parameters contained in this request.  String[] getParameterValues(String name)  Returns an array of String objects containing all of the values the given request parameter has, or null if the parameter does not exist. PAW - HTTP Servlets 20
  • 21. HTTP headers information (1/2)  String getHeader(String name)  Returns the value of the specified request header as a String.  Int getIntHeader(String name)  Returns the value of the specified request header as an int.  Enumeration getHeaderNames()  Returns an enumeration of all the header names this request contains.  Enumeration getHeaders(String name)  Returns all the values of the specified request header as an Enumeration of String objects. PAW - HTTP Servlets 21
  • 22. HTTP headers information (2/2)  long getDateHeader(String name)  Returns the value of the specified request header as a long value that represents a Date object.  String getMethod()  Returns the name of the HTTP method with which this request was made, for example, GET, POST, or PUT.  String getQueryString()  Returns the query string that is contained in the request URL after the path.  String getRemoteUser()  Returns the login of the user making this request, if the user has been authenticated, or null if the user has not been authenticated. PAW - HTTP Servlets 22
  • 23. HTTP session handling  Cookie[] getCookies()  Returns an array containing all of the Cookie objects the client sent with this request.  String getRequestedSessionId()  Returns the session ID specified by the client.  HttpSession getSession()  Returns the current session associated with this request, or if the request does not have a session, creates one.  boolean isRequestedSessionIdValid()  Checks whether the requested session ID is still valid. PAW - HTTP Servlets 23
  • 24. Other interesting information  String getRemoteAddr()  Returns the Internet Protocol (IP) address of the client or last proxy that sent the request.  String getRemoteHost()  Returns the fully qualified name of the client or the last proxy that sent the request.  int getRemotePort()  Returns the Internet Protocol (IP) source port of the client or last proxy that sent the request.  String getServerName()  Returns the host name of the server to which the request was sent.  int getServerPort()  Returns the port number to which the request was sent. PAW - HTTP Servlets 24
  • 25. HttpSession class (1/3)  getAttribute(), getAttributeNames(), setAttribute(), removeAttribute()  These methods are used to set, get and remove objects from a user session.  getId()  Every session created by the server has a unique 'id' associated with it in order to identify this session from other sessions. This method returns the 'id' of this session.  getCreationTime()  Simple returns a long value indicating the date and time this session was created, meaning there by that you get the time this user first accessed your site. PAW - HTTP Servlets 25
  • 26. HttpSession class (2/3)  getLastAccessedTime()  Returns a long value indicating the last time user accessed any resource on this server.  getMaxInactiveInterval(), setMaxInactiveInterval()  Return and set the maximum inactive interval in seconds for this session respectively. Every session has a maximum inactive interval during which if user doesn't make request to the server, the session is invalidated.  isNew()  Returns a boolean value indicating if the session is new. Either it is the first page of the site user has hit so his session is new and has just been created or that user is not accepting cookies required for managing sessions so this value will then always return true. PAW - HTTP Servlets 26
  • 27. HttpSession class (3/3)  invalidate()  Simply invalidates a session. You can use this method on a 'logout' page allowing user to end his session. If after invalidation of his session user accesses some resource on the site then a new session will be created for it. PAW - HTTP Servlets 27
  • 28. ServletConfig class  ServletConfig object is used to pass information to the Servlet during its initialization  Inistialization information is stored in web.xml  Servlet can obtain information regarding initialization parameters and their values  using different methods of ServletConfig class. PAW - HTTP Servlets 28
  • 29. ServletConfig methods  getInitParameter(String paramName)  Returns value of the given parameter. If value of parameter could not be found in web.xml file then a null value is returned.  getInitParameterNames()  Returns an Enumeration object containing all the names of initialization parameters provided for this Servlet.  getServletContext()  Returns reference to the ServletContext object for this Servlet. It is similar to getServletContext() method provided by HttpServlet class.  getServletName()  Returns name of the Servlet as provided in the web.xml file or if none is provided then returns complete class PAW - HTTP Servlets to the Servlet. path 29
  • 30. A “hello world” servlet with init public void init(ServletConfig config) throws ServletException { super.init(config); String sRipetizioni = config.getInitParameter("ripetizioni"); Ripetizioni = Integer.parseInt(sRipetizioni); } 31 PAW - HTTP Servlets 30
  • 31. How To... JSP vs Servlet  Useful JSP constructs  <%@page pageEncoding=”text/html” %>  <jsp:forward page=”a.jsp” %>  <jsp:useBean … scope=”request” />  <jsp:useBean … scope=”session” />  How to translate them into Servlet instructions? PAW - HTTP Servlets 31
  • 32. HOW TO... output HTML  response.setContentType("text/html");  PrintWriter out = response.getWriter();  out.print("<html><head>..."); PAW - HTTP Servlets 32
  • 33. HOW TO... forward to another page  request.getRequestDispatcher(url).forward(request, response);  Step-by-step:  //request is HttpServletRequest object  RequestDispatcher rd;  rd = request.getRequestDispatcher("pathToServlet");  rd.forward(request, response); PAW - HTTP Servlets 33
  • 34. HOW TO... define and use a request Bean  Create a new bean with request scope  UserDataBean userData = new UserDataBean() ;  request.setAttribute("userData", userData);  Retrieve a bean from the request scope  UserDataBean userData = ((UserDataBean)request.getAttribute("userData")); PAW - HTTP Servlets 34
  • 35. HOW TO... define and use a session Bean  Linking to the current session  HttpSession session = request.getSession(true);  Creating a new bean with session scope  CounterBean counter; if(session.isNew()) { counter = new CounterBean(); session.setAttribute("counter", counter); }  Retrieving an existing bean with session scope  Counter = ((CounterBean)session.getAttribute("counter")); PAW - HTTP Servlets 35
  • 36. For more info...  http://www.unix.org.ua/orelly/java- ent/servlet/ch01_01.htm  http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/se rvlet/ PAW - HTTP Servlets 36