Servlets
                  Java Web Applications




© SUPINFO International University – http://www.supinfo.com
Servlets

                      Course objectives
         By completing this course you will be able to:

                  – Explain what a servlet is

                  – Describe the Servlet API

                  – Create basic and advanced servlets

                  – Enumerate the main new features in Servlet 3.0

© SUPINFO International University – http://www.supinfo.com
Servlets

                      Course plan
                                                              – Introduction
                                                              – Servlet hierarchy
                                                              – Request and response processing
                                                              – Deployment descriptor
                                                              – The Web Container Model
                                                              – What’s new in Servlet 3.0?



© SUPINFO International University – http://www.supinfo.com
Servlets

              OVERVIEW

© SUPINFO International University – http://www.supinfo.com
Overview

                      Presentation
         • Classes executed on the server

         • Dynamic request processing

         • Dynamic response producing

         • Generally used on a Web server

© SUPINFO International University – http://www.supinfo.com
Overview

                      Advantages
         • Efficient :
                  –     JVM’s memory management
                  –     Only one instance per Servlet
                  –     One request = One Thread
                  –     …
         • Useful :
                  – Cookies
                  – Sessions
                  –…
© SUPINFO International University – http://www.supinfo.com
Overview

                      Advantages

         • Extensible and flexible :
                  – Run on numerous platforms and HTTP servers without
                    change
                  – Enhanced by many frameworks


         • Java Language ! (powerful, reliable with a lot of API)


© SUPINFO International University – http://www.supinfo.com
Overview

                      Drawbacks
         • Unsuitable for generating HTML and JavaScript code
                  – But JSP does (we’ll see it later)

         • Needs a Java Runtime Environment on the server
         • Needs a special “Servlet Container" on web server
         • Low level API
                  – But many Frameworks are based on it


© SUPINFO International University – http://www.supinfo.com
Overview

                      Dynamic process
         • Basic HTTP request handling
                  – Static HTML

                                                              ≠
         • Servlet request handling
                  – Dynamic response generated


© SUPINFO International University – http://www.supinfo.com
Overview

                      Basic request
                               1. Connection and request from client




                                                              2. Look for the target




             3. Page transferred to the client then disconnection

© SUPINFO International University – http://www.supinfo.com
Overview

                      Servlet request – First call
                               1. Connection and request from client
                                                                   2. Servlet is created
                                                                    and initialized by
                                                                       init() method



                                                                   3. Servlet executes
                                                                    service() method
               4. Response transferred then disconnection
© SUPINFO International University – http://www.supinfo.com
Overview

                      Servlet request – Other calls
                               1. Connection and request from client




                                                                   2. Servlet executes
                                                                    service() method



               3. Response transferred then disconnection
© SUPINFO International University – http://www.supinfo.com
Overview

                      Servlet Container
         • Servlet container implements the web component
           contract of the Java EE architecture
         • Also known as a web container
         • Examples of Servlet containers are :
                  – Tomcat
                  – Jetty
                  – Oracle iPlanet Web Server



© SUPINFO International University – http://www.supinfo.com
Overview

                      Servlet-Based frameworks
         • Few companies used Servlet technology alone…
                  – But a lot of companies used Servlet-based Frameworks !
                  – A large number exists :
                           •    Struts
                           •    JSF
                           •    Spring MVC
                           •    Wicket
                           •    Grails
                           •    …


© SUPINFO International University – http://www.supinfo.com
Overview

                      Servlet-Based frameworks




© SUPINFO International University – http://www.supinfo.com
Questions ?




© SUPINFO International University – http://www.supinfo.com
Servlets

              SERVLET HIERARCHY

© SUPINFO International University – http://www.supinfo.com
Servlet Hierarchy

                      Presentation
         • Servlet hierarchy is mainly composed of :

                  – Servlet interface

                  – GenericServlet abstract class

                  – HttpServlet abstract class



© SUPINFO International University – http://www.supinfo.com
Servlet Hierarchy

                      Servlet interface
         • Defines methods a servlet must implement :

                  – How the servlet is initialized?

                  – What services does it provide?

                  – How is it destroyed?

                  –…
© SUPINFO International University – http://www.supinfo.com
Servlets Hierarchy

                      Servlet methods overview

         Method                                               Description
         void init(ServletConfig sc)                          Called by the servlet container to make the servlet
                                                              active
         void service(ServletRequest req,                     Called by the servlet container to respond to a
         ServletResponse res)                                 request
         void destroy()                                       Called by the servlet container to make the servlet
                                                              out of service
         ServletConfig getServletConfig()                     Returns a ServletConfig object, which contains
                                                              initialization and startup parameters for this servlet
         String getServletInfo()                              Returns information about the servlet, such as
                                                              author, version, and copyright

© SUPINFO International University – http://www.supinfo.com
public class MyServlet implements Servlet {

        Servlet Example 1/2
                                    private ServletConfig config;

                                   @Override
                                   public void init(ServletConfig sc) {
                                      this.config = sc;
                                   }

                                   @Override
                                   public ServletConfig getServletConfig() {
                                      return this.config;
                                   }

                                   ...

© SUPINFO International University – http://www.supinfo.com
...
                                   @Override
        Servlet Example 2/2
                                   public String getServletInfo() {
                                       return "MyServlet is the best !!";
                                   }

                                    @Override
                                    public void service(ServletRequest req,
                                                              ServletResponse res) {
                                       res.getWriter().println("Hello world");
                                    }

                                    @Override
                                    public void destroy() { /* ... */ }
                              }

© SUPINFO International University – http://www.supinfo.com
Servlet Hierarchy

                      GenericServlet class
         • An independent-protocol Servlet
                  – Implements :
                           • Servlet
                           • ServletConfig


         • Implementations just need to
           define the service method



© SUPINFO International University – http://www.supinfo.com
Servlet Hierarchy

                      GenericServlet class example


      public class MyServlet extends GenericServlet {

      @Override
      public void service(ServletRequest req,
                                    ServletResponse res) {
         // Do whatever you want
      }
      }



© SUPINFO International University – http://www.supinfo.com
Servlet Hierarchy

                      HttpServlet class
         • A Servlet suitable for Web sites
         • Handles HTTP methods :
                  –     GET requests with doGet(…)
                  –     POST requests with doPost(…)
                  –     PUT requests with doPut(…)
                  –     Etc…
         • You can override one or
           several of them

© SUPINFO International University – http://www.supinfo.com
Servlet Hierarchy

                      HttpServlet class
         • How does it work?
                                            request Get
                                                                              doGet()
                                            request Post      service()
                                                                              doPost()
                  Client
                                                                          HttpServlet

         Be Careful: doGet(), doPost() and others, are called by the HttpServlet
         implementation of the service() method.
         If it is overridden, the HTTP handler methods will not be called!
© SUPINFO International University – http://www.supinfo.com
Servlets Hierarchy

                      HttpServlet
         • Methods overview:

         Method                                               Description
                                                              Receives standard HTTP requests and
         void service(HttpServletRequest req,
                                                              dispatches them to the doXXX methods
          HttpServletResponse res)
                                                              defined in this class
         void doGet(HttpServletRequest req,                   Handles GET requests
          HttpServletResponse res)
         void doPost(HttpServletRequest req,                  Handles POST requests
          HttpServletResponse res)
         …                                                    …

