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

Viewers also liked (20)

Introduction to java servlet 3.0 api javaone 2008
Introduction to java servlet 3.0 api javaone 2008Introduction to java servlet 3.0 api javaone 2008
Introduction to java servlet 3.0 api javaone 2008
JavaEE Trainers
 
Web Application Deployment
Web Application DeploymentWeb Application Deployment
Web Application Deployment
elliando dias
 
Story of Julia
Story of JuliaStory of Julia
Story of Julia
Akeneo
 
The Patterns to boost your time to market - An introduction to DevOps
The Patterns to boost your time to market - An introduction to DevOpsThe Patterns to boost your time to market - An introduction to DevOps
The Patterns to boost your time to market - An introduction to DevOps
Brice Argenson
 
Docker 1.12 & Swarm Mode [Montreal Docker Meetup Sept. 2016]
Docker 1.12 & Swarm Mode [Montreal Docker Meetup Sept. 2016]Docker 1.12 & Swarm Mode [Montreal Docker Meetup Sept. 2016]
Docker 1.12 & Swarm Mode [Montreal Docker Meetup Sept. 2016]
Brice Argenson
 
Evry`U guide
Evry`U guideEvry`U guide
Evry`U guide
SmaartMobile
 
Serenity walk
Serenity walkSerenity walk
Serenity walk
falfa421
 
English house Tuleneva
English house TulenevaEnglish house Tuleneva
English house Tuleneva
Наталья Осипова
 
Stappenplan+ben+rietdijk+sport
Stappenplan+ben+rietdijk+sportStappenplan+ben+rietdijk+sport
Stappenplan+ben+rietdijk+sport
micd88
 
Lucy and the lost mouse
Lucy and the lost mouseLucy and the lost mouse
Lucy and the lost mouse
adickson2011
 
Resolucio practica5 pqpi2
Resolucio practica5 pqpi2Resolucio practica5 pqpi2
Resolucio practica5 pqpi2
VICENT PITARCH
 
как выучить иностранный язык
как выучить иностранный языккак выучить иностранный язык
как выучить иностранный язык
Наталья Осипова
 
Shopping
ShoppingShopping
Shopping
Наталья Осипова
 
Project "My flat" by Pochkina A. 5 form
Project "My flat" by Pochkina A. 5 formProject "My flat" by Pochkina A. 5 form
Project "My flat" by Pochkina A. 5 form
Наталья Осипова
 
Three sad dogs
Three sad dogsThree sad dogs
Three sad dogs
adickson2011
 
Write quickinc portfoliosamples
Write quickinc portfoliosamplesWrite quickinc portfoliosamples
Write quickinc portfoliosamples
sorenk22
 
Amigos(as))
Amigos(as))Amigos(as))
Amigos(as))
Yu40
 
Biruk.rwandan genocide.p6
Biruk.rwandan genocide.p6Biruk.rwandan genocide.p6
Biruk.rwandan genocide.p6
estee33
 
Tips on How To Apply A Screen Protector In Base
Tips on How To Apply A Screen Protector    In  BaseTips on How To Apply A Screen Protector    In  Base
Tips on How To Apply A Screen Protector In Base
Aashish Kumbhat
 
Introduction to java servlet 3.0 api javaone 2008
Introduction to java servlet 3.0 api javaone 2008Introduction to java servlet 3.0 api javaone 2008
Introduction to java servlet 3.0 api javaone 2008
JavaEE Trainers
 
Web Application Deployment
Web Application DeploymentWeb Application Deployment
Web Application Deployment
elliando dias
 
Story of Julia
Story of JuliaStory of Julia
Story of Julia
Akeneo
 
The Patterns to boost your time to market - An introduction to DevOps
The Patterns to boost your time to market - An introduction to DevOpsThe Patterns to boost your time to market - An introduction to DevOps
The Patterns to boost your time to market - An introduction to DevOps
Brice Argenson
 
Docker 1.12 & Swarm Mode [Montreal Docker Meetup Sept. 2016]
Docker 1.12 & Swarm Mode [Montreal Docker Meetup Sept. 2016]Docker 1.12 & Swarm Mode [Montreal Docker Meetup Sept. 2016]
Docker 1.12 & Swarm Mode [Montreal Docker Meetup Sept. 2016]
Brice Argenson
 
Serenity walk
Serenity walkSerenity walk
Serenity walk
falfa421
 
Stappenplan+ben+rietdijk+sport
Stappenplan+ben+rietdijk+sportStappenplan+ben+rietdijk+sport
Stappenplan+ben+rietdijk+sport
micd88
 
