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

Contenu connexe

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

Similaire à Introduction to Servlets

Similaire à 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
 

Dernier

Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...RKavithamani
 

Dernier (20)

Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
 

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