© SUPINFO International University – http://www.supinfo.com
public class MyServlet extends HttpServlet {

        HttpServlet example
                                   @Override
                                   public void doGet(HttpServletRequest req,
                                                          HttpServletResponse res) {
                                      // Do whatever you want
                                   }

                                   @Override
                                   public void doPost(HttpServletRequest req,
                                                          HttpServletResponse res) {
                                      // Do whatever you want here too ...
                                   }

                              }

© SUPINFO International University – http://www.supinfo.com
Questions ?




© SUPINFO International University – http://www.supinfo.com
Servlets

              REQUEST AND
              RESPONSE PROCESSING
© SUPINFO International University – http://www.supinfo.com
Request and Response processing

                      Introduction
         • The Servlet service() method owns:
                  – A ServletRequest representing a Request
                  – A ServletResponse representing a Response


         • You can use them !




© SUPINFO International University – http://www.supinfo.com
Request and Response processing

                      ServletRequest
         • Objects defined to provide client request information
           to a servlet

         • Useful to retrieve :
                  –     Parameters
                  –     Attributes
                  –     Server name and port
                  –     Protocol
                  –     …
© SUPINFO International University – http://www.supinfo.com
Request and Response processing

                      ServletRequest
         • Methods overview:
         Method                                               Description

         String getParameter(String name)
                                                              Return the request parameter(s)
         Map<String, String[]> getParameterMap()

         Object getAttribute()                                Retrieves/Stores an attribute from/to
         void setAttribute(String name, Object value)         the request

                                                              Indicates if the request was made using
         boolean isSecure()
                                                              a secure channel such as HTTPS



© SUPINFO International University – http://www.supinfo.com
Request and Response processing

                      ServletRequest
         • Methods overview:

         Method                                               Description

         String getServerName()
                                                              Get the server name and port
         int getServerPort()

         String getRemoteAddr()
                                                              Get the address, the hostname and the port of
         String getRemoteHost()
                                                              the client
         int getRemotePort()




© SUPINFO International University – http://www.supinfo.com
Request and Response processing

                      HttpServletRequest
         • Dedicated to HTTP Requests

         • Useful to retrieve :
                  –     The session associated to the request
                  –     The headers of the request
                  –     Cookies
                  –     …



© SUPINFO International University – http://www.supinfo.com
Request and Response processing

                      HttpServletRequest
         • Methods overview:

         Method                                               Description

         HttpSession getSession()                             Returns the session associated to the
         HttpSession getSession(boolean create)               request

         String getHeader(String name)                        Returns the value of the specified header

         Cookie[] getCookies()                                Get the cookies sent with the request




© SUPINFO International University – http://www.supinfo.com
Request and Response processing

                      ServletResponse
         • Objects defined to assist a servlet in sending a
           response to the client

         • Useful to retrieve :
                  – The output stream of the response
                  – A PrintWriter
                  –…



© SUPINFO International University – http://www.supinfo.com
Request and Response processing

                      ServletResponse
         • Methods overview:
         Method                                               Description
                                                              Returns the output stream of the servlet.
         ServletOutputStream getOutputStream()
                                                              Useful for binary data.
                                                              Returns a writer, useful to send textual
         PrintWriter getWriter()
                                                              response to the client
                                                              Defines the mime type of the response
         void setContentType(String content)
                                                              content, like "text/html"

         Be Careful: You can’t use getOutputStream() and getWriter() together.
         Calling both in a servlet gets an IllegalStateException.

© SUPINFO International University – http://www.supinfo.com
Request and Response processing

                      HttpServletResponse

         • Dedicated to HTTP Responses

         • Useful to :
                  – Add cookies
                  – Redirect the client
                  –…


© SUPINFO International University – http://www.supinfo.com
Request and Response processing

                      HttpServletResponse
         • Methods overview:


         Method                                               Description
         void addCookie(Cookie c)                             Add a cookie to the response
         void sendRedirect(String location)                   Redirect the client to the specified location




© SUPINFO International University – http://www.supinfo.com
public class MyServlet extends HttpServlet {
        PrintWriter Example         @Override
                                    protected void doGet(HttpServletRequest req,
                                                      HttpServletResponse resp) {

                                             String name = req.getParameter("name");

                                             resp.setContentType("text/html");
                                             PrintWriter out = resp.getWriter();
                                             out.println("<html>");
                                             out.println("<head>");
                                             out.println("<title>My Servlet</title>");
                                             out.println("</head>");
                                             out.println("<body>");
                                             out.println("<h1>Hello " + name + " !</h1>");
                                             out.println("</body>");
                                             out.println("</html>");
                                      }
                              }

© SUPINFO International University – http://www.supinfo.com
Questions ?




© SUPINFO International University – http://www.supinfo.com
Servlets

              DEPLOYMENT DESCRIPTOR
                                                   I’ve got my servlet, and now?

© SUPINFO International University – http://www.supinfo.com
Deployment descriptor

                      Introduction
         • A Servlet application has always (or almost) a
           deployment descriptor :
                  – /WEB-INF/web.xml

         • It defines :
                  –     The servlets classes                  - The welcome files
                  –     The servlets mappings                 - The application resources
                  –     The filters classes                   - And some other stuffs…
                  –     The filters mappings

© SUPINFO International University – http://www.supinfo.com
Deployment descriptor

                      web.xml
       <?xml version="1.0" encoding="UTF-8"?>
       <web-app xmlns=...>

                <display-name>MyApplication</display-name>

                <welcome-file-list>
                   <welcome-file>index.html</welcome-file>
                   <welcome-file>index.jsp</welcome-file>
                </welcome-file-list>

                <!-- Servlet declarations -->
                <!-- Servlet mappings -->
                <!– Other stuffs -->

       </web-app>

© SUPINFO International University – http://www.supinfo.com
Deployment Descriptor

                      Servlet declaration and mapping
         • When you create a servlet, in order to use it, you
           must

                 1. Declare it in a servlet block
                         a.        Give it a logical name
                         b.        Give the “Fully Qualified Name” of the servlet


                 2. Map it to an url-pattern in a servlet-mapping block


© SUPINFO International University – http://www.supinfo.com
Deployment descriptor

                      web.xml

      <servlet>
         <servlet-name>MyServlet</servlet-name>
         <servlet-class>com.supinfo.app.MyServlet</servlet-class>
      </servlet>

      <servlet-mapping>
         <servlet-name>MyServlet</servlet-name>
         <url-pattern>/Hello</url-pattern>
      </servlet-mapping>


      ⇒ The “servlet-name” in both blocks “servlet” and
        “servlet-mapping” must be the same!

© SUPINFO International University – http://www.supinfo.com
Deployment descriptor

                      How it works?
                                                   1

                                                                           5


                       <servlet>
                            <servlet-name>MyServlet</servlet-name>
                                                                        4
                            <servlet-class>com.supinfo.app.MyServlet</servlet-class>
                       </servlet>
             3
                       <servlet-mapping>
                            <servlet-name>MyServlet</servlet-name>
                            <url-pattern>/Hello</url-pattern>          2
                       </servlet-mapping>



