SlideShare a Scribd company logo
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

ODP
Servlets
PPTX
Servlet.ppt
PPTX
Core web application development
PPTX
Servlet api &amp; servlet http package
PPTX
Java Servlets
PPTX
Servlets
PPT
Knowledge Sharing : Java Servlet
PDF
Java servlets
Servlets
Servlet.ppt
Core web application development
Servlet api &amp; servlet http package
Java Servlets
Servlets
Knowledge Sharing : Java Servlet
Java servlets

What's hot (20)

PPTX
Javax.servlet,http packages
PPTX
PPT
Java Servlet
PDF
Servlet and JSP
PPTX
Servletarchitecture,lifecycle,get,post
PPTX
java Servlet technology
PPT
1 java servlets and jsp
PDF
Java servlet technology
PDF
Weblogic
PPT
Java Servlets
PDF
Java EE 01-Servlets and Containers
PPT
Java Servlets
DOC
Java Servlets & JSP
PPTX
PPT
An Introduction To Java Web Technology
PDF
PPT
Web Tech Java Servlet Update1
PPT
Servlet 01
PDF
Jsp servlets
PDF
Servlets
Javax.servlet,http packages
Java Servlet
Servlet and JSP
Servletarchitecture,lifecycle,get,post
java Servlet technology
1 java servlets and jsp
Java servlet technology
Weblogic
Java Servlets
Java EE 01-Servlets and Containers
Java Servlets
Java Servlets & JSP
An Introduction To Java Web Technology
Web Tech Java Servlet Update1
Servlet 01
Jsp servlets
Servlets
Ad

Similar to Introduction to Servlets (20)

DOCX
Servlet
PPTX
SERVLET in web technolgy engineering.pptx
PPTX
Java servlets
PPT
PPTX
Http Server Programming in JAVA - Handling http requests and responses
PPTX
UNIT-3 Servlet
PPTX
Wt unit 3
PPTX
Java Servlet
PPT
Chap4 4 1
PPTX
gayathri.pptx
PDF
PPT
JAVA Servlets
PPTX
Chapter 3 servlet & jsp
PPTX
Servlets & jsp Overview
PDF
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
PPT
S E R V L E T S
PDF
SERVER SIDE PROGRAMMING
PPTX
Servlet in java , java servlet , servlet servlet and CGI, API
Servlet
SERVLET in web technolgy engineering.pptx
Java servlets
Http Server Programming in JAVA - Handling http requests and responses
UNIT-3 Servlet
Wt unit 3
Java Servlet
Chap4 4 1
gayathri.pptx
JAVA Servlets
Chapter 3 servlet & jsp
Servlets & jsp Overview
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
S E R V L E T S
SERVER SIDE PROGRAMMING
Servlet in java , java servlet , servlet servlet and CGI, API
Ad

Recently uploaded (20)

PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
Anesthesia in Laparoscopic Surgery in India
PPTX
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
PPTX
Cell Types and Its function , kingdom of life
PDF
What if we spent less time fighting change, and more time building what’s rig...
PDF
Practical Manual AGRO-233 Principles and Practices of Natural Farming
PPTX
UV-Visible spectroscopy..pptx UV-Visible Spectroscopy – Electronic Transition...
PDF
ChatGPT for Dummies - Pam Baker Ccesa007.pdf
PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
LDMMIA Reiki Yoga Finals Review Spring Summer
PDF
RMMM.pdf make it easy to upload and study
PDF
Updated Idioms and Phrasal Verbs in English subject
PPTX
Orientation - ARALprogram of Deped to the Parents.pptx
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
Chinmaya Tiranga quiz Grand Finale.pdf
PDF
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
PDF
Computing-Curriculum for Schools in Ghana
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Anesthesia in Laparoscopic Surgery in India
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
Cell Types and Its function , kingdom of life
What if we spent less time fighting change, and more time building what’s rig...
Practical Manual AGRO-233 Principles and Practices of Natural Farming
UV-Visible spectroscopy..pptx UV-Visible Spectroscopy – Electronic Transition...
ChatGPT for Dummies - Pam Baker Ccesa007.pdf
202450812 BayCHI UCSC-SV 20250812 v17.pptx
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
LDMMIA Reiki Yoga Finals Review Spring Summer
RMMM.pdf make it easy to upload and study
Updated Idioms and Phrasal Verbs in English subject
Orientation - ARALprogram of Deped to the Parents.pptx
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Chinmaya Tiranga quiz Grand Finale.pdf
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
2.FourierTransform-ShortQuestionswithAnswers.pdf
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
Computing-Curriculum for Schools in Ghana

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