Lucy and the lost mouse
Lucy and the lost mouseLucy and the lost mouse
Lucy and the lost mouse
adickson2011
 
Resolucio practica5 pqpi2
Resolucio practica5 pqpi2Resolucio practica5 pqpi2
Resolucio practica5 pqpi2
VICENT PITARCH
 
как выучить иностранный язык
как выучить иностранный языккак выучить иностранный язык
как выучить иностранный язык
Наталья Осипова
 
Write quickinc portfoliosamples
Write quickinc portfoliosamplesWrite quickinc portfoliosamples
Write quickinc portfoliosamples
sorenk22
 
Amigos(as))
Amigos(as))Amigos(as))
Amigos(as))
Yu40
 
Biruk.rwandan genocide.p6
Biruk.rwandan genocide.p6Biruk.rwandan genocide.p6
Biruk.rwandan genocide.p6
estee33
 
Tips on How To Apply A Screen Protector In Base
Tips on How To Apply A Screen Protector    In  BaseTips on How To Apply A Screen Protector    In  Base
Tips on How To Apply A Screen Protector In Base
Aashish Kumbhat
 

Similar to Java EE - Servlets API (20)

WEB TECHNOLOGY Unit-3.pptx
WEB TECHNOLOGY Unit-3.pptxWEB TECHNOLOGY Unit-3.pptx
WEB TECHNOLOGY Unit-3.pptx
karthiksmart21
 
servlets sessions and cookies, jdbc connectivity
servlets sessions and cookies, jdbc connectivityservlets sessions and cookies, jdbc connectivity
servlets sessions and cookies, jdbc connectivity
snehalatha790700
 
Java EE 01-Servlets and Containers
Java EE 01-Servlets and ContainersJava EE 01-Servlets and Containers
Java EE 01-Servlets and Containers
Fernando Gil
 
SERVER SIDE PROGRAMMING
SERVER SIDE PROGRAMMINGSERVER SIDE PROGRAMMING
SERVER SIDE PROGRAMMING
Prabu U
 
SERVLETS (2).pptxintroduction to servlet with all servlets
SERVLETS (2).pptxintroduction to servlet with all servletsSERVLETS (2).pptxintroduction to servlet with all servlets
SERVLETS (2).pptxintroduction to servlet with all servlets
RadhikaP41
 
JAVA Servlets
JAVA ServletsJAVA Servlets
JAVA Servlets
deepak kumar
 
Wt unit 3
Wt unit 3 Wt unit 3
Wt unit 3
team11vgnt
 
SERVLET in web technolgy engineering.pptx
SERVLET in web technolgy engineering.pptxSERVLET in web technolgy engineering.pptx
SERVLET in web technolgy engineering.pptx
ARUNKUMARM230658
 
Bt0083 server side programing
Bt0083 server side programing Bt0083 server side programing
Bt0083 server side programing
Techglyphs
 
J2ee servlet
J2ee servletJ2ee servlet
J2ee servlet
vinoth ponnurangam
 
Java Servlet
Java ServletJava Servlet
Java Servlet
Yoga Raja
 
Weblogic
WeblogicWeblogic
Weblogic
Raju Sagi
 
BITM3730Week12.pptx
BITM3730Week12.pptxBITM3730Week12.pptx
BITM3730Week12.pptx
MattMarino13
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servlet
ssbd6985
 
JAVA SERVLETS acts as a middle layer between a request coming from a web brow...
JAVA SERVLETS acts as a middle layer between a request coming from a web brow...JAVA SERVLETS acts as a middle layer between a request coming from a web brow...
JAVA SERVLETS acts as a middle layer between a request coming from a web brow...
ssuser4f7d71
 
Java servlets
Java servletsJava servlets
Java servlets
Mukesh Tekwani
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jsp
Jafar Nesargi
 
Enterprise java unit-1_chapter-3
Enterprise java unit-1_chapter-3Enterprise java unit-1_chapter-3
Enterprise java unit-1_chapter-3
sandeep54552
 
Servlets-UNIT3and introduction to servlet
Servlets-UNIT3and introduction to servletServlets-UNIT3and introduction to servlet
Servlets-UNIT3and introduction to servlet
RadhikaP41
 
ADP - Chapter 2 Exploring the java Servlet Technology
ADP - Chapter 2 Exploring the java Servlet TechnologyADP - Chapter 2 Exploring the java Servlet Technology
ADP - Chapter 2 Exploring the java Servlet Technology
Riza Nurman
 