© SUPINFO International University – http://www.supinfo.com
Deployment descriptor

                      URL Patterns
            Match rule                    URL Pattern             URL Pattern form         URLs That Would Match
                 Exact                /something              Any string with “/” below    /something

                                                                                           /something/
                                                              String beginning with “/”
                  Path                /something/*                                         /something/else
                                                              and ending with “/*”
                                                                                           /something/index.htm

                                                                                           /index.jsp
             Extension                *.jsp                   String ending with “*.jsp”
                                                                                           /something/index.jsp
                                                                                           Any URL without better
               Default                /                       Only “/”
                                                                                           matching



© SUPINFO International University – http://www.supinfo.com
Questions ?




© SUPINFO International University – http://www.supinfo.com
Servlets

              THE WEB CONTAINER MODEL
                                                 ServletContext, scopes, filters…

© SUPINFO International University – http://www.supinfo.com
The web container model

                      Scopes
         • Java Web Applications have 3 different scopes
                  – Request representing by ServletRequest
                  – Session representing by HttpSession
                  – Application representing by ServletContext



         • We have already seen ServletRequest, we’re going to
           discover the two others…

© SUPINFO International University – http://www.supinfo.com
The web container model

                      Scopes
         • Each of them can manage attributes
                  – Object getAttribute(String name)
                  – void setAttribute(String name, Object value)
                  – void removeAttribute(String name)


         • These functions are useful to forward some values
           along user navigation, like the user name or the
           amount of pages visited on a specific day

© SUPINFO International University – http://www.supinfo.com
The web container model

                      ServletContext
         • Retrieve it with a ServletConfig
                  – Or an HttpServlet
                           (which implements a ServletConfig, remember ?)
         • Allows communication between the servlets and the
           servlet container
                  – Only one instance per Web Application per JVM


         • Contains useful data as context path, Application
           Scope attributes, …
© SUPINFO International University – http://www.supinfo.com
The web container model

                      ServletContext
         • Add an attribute to the ServletContext
                  – This attribute will be accessible in whole application


    // ...
    getServletContext().setAttribute("nbOfConnection”,0);
    // ...




© SUPINFO International University – http://www.supinfo.com
The web container model

                      ServletContext
         • Retrieve an attribute from the ServletContext and
           update it:

     // ...
     ServletContext sc = getServletContext();
     Integer nbOfConnection =
            (Integer) sc.getAttribute("nbOfConnection");
     sc.setAttribute("nbOfConnection", ++nbOfConnection);
     // ...




© SUPINFO International University – http://www.supinfo.com
The web container model

                      ServletContext
         • Remove an attribute from the ServletContext:
                  – Trying to retrieve an unknown or unset value returns null


    // ...
    getServletContext().removeAttribute("nbOfConnection");
    // ...




© SUPINFO International University – http://www.supinfo.com
The web container model

                      Session
         • Interface: HttpSession
         • Retrieve it with an HttpServletRequest
                  – request.getSession();


         • Useful methods:
                  – setAttribute(String name, Object value)
                  – getAttribute(String name)
                  – removeAttribute(String name)

© SUPINFO International University – http://www.supinfo.com
The web container model

                      Session
         • Retrieve a HttpSession and add an attribute to it :
                  – This attribute will be accessible in whole user session

     // ...
     HttpSession session = request.getSession();
     Car myCar = new Car();
     session.setAttribute("car", myCar);
     // ...




© SUPINFO International University – http://www.supinfo.com
The web container model

                      Session
         • Retrieve an attribute to it:


     // ...
     Car aCar = (Car) session.getAttribute("car");
     // ...




© SUPINFO International University – http://www.supinfo.com
The web container model

                      Session
         • Remove an attribute to it:
                  – Trying to retrieve an unknown or unset value returns null


    // ...
    session.removeAttribute("car");
    // ...




© SUPINFO International University – http://www.supinfo.com
The web container model

                      Chaining

         • From a servlet you can:

                  – include the content of another resource inside the
                    response

                  – forward a request from the servlet to another resource



© SUPINFO International University – http://www.supinfo.com
The web container model

                      Chaining

         • You must use a RequestDispatcher

                  – Obtained with the request

    // Get the dispatcher
    RequestDispatcher rd =
       request.getRequestDispatcher("/somewhereElse");




© SUPINFO International University – http://www.supinfo.com
The web container model

                      Chaining
         • Then you can include another servlet:

    rd.include(request, response);
    out.println("This print statement will be executed");



         • Or forward the request to another servlet:

    rd.forward(request, response);
    out.println("This print statement will not be executed");



© SUPINFO International University – http://www.supinfo.com
The web container model

                      Chaining – Include

                                                                  MyHttpServlet1
                                        request                                         MyHttpServlet2
                                                                  service(...) {    2
                                                              1
                                                                  // do something       service(...) {
                                                                  rd.include(…);        // do sthg else
                                                                  // do something       }
                                                                                    3
                  Client                response                  }
                                                              4




© SUPINFO International University – http://www.supinfo.com
The web container model

                      Chaining – Forward

                                                              MyHttpServlet1
                                   request
                                                              service(...) {
                                                              // do something
                                                         1                      2   MyHttpServlet2
                                                              rd.forward(…);        service(...) {
                                                              }                     // do sthg else
             Client
                                   response                                         }
                                                         3




© SUPINFO International University – http://www.supinfo.com
The web container model

                      Chaining
         • Use request attributes to pass information between
           servlets
                  – Servlet 1:
     // Other stuff
     Car aCar = new Car("Renault", "Clio");
     request.setAttribute("car", aCar);
     RequestDispatcher rd =
        request.getRequestDispatcher("/Servlet2");
     rd.forward(request, response);


© SUPINFO International University – http://www.supinfo.com
The web container model

                      Chaining
         • Retrieve attribute in another servlet:
                  – Servlet 2 mapped to /Servlet2


     // Other stuff
     Car aCar = (Car) request.getAttribute("car");
     out.println("My car is a " + car.getBrand());
     // Outputs "Renault"




© SUPINFO International University – http://www.supinfo.com
The web container model

                      Filter
         • Component which dynamically intercepts requests &
           responses to use or transform them
         • Encapsulate recurring tasks in reusable units

         • Example of functions filters can have :
                  – Authentication - Blocking requests based on user identity
                  – Logging and auditing - Tracking users of a web application.
                  – Data compression - Making downloads smaller.

© SUPINFO International University – http://www.supinfo.com
The web container model

                      Filter
                                      Request
                                                                                              LoginServlet
                                                                                   Response


                                                                                              AddCarServlet
                                                                             Authenticate
                                                              Audit Filter      Filter
                                                                                              EditCarServlet



                                                                                              LogoutServlet


© SUPINFO International University – http://www.supinfo.com
The web container model

                      Filter
         • Create a class implementing the javax.servlet.Filter
           interface
         • Define the methods :
                  – init(FilterConfig)
                  – doFilter(ServletResquest, ServletResponse, FilterChain)
                  – destroy()




© SUPINFO International University – http://www.supinfo.com
The web container model

                      Filter
         • In the doFilter method
                  – Use the doFilter(…) of the FilterChain to call the next
                    element in the chain

                  – Instructions before this statement will be executed before
                    the next element
                  – Instructions after will be executed after the next element

                  – Don’t call doFilter(…) method of the FilterChain to break
                    the chain
© SUPINFO International University – http://www.supinfo.com
The web container model

                      Filter
                                            Request                 Client            Response


                                                                     Filter

                                                                     Filter

                                                                     Filter

                                                                  Resource
                                                              Servlet, JSP, HTML, …


                                                                   Container


© SUPINFO International University – http://www.supinfo.com
The web container model

                      Filter example
       public final class HitCounterFilter implements Filter {
          //...
          public void doFilter(ServletRequest request,
                ServletResponse response, FilterChain chain) {

                        ServletContext sc = filterConfig.getServletContext();
                        Counter counter =
                               (Counter) sc.getAttribute("hitCounter");

                         System.out.println("The number of hits is: "
                                                  + counter.incCounter());
                        chain.doFilter(request, response);
                }
                //...
       }

© SUPINFO International University – http://www.supinfo.com
The web container model

                      Filter declaration
         • Declare your filter in the web.xml file:
      <filter>
          <filter-name>MyHitCounterFilter</filter-name>
          <filter-class>
              com.supinfo.sun.filters.HitCounterFilter
          </filter-class>
      </filter>

      <filter-mapping>
          <filter-name>MyHitCounterFilter</filter-name>
          <url-pattern>/*</url-pattern>
      </filter-mapping>


© SUPINFO International University – http://www.supinfo.com
The web container model

                      Cookies
         • Can be placed in an HttpServletResponse
         • Can be retrieved in an HttpServletRequest
         • Constructor :
                  – Cookie(String name, String value)
         • Methods :
                  – String getName()
                  – String getValue()


© SUPINFO International University – http://www.supinfo.com
The web container model

                      Cookies example
         • Add a cookie to a response:


     // ...
     Cookie myCookie = new Cookie("MySuperCookie",
                               "This is my cookie :)");
     response.addCookie(myCookie);
     // ...




© SUPINFO International University – http://www.supinfo.com
The web container model

                      Cookies example
         • Retrieve cookies from the request:

      // ...
      Cookie[] list = request.getCookies();
      for(Cookie c : list) {
      System.out.println("Name: " + c.getName()
                          + " Value: " + c.getValue());
      }
      // ...



© SUPINFO International University – http://www.supinfo.com
Questions ?




© SUPINFO International University – http://www.supinfo.com
Servlets

              WHAT’S NEW IN SERVLET 3.0 ?
                                                 Annotations, Web fragments, …

© SUPINFO International University – http://www.supinfo.com
What’s new in Servlet 3.0 ?

                      Introduction
         • The 10th December 2009, Sun Microsystems releases
           the version 6 of Java EE
         • It includes a lot of new JSR like:
                  – EJB 3.1
                  – JPA 2.0
                  – … and Servlet 3.0 !
         • For more information about JSRs include in Java EE 6:
                                   http://en.wikipedia.org/wiki/Java_EE_version_history


© SUPINFO International University – http://www.supinfo.com
What’s new in Servlet 3.0 ?

                      Configuration through annotations
         • Annotations are used more and more in Java
           development :
                  – To map classes with tables in database (JPA)

                  – To define validation rules (Bean Validation)

                  – And now to define Servlets and Filters without declare
                    them into deployment descriptor !


© SUPINFO International University – http://www.supinfo.com
What’s new in Servlet 3.0 ?

                      Configuration through annotations
         • So why not have seen this from the beginning ?
                  – Because Servlet 2.5 is still extremely used

                  – And you can still used deployment descriptor with Servlet
                    3.0




© SUPINFO International University – http://www.supinfo.com
What’s new in Servlet 3.0 ?

                      Servet 3.0 main annotations
         • @WebServlet : Mark a class as a Servlet (must still
           extends HttpServlet)

         • Some attributes of this annotation are :
                  – name (optional) :
                           • The name of the Servlet
                  – urlPatterns :
                           • The URL patterns to which the Servlet applies


© SUPINFO International University – http://www.supinfo.com
What’s new in Servlet 3.0 ?

                      Servlet 3.0 main annotations
         • @WebFilter : Mark a class as a Filter

         • Some attributes of this annotation are :
                  – filterName (optional) :
                           • The name of the Filter
                  – servletNames (optional if urlPatterns) :
                           • The names of the servlets to which the Filter applies
                  – urlPatterns (optional if servletNames) :
                           • The URL patterns to which the Filter applies

© SUPINFO International University – http://www.supinfo.com
What’s new in Servlet 3.0 ?

                      Examples

     @WebServlet(urlPatterns="/myservlet")
     public class SimpleServlet extends HttpServlet {
      ...
     }



     @WebFilter(urlPatterns={"/myfilter","/simplefilter"})
     public class SimpleFilter implements Filter {
      ...
     }


© SUPINFO International University – http://www.supinfo.com
What’s new in Servlet 3.0 ?

                      Web Fragments
         • New system which allow to partition the deployment
           descriptor
                  – Useful for third party libraries to include a default web
                    configuration
         • A Web Fragment, as Deployment Descriptor, is an
           XML file :
                  – Named web-fragment.xml
                  – Placed inside the META-INF folder of the library
                  – With <web-fragment> as root element
© SUPINFO International University – http://www.supinfo.com
<!-- Example of web-fragment.xml -->
        Web Fragments Example   <web-fragment>
                                   <name>MyFragment</name>
                                   <listener>
                                      <listener-class>
                                         com.enterprise.project.module.MyListener
                                      </listener-class>
                                   </listener>
                                   <servlet>
                                      <servlet-name>MyServletFragment</servlet-name>
                                      <servlet-class>
                                         com.enterprise.project.module.MyServlet
                                      </servlet-class>
                                   </servlet>
                                </web-fragment>

© SUPINFO International University – http://www.supinfo.com
Questions ?




© SUPINFO International University – http://www.supinfo.com
Servlets

                      The end




            Thanks for your attention
© SUPINFO International University – http://www.supinfo.com

More Related Content

PDF
Making Portals Cool: The Compelling Advantages of a Portlet Bridge
PDF
Ajax In Enterprise Portals
PDF
Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010
PDF
Introduction to Servlets
PDF
Apache Manager Table of Contents
PDF
Packagez et déployez vos applications avec Docker - Montréal CloudFoundry Mee...
PPT
Java: Java Applets
PDF
Introduction to java servlet 3.0 api javaone 2009
Making Portals Cool: The Compelling Advantages of a Portlet Bridge
Ajax In Enterprise Portals
Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010
Introduction to Servlets
Apache Manager Table of Contents
Packagez et déployez vos applications avec Docker - Montréal CloudFoundry Mee...
Java: Java Applets
Introduction to java servlet 3.0 api javaone 2009

Viewers also liked (20)

PDF
Introduction to java servlet 3.0 api javaone 2008
PPT
Web Application Deployment
PDF
Story of Julia
PDF
The Patterns to boost your time to market - An introduction to DevOps
PDF
Docker 1.12 & Swarm Mode [Montreal Docker Meetup Sept. 2016]
PDF
Evry`U guide
PPTX
Serenity walk
PPTX
English house Tuleneva
PDF
Stappenplan+ben+rietdijk+sport
PPT
Lucy and the lost mouse
ODT
Resolucio practica5 pqpi2
PPTX
как выучить иностранный язык
PPTX
Project "My flat" by Pochkina A. 5 form
PPT
Three sad dogs
PDF
Write quickinc portfoliosamples
PPTX
Amigos(as))
DOC
Bible study lesson #10 (fall 2011)
PPT
Biruk.rwandan genocide.p6
PPTX
Tips on How To Apply A Screen Protector In Base
Introduction to java servlet 3.0 api javaone 2008
Web Application Deployment
Story of Julia
The Patterns to boost your time to market - An introduction to DevOps
Docker 1.12 & Swarm Mode [Montreal Docker Meetup Sept. 2016]
Evry`U guide
Serenity walk
English house Tuleneva
Stappenplan+ben+rietdijk+sport
Lucy and the lost mouse
Resolucio practica5 pqpi2
как выучить иностранный язык
Project "My flat" by Pochkina A. 5 form
Three sad dogs
Write quickinc portfoliosamples
Amigos(as))
Bible study lesson #10 (fall 2011)
Biruk.rwandan genocide.p6
Tips on How To Apply A Screen Protector In Base
Ad

Similar to Java EE - Servlets API (20)

PPTX
WEB TECHNOLOGY Unit-3.pptx
PPTX
servlets sessions and cookies, jdbc connectivity
PDF
Java EE 01-Servlets and Containers
PDF
SERVER SIDE PROGRAMMING
PPTX
SERVLETS (2).pptxintroduction to servlet with all servlets
PPT
JAVA Servlets
PPTX
Wt unit 3
PPTX
SERVLET in web technolgy engineering.pptx
PDF
Bt0083 server side programing
PPTX
J2ee servlet
PPTX
Java Servlet
PDF
Weblogic
PPTX
BITM3730Week12.pptx
PPTX
UNIT-3 Servlet
PPTX
JAVA SERVLETS acts as a middle layer between a request coming from a web brow...
PDF
Java servlets
PPTX
Chapter 3 servlet & jsp
PPTX
Enterprise java unit-1_chapter-3
PPTX
Servlets-UNIT3and introduction to servlet
PPTX
ADP - Chapter 2 Exploring the java Servlet Technology
WEB TECHNOLOGY Unit-3.pptx
servlets sessions and cookies, jdbc connectivity
Java EE 01-Servlets and Containers
SERVER SIDE PROGRAMMING
SERVLETS (2).pptxintroduction to servlet with all servlets
JAVA Servlets
Wt unit 3
SERVLET in web technolgy engineering.pptx
Bt0083 server side programing
J2ee servlet
Java Servlet
Weblogic
BITM3730Week12.pptx
UNIT-3 Servlet
JAVA SERVLETS acts as a middle layer between a request coming from a web brow...
Java servlets
Chapter 3 servlet & jsp
Enterprise java unit-1_chapter-3
Servlets-UNIT3and introduction to servlet
ADP - Chapter 2 Exploring the java Servlet Technology
Ad

More from Brice Argenson (9)

PDF
RSpock Testing Framework for Ruby
PDF
Serverless Applications
PDF
Serverless - Lunch&Learn CleverToday - Mars 2017
PDF
Docker 1.13 - Docker meetup février 2017
PPTX
Introduction to Continuous Integration with Jenkins
PDF
JS-Everywhere - SSE Hands-on
PDF
JS-Everywhere - LocalStorage Hands-on
PPTX
Effective Java
PPTX
Soutenance mémoire : Implémentation d'un DSL en entreprise
RSpock Testing Framework for Ruby
Serverless Applications
Serverless - Lunch&Learn CleverToday - Mars 2017
Docker 1.13 - Docker meetup février 2017
Introduction to Continuous Integration with Jenkins
JS-Everywhere - SSE Hands-on
JS-Everywhere - LocalStorage Hands-on
Effective Java
Soutenance mémoire : Implémentation d'un DSL en entreprise

Recently uploaded (20)

PPTX
Final SEM Unit 1 for mit wpu at pune .pptx
PDF
Getting started with AI Agents and Multi-Agent Systems
PDF
Convolutional neural network based encoder-decoder for efficient real-time ob...
DOCX
Basics of Cloud Computing - Cloud Ecosystem
PDF
Taming the Chaos: How to Turn Unstructured Data into Decisions
PPTX
Benefits of Physical activity for teenagers.pptx
PPTX
The various Industrial Revolutions .pptx
DOCX
search engine optimization ppt fir known well about this
PDF
CloudStack 4.21: First Look Webinar slides
PDF
Developing a website for English-speaking practice to English as a foreign la...
PDF
Five Habits of High-Impact Board Members
PPTX
Custom Battery Pack Design Considerations for Performance and Safety
PDF
Flame analysis and combustion estimation using large language and vision assi...
PDF
Hybrid horned lizard optimization algorithm-aquila optimizer for DC motor
PDF
How ambidextrous entrepreneurial leaders react to the artificial intelligence...
PDF
OpenACC and Open Hackathons Monthly Highlights July 2025
PDF
Statistics on Ai - sourced from AIPRM.pdf
PDF
“A New Era of 3D Sensing: Transforming Industries and Creating Opportunities,...
PDF
sbt 2.0: go big (Scala Days 2025 edition)
PDF
Comparative analysis of machine learning models for fake news detection in so...
Final SEM Unit 1 for mit wpu at pune .pptx
Getting started with AI Agents and Multi-Agent Systems
Convolutional neural network based encoder-decoder for efficient real-time ob...
Basics of Cloud Computing - Cloud Ecosystem
Taming the Chaos: How to Turn Unstructured Data into Decisions
Benefits of Physical activity for teenagers.pptx
The various Industrial Revolutions .pptx
search engine optimization ppt fir known well about this
CloudStack 4.21: First Look Webinar slides
Developing a website for English-speaking practice to English as a foreign la...
Five Habits of High-Impact Board Members
Custom Battery Pack Design Considerations for Performance and Safety
Flame analysis and combustion estimation using large language and vision assi...
Hybrid horned lizard optimization algorithm-aquila optimizer for DC motor
How ambidextrous entrepreneurial leaders react to the artificial intelligence...
OpenACC and Open Hackathons Monthly Highlights July 2025
Statistics on Ai - sourced from AIPRM.pdf
“A New Era of 3D Sensing: Transforming Industries and Creating Opportunities,...
sbt 2.0: go big (Scala Days 2025 edition)
Comparative analysis of machine learning models for fake news detection in so...

Java EE - Servlets API

  • 1. Servlets Java Web Applications © SUPINFO International University – http://www.supinfo.com
  • 2. Servlets Course objectives By completing this course you will be able to: – Explain what a servlet is – Describe the Servlet API – Create basic and advanced servlets – Enumerate the main new features in Servlet 3.0 © SUPINFO International University – http://www.supinfo.com
  • 3. Servlets Course plan – Introduction – Servlet hierarchy – Request and response processing – Deployment descriptor – The Web Container Model – What’s new in Servlet 3.0? © SUPINFO International University – http://www.supinfo.com
  • 4. Servlets OVERVIEW © SUPINFO International University – http://www.supinfo.com
  • 5. Overview Presentation • Classes executed on the server • Dynamic request processing • Dynamic response producing • Generally used on a Web server © SUPINFO International University – http://www.supinfo.com
  • 6. Overview Advantages • Efficient : – JVM’s memory management – Only one instance per Servlet – One request = One Thread – … • Useful : – Cookies – Sessions –… © SUPINFO International University – http://www.supinfo.com
  • 7. Overview Advantages • Extensible and flexible : – Run on numerous platforms and HTTP servers without change – Enhanced by many frameworks • Java Language ! (powerful, reliable with a lot of API) © SUPINFO International University – http://www.supinfo.com
  • 8. Overview Drawbacks • Unsuitable for generating HTML and JavaScript code – But JSP does (we’ll see it later) • Needs a Java Runtime Environment on the server • Needs a special “Servlet Container" on web server • Low level API – But many Frameworks are based on it © SUPINFO International University – http://www.supinfo.com
  • 9. Overview Dynamic process • Basic HTTP request handling – Static HTML ≠ • Servlet request handling – Dynamic response generated © SUPINFO International University – http://www.supinfo.com
  • 10. Overview Basic request 1. Connection and request from client 2. Look for the target 3. Page transferred to the client then disconnection © SUPINFO International University – http://www.supinfo.com
  • 11. Overview Servlet request – First call 1. Connection and request from client 2. Servlet is created and initialized by init() method 3. Servlet executes service() method 4. Response transferred then disconnection © SUPINFO International University – http://www.supinfo.com
  • 12. Overview Servlet request – Other calls 1. Connection and request from client 2. Servlet executes service() method 3. Response transferred then disconnection © SUPINFO International University – http://www.supinfo.com
  • 13. Overview Servlet Container • Servlet container implements the web component contract of the Java EE architecture • Also known as a web container • Examples of Servlet containers are : – Tomcat – Jetty – Oracle iPlanet Web Server © SUPINFO International University – http://www.supinfo.com
  • 14. Overview Servlet-Based frameworks • Few companies used Servlet technology alone… – But a lot of companies used Servlet-based Frameworks ! – A large number exists : • Struts • JSF • Spring MVC • Wicket • Grails • … © SUPINFO International University – http://www.supinfo.com
  • 15. Overview Servlet-Based frameworks © SUPINFO International University – http://www.supinfo.com
  • 16. Questions ? © SUPINFO International University – http://www.supinfo.com
  • 17. Servlets SERVLET HIERARCHY © SUPINFO International University – http://www.supinfo.com
  • 18. Servlet Hierarchy Presentation • Servlet hierarchy is mainly composed of : – Servlet interface – GenericServlet abstract class – HttpServlet abstract class © SUPINFO International University – http://www.supinfo.com
  • 19. Servlet Hierarchy Servlet interface • Defines methods a servlet must implement : – How the servlet is initialized? – What services does it provide? – How is it destroyed? –… © SUPINFO International University – http://www.supinfo.com
  • 20. Servlets Hierarchy Servlet methods overview Method Description void init(ServletConfig sc) Called by the servlet container to make the servlet active void service(ServletRequest req, Called by the servlet container to respond to a ServletResponse res) request void destroy() Called by the servlet container to make the servlet out of service ServletConfig getServletConfig() Returns a ServletConfig object, which contains initialization and startup parameters for this servlet String getServletInfo() Returns information about the servlet, such as author, version, and copyright © SUPINFO International University – http://www.supinfo.com
  • 21. public class MyServlet implements Servlet { Servlet Example 1/2 private ServletConfig config; @Override public void init(ServletConfig sc) { this.config = sc; } @Override public ServletConfig getServletConfig() { return this.config; } ... © SUPINFO International University – http://www.supinfo.com
  • 22. ... @Override Servlet Example 2/2 public String getServletInfo() { return "MyServlet is the best !!"; } @Override public void service(ServletRequest req, ServletResponse res) { res.getWriter().println("Hello world"); } @Override public void destroy() { /* ... */ } } © SUPINFO International University – http://www.supinfo.com
  • 23. Servlet Hierarchy GenericServlet class • An independent-protocol Servlet – Implements : • Servlet • ServletConfig • Implementations just need to define the service method © SUPINFO International University – http://www.supinfo.com
  • 24. Servlet Hierarchy GenericServlet class example public class MyServlet extends GenericServlet { @Override public void service(ServletRequest req, ServletResponse res) { // Do whatever you want } } © SUPINFO International University – http://www.supinfo.com
  • 25. Servlet Hierarchy HttpServlet class • A Servlet suitable for Web sites • Handles HTTP methods : – GET requests with doGet(…) – POST requests with doPost(…) – PUT requests with doPut(…) – Etc… • You can override one or several of them © SUPINFO International University – http://www.supinfo.com
  • 26. Servlet Hierarchy HttpServlet class • How does it work? request Get doGet() request Post service() doPost() Client HttpServlet Be Careful: doGet(), doPost() and others, are called by the HttpServlet implementation of the service() method. If it is overridden, the HTTP handler methods will not be called! © SUPINFO International University – http://www.supinfo.com
  • 27. Servlets Hierarchy HttpServlet • Methods overview: Method Description Receives standard HTTP requests and void service(HttpServletRequest req, dispatches them to the doXXX methods HttpServletResponse res) defined in this class void doGet(HttpServletRequest req, Handles GET requests HttpServletResponse res) void doPost(HttpServletRequest req, Handles POST requests HttpServletResponse res) … … © SUPINFO International University – http://www.supinfo.com
  • 28. public class MyServlet extends HttpServlet { HttpServlet example @Override public void doGet(HttpServletRequest req, HttpServletResponse res) { // Do whatever you want } @Override public void doPost(HttpServletRequest req, HttpServletResponse res) { // Do whatever you want here too ... } } © SUPINFO International University – http://www.supinfo.com
  • 29. Questions ? © SUPINFO International University – http://www.supinfo.com
  • 30. Servlets REQUEST AND RESPONSE PROCESSING © SUPINFO International University – http://www.supinfo.com
  • 31. Request and Response processing Introduction • The Servlet service() method owns: – A ServletRequest representing a Request – A ServletResponse representing a Response • You can use them ! © SUPINFO International University – http://www.supinfo.com
  • 32. Request and Response processing ServletRequest • Objects defined to provide client request information to a servlet • Useful to retrieve : – Parameters – Attributes – Server name and port – Protocol – … © SUPINFO International University – http://www.supinfo.com
  • 33. Request and Response processing ServletRequest • Methods overview: Method Description String getParameter(String name) Return the request parameter(s) Map<String, String[]> getParameterMap() Object getAttribute() Retrieves/Stores an attribute from/to void setAttribute(String name, Object value) the request Indicates if the request was made using boolean isSecure() a secure channel such as HTTPS © SUPINFO International University – http://www.supinfo.com
  • 34. Request and Response processing ServletRequest • Methods overview: Method Description String getServerName() Get the server name and port int getServerPort() String getRemoteAddr() Get the address, the hostname and the port of String getRemoteHost() the client int getRemotePort() © SUPINFO International University – http://www.supinfo.com
  • 35. Request and Response processing HttpServletRequest • Dedicated to HTTP Requests • Useful to retrieve : – The session associated to the request – The headers of the request – Cookies – … © SUPINFO International University – http://www.supinfo.com
  • 36. Request and Response processing HttpServletRequest • Methods overview: Method Description HttpSession getSession() Returns the session associated to the HttpSession getSession(boolean create) request String getHeader(String name) Returns the value of the specified header Cookie[] getCookies() Get the cookies sent with the request © SUPINFO International University – http://www.supinfo.com
  • 37. Request and Response processing ServletResponse • Objects defined to assist a servlet in sending a response to the client • Useful to retrieve : – The output stream of the response – A PrintWriter –… © SUPINFO International University – http://www.supinfo.com
  • 38. Request and Response processing ServletResponse • Methods overview: Method Description Returns the output stream of the servlet. ServletOutputStream getOutputStream() Useful for binary data. Returns a writer, useful to send textual PrintWriter getWriter() response to the client Defines the mime type of the response void setContentType(String content) content, like "text/html" Be Careful: You can’t use getOutputStream() and getWriter() together. Calling both in a servlet gets an IllegalStateException. © SUPINFO International University – http://www.supinfo.com
  • 39. Request and Response processing HttpServletResponse • Dedicated to HTTP Responses • Useful to : – Add cookies – Redirect the client –… © SUPINFO International University – http://www.supinfo.com
  • 40. Request and Response processing HttpServletResponse • Methods overview: Method Description void addCookie(Cookie c) Add a cookie to the response void sendRedirect(String location) Redirect the client to the specified location © SUPINFO International University – http://www.supinfo.com
  • 41. public class MyServlet extends HttpServlet { PrintWriter Example @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) { String name = req.getParameter("name"); resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); out.println("<html>"); out.println("<head>"); out.println("<title>My Servlet</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Hello " + name + " !</h1>"); out.println("</body>"); out.println("</html>"); } } © SUPINFO International University – http://www.supinfo.com
  • 42. Questions ? © SUPINFO International University – http://www.supinfo.com
  • 43. Servlets DEPLOYMENT DESCRIPTOR I’ve got my servlet, and now? © SUPINFO International University – http://www.supinfo.com
  • 44. Deployment descriptor Introduction • A Servlet application has always (or almost) a deployment descriptor : – /WEB-INF/web.xml • It defines : – The servlets classes - The welcome files – The servlets mappings - The application resources – The filters classes - And some other stuffs… – The filters mappings © SUPINFO International University – http://www.supinfo.com
  • 45. Deployment descriptor web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns=...> <display-name>MyApplication</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- Servlet declarations --> <!-- Servlet mappings --> <!– Other stuffs --> </web-app> © SUPINFO International University – http://www.supinfo.com
  • 46. Deployment Descriptor Servlet declaration and mapping • When you create a servlet, in order to use it, you must 1. Declare it in a servlet block a. Give it a logical name b. Give the “Fully Qualified Name” of the servlet 2. Map it to an url-pattern in a servlet-mapping block © SUPINFO International University – http://www.supinfo.com
  • 47. Deployment descriptor web.xml <servlet> <servlet-name>MyServlet</servlet-name> <servlet-class>com.supinfo.app.MyServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>MyServlet</servlet-name> <url-pattern>/Hello</url-pattern> </servlet-mapping> ⇒ The “servlet-name” in both blocks “servlet” and “servlet-mapping” must be the same! © SUPINFO International University – http://www.supinfo.com
  • 48. Deployment descriptor How it works? 1 5 <servlet> <servlet-name>MyServlet</servlet-name> 4 <servlet-class>com.supinfo.app.MyServlet</servlet-class> </servlet> 3 <servlet-mapping> <servlet-name>MyServlet</servlet-name> <url-pattern>/Hello</url-pattern> 2 </servlet-mapping> © SUPINFO International University – http://www.supinfo.com
  • 49. Deployment descriptor URL Patterns Match rule URL Pattern URL Pattern form URLs That Would Match Exact /something Any string with “/” below /something /something/ String beginning with “/” Path /something/* /something/else and ending with “/*” /something/index.htm /index.jsp Extension *.jsp String ending with “*.jsp” /something/index.jsp Any URL without better Default / Only “/” matching © SUPINFO International University – http://www.supinfo.com
  • 50. Questions ? © SUPINFO International University – http://www.supinfo.com
  • 51. Servlets THE WEB CONTAINER MODEL ServletContext, scopes, filters… © SUPINFO International University – http://www.supinfo.com
  • 52. The web container model Scopes • Java Web Applications have 3 different scopes – Request representing by ServletRequest – Session representing by HttpSession – Application representing by ServletContext • We have already seen ServletRequest, we’re going to discover the two others… © SUPINFO International University – http://www.supinfo.com
  • 53. The web container model Scopes • Each of them can manage attributes – Object getAttribute(String name) – void setAttribute(String name, Object value) – void removeAttribute(String name) • These functions are useful to forward some values along user navigation, like the user name or the amount of pages visited on a specific day © SUPINFO International University – http://www.supinfo.com
  • 54. The web container model ServletContext • Retrieve it with a ServletConfig – Or an HttpServlet (which implements a ServletConfig, remember ?) • Allows communication between the servlets and the servlet container – Only one instance per Web Application per JVM • Contains useful data as context path, Application Scope attributes, … © SUPINFO International University – http://www.supinfo.com
  • 55. The web container model ServletContext • Add an attribute to the ServletContext – This attribute will be accessible in whole application // ... getServletContext().setAttribute("nbOfConnection”,0); // ... © SUPINFO International University – http://www.supinfo.com
  • 56. The web container model ServletContext • Retrieve an attribute from the ServletContext and update it: // ... ServletContext sc = getServletContext(); Integer nbOfConnection = (Integer) sc.getAttribute("nbOfConnection"); sc.setAttribute("nbOfConnection", ++nbOfConnection); // ... © SUPINFO International University – http://www.supinfo.com
  • 57. The web container model ServletContext • Remove an attribute from the ServletContext: – Trying to retrieve an unknown or unset value returns null // ... getServletContext().removeAttribute("nbOfConnection"); // ... © SUPINFO International University – http://www.supinfo.com
  • 58. The web container model Session • Interface: HttpSession • Retrieve it with an HttpServletRequest – request.getSession(); • Useful methods: – setAttribute(String name, Object value) – getAttribute(String name) – removeAttribute(String name) © SUPINFO International University – http://www.supinfo.com
  • 59. The web container model Session • Retrieve a HttpSession and add an attribute to it : – This attribute will be accessible in whole user session // ... HttpSession session = request.getSession(); Car myCar = new Car(); session.setAttribute("car", myCar); // ... © SUPINFO International University – http://www.supinfo.com
  • 60. The web container model Session • Retrieve an attribute to it: // ... Car aCar = (Car) session.getAttribute("car"); // ... © SUPINFO International University – http://www.supinfo.com
  • 61. The web container model Session • Remove an attribute to it: – Trying to retrieve an unknown or unset value returns null // ... session.removeAttribute("car"); // ... © SUPINFO International University – http://www.supinfo.com
  • 62. The web container model Chaining • From a servlet you can: – include the content of another resource inside the response – forward a request from the servlet to another resource © SUPINFO International University – http://www.supinfo.com
  • 63. The web container model Chaining • You must use a RequestDispatcher – Obtained with the request // Get the dispatcher RequestDispatcher rd = request.getRequestDispatcher("/somewhereElse"); © SUPINFO International University – http://www.supinfo.com
  • 64. The web container model Chaining • Then you can include another servlet: rd.include(request, response); out.println("This print statement will be executed"); • Or forward the request to another servlet: rd.forward(request, response); out.println("This print statement will not be executed"); © SUPINFO International University – http://www.supinfo.com
  • 65. The web container model Chaining – Include MyHttpServlet1 request MyHttpServlet2 service(...) { 2 1 // do something service(...) { rd.include(…); // do sthg else // do something } 3 Client response } 4 © SUPINFO International University – http://www.supinfo.com
  • 66. The web container model Chaining – Forward MyHttpServlet1 request service(...) { // do something 1 2 MyHttpServlet2 rd.forward(…); service(...) { } // do sthg else Client response } 3 © SUPINFO International University – http://www.supinfo.com
  • 67. The web container model Chaining • Use request attributes to pass information between servlets – Servlet 1: // Other stuff Car aCar = new Car("Renault", "Clio"); request.setAttribute("car", aCar); RequestDispatcher rd = request.getRequestDispatcher("/Servlet2"); rd.forward(request, response); © SUPINFO International University – http://www.supinfo.com
  • 68. The web container model Chaining • Retrieve attribute in another servlet: – Servlet 2 mapped to /Servlet2 // Other stuff Car aCar = (Car) request.getAttribute("car"); out.println("My car is a " + car.getBrand()); // Outputs "Renault" © SUPINFO International University – http://www.supinfo.com
  • 69. The web container model Filter • Component which dynamically intercepts requests & responses to use or transform them • Encapsulate recurring tasks in reusable units • Example of functions filters can have : – Authentication - Blocking requests based on user identity – Logging and auditing - Tracking users of a web application. – Data compression - Making downloads smaller. © SUPINFO International University – http://www.supinfo.com
  • 70. The web container model Filter Request LoginServlet Response AddCarServlet Authenticate Audit Filter Filter EditCarServlet LogoutServlet © SUPINFO International University – http://www.supinfo.com
  • 71. The web container model Filter • Create a class implementing the javax.servlet.Filter interface • Define the methods : – init(FilterConfig) – doFilter(ServletResquest, ServletResponse, FilterChain) – destroy() © SUPINFO International University – http://www.supinfo.com
  • 72. The web container model Filter • In the doFilter method – Use the doFilter(…) of the FilterChain to call the next element in the chain – Instructions before this statement will be executed before the next element – Instructions after will be executed after the next element – Don’t call doFilter(…) method of the FilterChain to break the chain © SUPINFO International University – http://www.supinfo.com
  • 73. The web container model Filter Request Client Response Filter Filter Filter Resource Servlet, JSP, HTML, … Container © SUPINFO International University – http://www.supinfo.com
  • 74. The web container model Filter example public final class HitCounterFilter implements Filter { //... public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) { ServletContext sc = filterConfig.getServletContext(); Counter counter = (Counter) sc.getAttribute("hitCounter"); System.out.println("The number of hits is: " + counter.incCounter()); chain.doFilter(request, response); } //... } © SUPINFO International University – http://www.supinfo.com
  • 75. The web container model Filter declaration • Declare your filter in the web.xml file: <filter> <filter-name>MyHitCounterFilter</filter-name> <filter-class> com.supinfo.sun.filters.HitCounterFilter </filter-class> </filter> <filter-mapping> <filter-name>MyHitCounterFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> © SUPINFO International University – http://www.supinfo.com
  • 76. The web container model Cookies • Can be placed in an HttpServletResponse • Can be retrieved in an HttpServletRequest • Constructor : – Cookie(String name, String value) • Methods : – String getName() – String getValue() © SUPINFO International University – http://www.supinfo.com
  • 77. The web container model Cookies example • Add a cookie to a response: // ... Cookie myCookie = new Cookie("MySuperCookie", "This is my cookie :)"); response.addCookie(myCookie); // ... © SUPINFO International University – http://www.supinfo.com
  • 78. The web container model Cookies example • Retrieve cookies from the request: // ... Cookie[] list = request.getCookies(); for(Cookie c : list) { System.out.println("Name: " + c.getName() + " Value: " + c.getValue()); } // ... © SUPINFO International University – http://www.supinfo.com
  • 79. Questions ? © SUPINFO International University – http://www.supinfo.com
  • 80. Servlets WHAT’S NEW IN SERVLET 3.0 ? Annotations, Web fragments, … © SUPINFO International University – http://www.supinfo.com
  • 81. What’s new in Servlet 3.0 ? Introduction • The 10th December 2009, Sun Microsystems releases the version 6 of Java EE • It includes a lot of new JSR like: – EJB 3.1 – JPA 2.0 – … and Servlet 3.0 ! • For more information about JSRs include in Java EE 6: http://en.wikipedia.org/wiki/Java_EE_version_history © SUPINFO International University – http://www.supinfo.com
  • 82. What’s new in Servlet 3.0 ? Configuration through annotations • Annotations are used more and more in Java development : – To map classes with tables in database (JPA) – To define validation rules (Bean Validation) – And now to define Servlets and Filters without declare them into deployment descriptor ! © SUPINFO International University – http://www.supinfo.com
  • 83. What’s new in Servlet 3.0 ? Configuration through annotations • So why not have seen this from the beginning ? – Because Servlet 2.5 is still extremely used – And you can still used deployment descriptor with Servlet 3.0 © SUPINFO International University – http://www.supinfo.com
  • 84. What’s new in Servlet 3.0 ? Servet 3.0 main annotations • @WebServlet : Mark a class as a Servlet (must still extends HttpServlet) • Some attributes of this annotation are : – name (optional) : • The name of the Servlet – urlPatterns : • The URL patterns to which the Servlet applies © SUPINFO International University – http://www.supinfo.com
  • 85. What’s new in Servlet 3.0 ? Servlet 3.0 main annotations • @WebFilter : Mark a class as a Filter • Some attributes of this annotation are : – filterName (optional) : • The name of the Filter – servletNames (optional if urlPatterns) : • The names of the servlets to which the Filter applies – urlPatterns (optional if servletNames) : • The URL patterns to which the Filter applies © SUPINFO International University – http://www.supinfo.com
  • 86. What’s new in Servlet 3.0 ? Examples @WebServlet(urlPatterns="/myservlet") public class SimpleServlet extends HttpServlet { ... } @WebFilter(urlPatterns={"/myfilter","/simplefilter"}) public class SimpleFilter implements Filter { ... } © SUPINFO International University – http://www.supinfo.com
  • 87. What’s new in Servlet 3.0 ? Web Fragments • New system which allow to partition the deployment descriptor – Useful for third party libraries to include a default web configuration • A Web Fragment, as Deployment Descriptor, is an XML file : – Named web-fragment.xml – Placed inside the META-INF folder of the library – With <web-fragment> as root element © SUPINFO International University – http://www.supinfo.com
  • 88. <!-- Example of web-fragment.xml --> Web Fragments Example <web-fragment> <name>MyFragment</name> <listener> <listener-class> com.enterprise.project.module.MyListener </listener-class> </listener> <servlet> <servlet-name>MyServletFragment</servlet-name> <servlet-class> com.enterprise.project.module.MyServlet </servlet-class> </servlet> </web-fragment> © SUPINFO International University – http://www.supinfo.com
  • 89. Questions ? © SUPINFO International University – http://www.supinfo.com
  • 90. Servlets The end Thanks for your attention © SUPINFO International University – http://www.supinfo.com

Editor's Notes

  • #41: Filter classes must stillimplementsjavax.servlet.Filter