WEB TECHNOLOGY Unit-3.pptx
WEB TECHNOLOGY Unit-3.pptxWEB TECHNOLOGY Unit-3.pptx
WEB TECHNOLOGY Unit-3.pptx
karthiksmart21
 
servlets sessions and cookies, jdbc connectivity
servlets sessions and cookies, jdbc connectivityservlets sessions and cookies, jdbc connectivity
servlets sessions and cookies, jdbc connectivity
snehalatha790700
 
Java EE 01-Servlets and Containers
Java EE 01-Servlets and ContainersJava EE 01-Servlets and Containers
Java EE 01-Servlets and Containers
Fernando Gil
 
SERVER SIDE PROGRAMMING
SERVER SIDE PROGRAMMINGSERVER SIDE PROGRAMMING
SERVER SIDE PROGRAMMING
Prabu U
 
SERVLETS (2).pptxintroduction to servlet with all servlets
SERVLETS (2).pptxintroduction to servlet with all servletsSERVLETS (2).pptxintroduction to servlet with all servlets
SERVLETS (2).pptxintroduction to servlet with all servlets
RadhikaP41
 
SERVLET in web technolgy engineering.pptx
SERVLET in web technolgy engineering.pptxSERVLET in web technolgy engineering.pptx
SERVLET in web technolgy engineering.pptx
ARUNKUMARM230658
 
Bt0083 server side programing
Bt0083 server side programing Bt0083 server side programing
Bt0083 server side programing
Techglyphs
 
Java Servlet
Java ServletJava Servlet
Java Servlet
Yoga Raja
 
BITM3730Week12.pptx
BITM3730Week12.pptxBITM3730Week12.pptx
BITM3730Week12.pptx
MattMarino13
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servlet
ssbd6985
 
JAVA SERVLETS acts as a middle layer between a request coming from a web brow...
JAVA SERVLETS acts as a middle layer between a request coming from a web brow...JAVA SERVLETS acts as a middle layer between a request coming from a web brow...
JAVA SERVLETS acts as a middle layer between a request coming from a web brow...
ssuser4f7d71
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jsp
Jafar Nesargi
 
Enterprise java unit-1_chapter-3
Enterprise java unit-1_chapter-3Enterprise java unit-1_chapter-3
Enterprise java unit-1_chapter-3
sandeep54552
 
Servlets-UNIT3and introduction to servlet
Servlets-UNIT3and introduction to servletServlets-UNIT3and introduction to servlet
Servlets-UNIT3and introduction to servlet
RadhikaP41
 
ADP - Chapter 2 Exploring the java Servlet Technology
ADP - Chapter 2 Exploring the java Servlet TechnologyADP - Chapter 2 Exploring the java Servlet Technology
ADP - Chapter 2 Exploring the java Servlet Technology
Riza Nurman
 
Ad

More from Brice Argenson (9)

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

Recently uploaded (20)

How to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptxHow to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptx
Version 1 Analytics
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training RoadblocksDown the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Infrassist Technologies Pvt. Ltd.
 
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Impelsys Inc.
 
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Safe Software
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean accountYour startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.
hok12341073
 
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and ImplementationAI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
Christine Shepherd
 
Oracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI ProfessionalOracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI Professional
VICTOR MAESTRE RAMIREZ
 
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
Edge AI and Vision Alliance
 
If You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FMEIf You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FME
Safe Software
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy SurveyTrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc
 
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely
 
PyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent IntegrationPyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent Integration
barqawicloud
 
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
Domino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use CasesDomino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use Cases
panagenda
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdfvertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
Oracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI FoundationsOracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI Foundations
VICTOR MAESTRE RAMIREZ
 
Ben Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding WorldBen Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding World
AWS Chicago
 
How to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptxHow to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptx
Version 1 Analytics
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training RoadblocksDown the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Infrassist Technologies Pvt. Ltd.
 
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Impelsys Inc.
 
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Safe Software
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean accountYour startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.
hok12341073
 
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and ImplementationAI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
Christine Shepherd
 
Oracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI ProfessionalOracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI Professional
VICTOR MAESTRE RAMIREZ
 
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
Edge AI and Vision Alliance
 
If You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FMEIf You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FME
Safe Software
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy SurveyTrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc
 
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely
 
PyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent IntegrationPyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent Integration
barqawicloud
 
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
Domino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use CasesDomino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use Cases
panagenda
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdfvertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
Oracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI FoundationsOracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI Foundations
VICTOR MAESTRE RAMIREZ
 
Ben Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding WorldBen Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding World
AWS Chicago
 

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