SlideShare a Scribd company logo
1 of 54
Java™ Servlet 3.0:
Empowering Your Web
Applications With Async,
Extensibility and More

Rajiv Mordani, Jan Luehe
Sun Microsystems
Greg Wilkins
Webtide / Jetty
Agenda
●   Overview
●   Ease of Development
●   Dynamic registration of Servlets and Filters
●   Pluggability
●   Asynchronous support
●   Security enhancements
●   Miscellaneous


                                                   2
Overview
●   Java Servlet 3.0 API – JSR 315
●   About 20 members in the expert group
     ●   Good mix of representation from major Java EE
         vendors, web container vendors and individual
         web framework authors
●   Main areas of focus
     ●   Ease of Development
     ●   Pluggability
     ●   Asynchronous support
     ●   Security
                                                         3
Status
●   Specification in Proposed Final Draft
●   Final release aligned with Java EE 6




                                            4
Agenda
●   Overview
●   Ease of Development
●   Dynamic registration of Servlets and Filters
●   Pluggability
●   Asynchronous support
●   Security enhancements
●   Miscellaneous


                                                   5
Ease of Development (EoD)
●   Focus on Ease of Development (EoD) in the
    Servlet 3.0 API
●   Enhance API to use the new language features
    introduced since J2SE 5.0
●   Annotations for declarative style of programming
     ●   No web.xml needed
●   Generics for type safety in the API without
    breaking backwards compatibility
●   Better defaults and convention over configuration

                                                        6
Ease of Development
 Use of Annotations
● Annotations to declare Servlets, Filters, Listeners

  and security constraints
   ● @WebServlet – Define a Servlet


   ● @WebFilter – Define a Filter


   ● @WebListener – Define a Listener


   ● @WebInitParam – Define init params


   ● @MultipartConfig – Define fileupload

      properties
● Can use web.xml to override values specified in

  the annotations
                                                        7
Ease of Development
Use of Annotations (contd)
●   @WebServlet for defining a Servlet
     ●   The annotation MUST have at a minimum the
          URL pattern for the Servlet
     ●   All other fields optional with reasonable defaults
     ●   For example, the default name of the Servlet is
          the fully qualified class name
     ●   Class MUST still extend HttpServlet
          ●   Method contracts for doGet, doPost
               inherited from abstract class


                                                              8
Servlet 2.5 example             web.xml
                                  (intentionally left
public class SimpleSample         unreadable)
extends HttpServlet {           <web-app>


                                  <servlet>

    public void doGet                 <servlet-name>              MyServlet

    (HttpServletRequest req,          </servlet-name>


     HttpServletResponse res)         <servlet-class>


    {                                 samples.SimpleSample


                                      </servlet-class>


                                  </servlet>




    }
                                  <servlet-mapping>


                                      <servlet-name>



}                                      MyServlet


                                      </servlet-name>


                                      <url-pattern>


                                       /MyApp


                                      </url-pattern>


                                  </servlet-mapping>


                                ...

                                                                              9
                                </web-app>
Servlet 3.0 example
@WebServlet(“/foo”)
public class SimpleSample extends
HttpServlet
{
    public void doGet(HttpServletRequest
             req,HttpServletResponse res)
    {


    }
}
                                            10
Servlet 3.0 example
@WebServlet(urlPatterns=“/foo”,
  name=”MyServlet”, asyncSupported=true)
public class SimpleSample extends
HttpServlet
{
    public void doGet(HttpServletRequest
             req,HttpServletResponse res)
    {


    }
}
                                            11
Agenda
●   Overview
●   Ease of Development
●   Dynamic registration of Servlets and Filters
●   Pluggability
●   Asynchronous support
●   Security enhancements
●   Miscellaneous


                                                   12
Dynamic registration of Servlets and
Filters
Register
● Performed during ServletContext initialization


● ServletContext#add[Servlet|Filter]


  ●   Overloaded versions take [Servlet|Filter] name
      and
       ●   Fully qualified [Servlet|Filter] class name OR
       ●   Class<? extends [Servlet|Filter]> OR
       ●   [Servlet|Filter] instance
  ●   Use returned Registration handle to configure
      all aspects of [Servlet|Filter]


                                                            13
Dynamic registration of Servlets and
Filters
Create and Register
●   ServletContext#create[Servlet|Filter]
    ●   Takes Class<? extends [Servlet|Filter]>
        argument
    ●   Container responsible for instantiating the
        [Servlet |Filter]
    ●   Supports resource injection by container
    ●   Returned [Servlet|Filter] instance may be
        fully customized before it is registered via the
        ServletContext#add[Servlet|Filter]
        methods

                                                           14
Dynamic registration of Servlets and
Filters
Lookup
●   ServletContext#get[Servlet|
    Filter]Registration
    ●   Takes [Servlet|Filter] name as argument
    ●   Returned Registration handle provides subset
        of configuration methods
         ●   May only be used to add initialization parameters and
             mappings
         ●   Any conflicts returned as java.util.Set




                                                                     15
Dynamic registration of Servlets/Filters
Register Example
ServletRegistration.Dynamic dynamic =
    servletContext.addServlet(
       "DynamicServlet",
 "com.mycom.MyServlet");
dynamic.addMapping("/dynamicServlet");
dynamic.setAsyncSupported(true);




                                           16
Dynamic registration of Servlets/Filters
Lookup Example
ServletRegistration declared =

 servletContext.getServletRegistration("Declar
 edServlet");
declared.addMapping("/declaredServlet");
declared.setInitParameter("param", "value");




                                               17
Agenda
●   Overview
●   Ease of Development
●   Dynamic registration of Servlets and Filters
●   Pluggability
●   Asynchronous support
●   Security enhancements
●   Miscellaneous


                                                   18
Pluggability
●   Enable use of libraries and framework without
    boiler plate configuration in deployment
    descriptors
     ●   Put the burden on the framework developer
●   Modularize web.xml to allow frameworks to be
    self-contained within their own JAR file
●   Programmatic configuration APIs
●   Use of annotations


                                                     19
Pluggability
Motivation for web.xml modularization
●   Use of framework requires (possibly complex)
    configuration in web.xml
●   For example
     ●   Declare a controller Servlet
     ●   Logging and security Filters
     ●   Declare Listeners to perform actions at various
         points in the lifecycle of the application
●   Can get complex as dependencies increase
●   Frameworks also need to document all the
    configuration that needs to be done
                                                           20
Pluggability
web-fragment.xml
●   web-fragment.xml is descriptor for framework /
    library
●   Included in META-INF directory
●   Container responsible for discovering fragments and
    assembling the effective deployment descriptor
●   Almost identical to web.xml
     ●   Ordering related elements different
●   Only JAR files in WEB-INF/lib considered as
     fragments

                                                     21
Pluggability
web-fragment.xml example
<web-fragment>
 <servlet>

   <servlet-name>welcome</servlet-name>

   <servlet-class>com.mycom.WelcomeServlet</servlet-class>

 </servlet>

 <servlet-mapping>

   <servlet-name>welcome</servlet-name>

   <url-pattern>/Welcome</url-pattern>

 </servlet-mapping>

 ...

</web-fragment>



                                                             22
Pluggability
 Ordering
● Compatible with JavaServer™ Faces


● Fragments identified by <name>


●    web.xml may declare absolute ordering of
    fragments via <absolute-ordering>
●   Fragments may declare ordering preferences
    relative to other fragments via <ordering> with
    nested <before> and <after>
     ●   Ignored if <absolute-ordering> specified
●   Special <others/> element moves fragment to
    beginning or end of list of sorted fragments
                                                      23
Pluggability
Resource sharing
●   Static and JavaServer™ Pages (JSP) resources
    no longer confined to web application's document
    root
●   May be placed inside WEB-INF/lib/[*.jar]/
    META-INF/resources
●   Container must honor this new location when
    processing HTTP requests and calls to
    ServletContext#getResource[AsStream]
●   Resources in document root take precedence
    over those in bundled JAR files
                                                       24
Pluggability
Resource sharing: Example
mywebapp.war packaging:
 /index.jsp
 /WEB-INF/lib/shared.jar!/META-
  INF/resources/shared.jsp
Request for:
http://localhost:8080/mywebapp/shared.jsp
will be served from:
  /path/to/mywebapp/WEB-
 INF/lib/shared.jar!/META-
 INF/resources/shared.jsp
                                       25
Pluggability
Shared libraries
●   Support plugging in of container installed JAR
    files
     ●   Examples: JSF, JAX-WS, Spring
●   Libraries may provide implementation of
    ServletContainerInitializer
●   Looked up via the JAR Services API in JDK 6
●   Invoked before any Listeners during the
    initialization of the application


                                                     26
Pluggability
Shared libraries (contd)

●   ServletContainerInitializer expresses
    interest in Classes via @HandlesTypes
●   Container discovers classes that match
     @HandlesTypes and passes them to
     ServletContainerInitializer
●   ServletContainerInitializer inspects
    passed in Classes and may register Servlets and
    Filters based on them


                                                      27
Pluggability
ServletContainerInitializer example
@HandlesTypes(WebService.class)
public   class  JAXWSInitializer      implements
 ServletContainerInitializer {
    public void onStartup(Set<Class<?>> c,
                          ServletContext ctx)
    {
        ctx.addServlet(“JAXWSServlet”,
                 “com.sun.jaxws.JAXWSServlet”);

    }
}
                                                   28
Agenda
●   Overview
●   Ease of Development
●   Dynamic registration of Servlets and Filters
●   Pluggability
●   Asynchronous support
●   Security enhancements
●   Miscellaneous


                                                   29
Why Asynchronous Servlets?
●   Not for Async IO!
     ●   Requests mostly small (single packet)
     ●   Hard to asynchronously produce large responses
     ●   Async IO support waiting for NIO2 (Servlet 3.1?)

●   Async Servlets are for:
     ●   Waiting for resources (eg JDBC connection)
     ●   Waiting for events (eg Chat)
     ●   Waiting for responses (eg web services, QoS)

                                                            30
Blocking waiting consumes resources
●   Web Application using remote web services
     ●   Handling 1000 requests / sec
     ●   50% requests call remote web service
     ●   500 threads in container thread pool

●   If remote web service is slow (1000ms)
     ●   Thread starvation in 1 second!
     ●   50% of requests use all 500 threads


                                                31
Waiting for Web Services
      Blocking                 Asynchronous



        Thread
        blocked




                           WS request
                            In parallel

                                              32
Asynchronous API
 ServletRequest
● ServletRequest#isAsyncSupported()


     ●   True if ALL [Filter|Servlet]s support async in
          ●   the Filter chain
          ●   the RequestDispatch chain
●   Configured in
     ●   web.xml
          ●   <async-supported>true</async-supported>
     ●   With annotation
          ●   @WebServlet(asyncSupported=true)
     ●   Programmatic
          ●   registration.setAsyncSupported(boolean)
                                                          33
Asynchronous API
ServletRequest
● AsyncContext

  ServletRequest#startAsync()
    ●   Called by [Filter|Servlet]
    ●   Response is NOT commited on return of:
         ●   Servlet.service(request,response)
         ●   Filter chain
●   AsyncContext
    ServletRequest#startAsync
                 (ServletRequest req,
                  ServletResponse res)
    ●   Variation that preserves wrappers
                                                 34
Asynchronous API
 AsyncContext
● AsyncContext#dispatch()


     ●   Called by your asynchronous handler
     ●   Schedule async dispatch:
           DispatcherType.ASYNC
     ●   Response generated by [Filter|Servlet] using:
          ●   container thread pool
          ●   JSP, JSF or other frameworks usable
          ●   JNDI, JTA, EJBs usable

●   AsyncContext#dispatch(String path)
     ●   Variation to async dispatch to specific Servlet
                                                           35
Asynchronous API
AsyncContext
●   AsyncContext#complete()
    ●   Called by your asynchronous handler
    ●   Response has been generated asynchronously
         ●   without Servlet features, or
         ●   with AsyncContext#start(Runnable r)
              ●   for JNDI, classloader




                                                     36
Asynchronous Web Service

            Server                          Webapp



                                 doGet()

                     s t a rtA s y n c ()            WS call




                     dis pa t c h ()
                                doGet()




                                                               37
Multiple Usage Styles
●   startAsync()          …      dispatch()
    ●   Retry request after async wait
    ●   Filters re-applied if on DispatcherType.ASYNC

●   startAsync()          …      dispatch(path)
    ●   Use specific Servlet handling after async wait

●   startAsync()          …      complete()
    ●   Generate response asynchronously

                                                         38
Multiple Usage Styles
●   startAsync(req,res) … dispatch()
    ●   Retry request after async wait
    ●   Wrappers are kept
    ●   RequestDispatcher#forward target used

●   startAsync(req,res) … dispatch(path)
    ●   Specific Servlet handling after async wait

●   startAsync(req,res) … complete()
    ●   Generate wrapped response asynchronously

                                                     39
Asynchronous API Details
●   Timeouts
     ●   ServletRequest#setAsyncTimeout(long ms)
     ●   By default error dispatch on timeout

●   Listeners
     ●   AsyncListener#OnTimeout
     ●   AsyncListener#OnComplete




                                                   40
Demonstration
Asynchronous eBay Web Service
>   EoD packaging
     ●   META-INF
          ●   web-fragment.xml
          ●   Resources/*

>   Glassfish Container
     ●   Async Serlvet

>   Jetty HTTP Client
     ●   Async Client
                                 41
Agenda
●   Overview
●   Ease of Development
●   Dynamic registration of Servlets and Filters
●   Pluggability
●   Asynchronous support
●   Security enhancements
●   Miscellaneous


                                                   42
Security
Security constraints via common annotations
●   Support for common annotations
     ●   @RolesAllowed -> auth-constraint with roles
     ●   @DenyAll -> Empty auth-constraint
     ●   @PermitAll -> No auth-constraint
     ●   @TransportProtected -> user-data-constraint
●   Annotations enforced on javax.http.Servlet
     class and doXXX methods of HttpServlet
●   Method-targeted annotations take precedence over
     class-targeted annotations

                                                       43
Security
Security constraints via common annotations (contd)
●   Security constraints in web.xml override
    annotations, metdata-complete disables
    annotations
●   web-resource-collection enhanced with http-
    method-omission to
     ●   Allow constraints to be specified on non-
          enumerable HTTP method subsets (i.e., all
          other methods)



                                                      44
Security
Programmatic container authentication and logout
●   HttpServletRequest#login(String username,
    String password)
    ●   Replacement for FBL
    ●   Application supervises credential collection
●   HttpServletRequest#authenticate(HttpServl
    etResponse)
    ●   Application initiates container mediated
         authentication from a resource that is not
         covered by any authentication constraints
    ●   Application decides when authentication must
         occur
                                                       45
Security
Programmatic container authentication and logout
(contd)
●   HttpServletRequest#logout
●   Integration of additional container authentication
    modules via Servlet Profile of JSR 196
    recommended




                                                         46
Agenda
●   Overview
●   Ease of Development
●   Dynamic registration of Servlets and Filters
●   Pluggability
●   Asynchronous support
●   Security enhancements
●   Miscellaneous


                                                   47
Miscellaneous Features / APIs
●   Session tracking cookie configuration
     ●   Via web.xml
     ●   Programmatic via
         javax.servlet.SessionCookieConfig
●   Support for HttpOnly cookie attribute
     ●   Example:
         servletContext.getSessionCookieConfig
         ().setHttpOnly(true)
●   Default error page

                                                 48
Miscellaneous Features / APIs (contd)
ServletRequest#getServletContext
ServletRequest#getDispatcherType
Servlet[Request|
  Response]Wrapper#isWrapperFor
HttpServletResponse#getStatus
HttpServletResponse#getHeader
HttpServletResponse#getHeaders
HttpServletResponse#getHeaderNames


                                        49
Miscellaneous Features / APIs (contd)
File upload APIs
ServletRequest#getParts
ServletRequest#getPart
@MultipartConfig
Changes to web.xml




                                        50
Summary
●   Major revision since Servlet 2.4
●   Comprehensive set of new features enable
    modern style of web applications and greatly
    increases developer productivity
●   Simplifies assembly of large applications from
    reusable components




                                                     51
GlassFish Community
Open Source and Enterprise Ready
●   GlassFish V3 Preview Available now!
        ●   Java EE 6 reference implementation                 • 24x7 Enterprise and Mission
        ●   Modular OSGi architecture – easy to develop & deploy Critical Support
        ●   Runs in-process and easy to extend                      •sun.com/glassfish
        ●   Support for Ruby-on-Rails, Groovy and Grails,
            Python and Django                                  • Tools Integration
●   GlassFish V2 – Production Ready                               •NetBeans and Eclipse
    ●   Best price/performance open source App server with
        Clustering, High Availability, Load Balancing                 glassfish.org
    ●   Secure, Reliable, Transactional, .NET-interop Web svcs
    ●   Support for Ajax and Comet
●   GlassFish ESB
    ●   SOA and Business Integration platform
●   GlassFish Communications App Server
    ●   SIP servlet technology for converged services


                Always free to download, deploy and distribute
                                                                                               52
Webtide & Jetty
>   Status update
>   http://eclipse.org/jetty




                               53
Rajiv Mordani
rajiv.mordani@sun.com
Jan Luehe
jan.luehe@sun.com
Greg Wilkins
gregw@webtide.com

More Related Content

What's hot

Advanced liferay architecture clustering and high availability
Advanced liferay architecture clustering and high availabilityAdvanced liferay architecture clustering and high availability
Advanced liferay architecture clustering and high availability
Bordin Kijsirijareonchai
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
vamsi krishna
 
Apache Aries Overview
Apache Aries   OverviewApache Aries   Overview
Apache Aries Overview
Ian Robinson
 
Javax.servlet,http packages
Javax.servlet,http packagesJavax.servlet,http packages
Javax.servlet,http packages
vamsi krishna
 

What's hot (20)

Advanced liferay architecture clustering and high availability
Advanced liferay architecture clustering and high availabilityAdvanced liferay architecture clustering and high availability
Advanced liferay architecture clustering and high availability
 
Weblogic Administration Managed Server migration
Weblogic Administration Managed Server migrationWeblogic Administration Managed Server migration
Weblogic Administration Managed Server migration
 
weblogic perfomence tuning
weblogic perfomence tuningweblogic perfomence tuning
weblogic perfomence tuning
 
Spring 4 final xtr_presentation
Spring 4 final xtr_presentationSpring 4 final xtr_presentation
Spring 4 final xtr_presentation
 
Apache Commons Pool and DBCP - Version 2 Update
Apache Commons Pool and DBCP - Version 2 UpdateApache Commons Pool and DBCP - Version 2 Update
Apache Commons Pool and DBCP - Version 2 Update
 
Servlet
Servlet Servlet
Servlet
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
 
Servlets
ServletsServlets
Servlets
 
Apache Aries Overview
Apache Aries   OverviewApache Aries   Overview
Apache Aries Overview
 
Architecting Large Enterprise Java Projects
Architecting Large Enterprise Java ProjectsArchitecting Large Enterprise Java Projects
Architecting Large Enterprise Java Projects
 
Arun Gupta: London Java Community: Java EE 6 and GlassFish 3
Arun Gupta: London Java Community: Java EE 6 and GlassFish 3 Arun Gupta: London Java Community: Java EE 6 and GlassFish 3
Arun Gupta: London Java Community: Java EE 6 and GlassFish 3
 
Lecture 2: Servlets
Lecture 2:  ServletsLecture 2:  Servlets
Lecture 2: Servlets
 
Lecture 3: Servlets - Session Management
Lecture 3:  Servlets - Session ManagementLecture 3:  Servlets - Session Management
Lecture 3: Servlets - Session Management
 
JAVA Servlets
JAVA ServletsJAVA Servlets
JAVA Servlets
 
Java EE 6 & GlassFish = Less Code + More Power at CEJUG
Java EE 6 & GlassFish = Less Code + More Power at CEJUGJava EE 6 & GlassFish = Less Code + More Power at CEJUG
Java EE 6 & GlassFish = Less Code + More Power at CEJUG
 
Javax.servlet,http packages
Javax.servlet,http packagesJavax.servlet,http packages
Javax.servlet,http packages
 
Servlets
ServletsServlets
Servlets
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Weblogic application server
Weblogic application serverWeblogic application server
Weblogic application server
 
Cis 274 intro
Cis 274   introCis 274   intro
Cis 274 intro
 

Similar to Introduction to java servlet 3.0 api javaone 2009

Java EE 6 - Deep Dive - Indic Threads, Pune - 2010
Java EE 6 - Deep Dive - Indic Threads, Pune - 2010Java EE 6 - Deep Dive - Indic Threads, Pune - 2010
Java EE 6 - Deep Dive - Indic Threads, Pune - 2010
Jagadish Prasath
 
Java EE 6 = Less Code + More Power (Tutorial) [5th IndicThreads Conference O...
Java EE 6 = Less Code + More Power (Tutorial)  [5th IndicThreads Conference O...Java EE 6 = Less Code + More Power (Tutorial)  [5th IndicThreads Conference O...
Java EE 6 = Less Code + More Power (Tutorial) [5th IndicThreads Conference O...
IndicThreads
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jsp
Jafar Nesargi
 
Jsp and Servlets
Jsp and ServletsJsp and Servlets
Jsp and Servlets
Raghu nath
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
Nitin Pai
 

Similar to Introduction to java servlet 3.0 api javaone 2009 (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
 
Java servlet technology
Java servlet technologyJava servlet technology
Java servlet technology
 
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
 
Java EE 6 - Deep Dive - Indic Threads, Pune - 2010
Java EE 6 - Deep Dive - Indic Threads, Pune - 2010Java EE 6 - Deep Dive - Indic Threads, Pune - 2010
Java EE 6 - Deep Dive - Indic Threads, Pune - 2010
 
Java EE 6 = Less Code + More Power (Tutorial) [5th IndicThreads Conference O...
Java EE 6 = Less Code + More Power (Tutorial)  [5th IndicThreads Conference O...Java EE 6 = Less Code + More Power (Tutorial)  [5th IndicThreads Conference O...
Java EE 6 = Less Code + More Power (Tutorial) [5th IndicThreads Conference O...
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 5...
 Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 5... Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 5...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 5...
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jsp
 
Java Servlet
Java ServletJava Servlet
Java Servlet
 
Servlet30 20081218
Servlet30 20081218Servlet30 20081218
Servlet30 20081218
 
Wt unit 3
Wt unit 3 Wt unit 3
Wt unit 3
 
Spring Portlet MVC
Spring Portlet MVCSpring Portlet MVC
Spring Portlet MVC
 
SERVER SIDE PROGRAMMING
SERVER SIDE PROGRAMMINGSERVER SIDE PROGRAMMING
SERVER SIDE PROGRAMMING
 
JavaEE6 my way
JavaEE6 my wayJavaEE6 my way
JavaEE6 my way
 
Jsp and Servlets
Jsp and ServletsJsp and Servlets
Jsp and Servlets
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
JEE Course - The Web Tier
JEE Course - The Web TierJEE Course - The Web Tier
JEE Course - The Web Tier
 
Boston 2011 OTN Developer Days - Java EE 6
Boston 2011 OTN Developer Days - Java EE 6Boston 2011 OTN Developer Days - Java EE 6
Boston 2011 OTN Developer Days - Java EE 6
 
Struts Interceptors
Struts InterceptorsStruts Interceptors
Struts Interceptors
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servlet
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 

More from JavaEE Trainers (9)

Introduction tomcat7 servlet3
Introduction tomcat7 servlet3Introduction tomcat7 servlet3
Introduction tomcat7 servlet3
 
Servlet/JSP course chapter 2: Introduction to JavaServer Pages (JSP)
Servlet/JSP course chapter 2: Introduction to JavaServer Pages (JSP)Servlet/JSP course chapter 2: Introduction to JavaServer Pages (JSP)
Servlet/JSP course chapter 2: Introduction to JavaServer Pages (JSP)
 
Servlet/JSP course chapter 1: Introduction to servlets
Servlet/JSP course chapter 1: Introduction to servletsServlet/JSP course chapter 1: Introduction to servlets
Servlet/JSP course chapter 1: Introduction to servlets
 
Introduction to the Servlet / JSP course
Introduction to the Servlet / JSP course Introduction to the Servlet / JSP course
Introduction to the Servlet / JSP course
 
Jsp quick reference card
Jsp quick reference cardJsp quick reference card
Jsp quick reference card
 
jsp, javaserver pages, Card20
jsp, javaserver pages, Card20jsp, javaserver pages, Card20
jsp, javaserver pages, Card20
 
Struts2 course chapter 2: installation and configuration
Struts2 course chapter 2: installation and configurationStruts2 course chapter 2: installation and configuration
Struts2 course chapter 2: installation and configuration
 
Struts2 course chapter 1: Evolution of Web Applications
Struts2 course chapter 1: Evolution of Web ApplicationsStruts2 course chapter 1: Evolution of Web Applications
Struts2 course chapter 1: Evolution of Web Applications
 
Struts2 Course: Introduction
Struts2 Course: IntroductionStruts2 Course: Introduction
Struts2 Course: Introduction
 

Recently uploaded

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 

Recently uploaded (20)

Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 

Introduction to java servlet 3.0 api javaone 2009

  • 1. Java™ Servlet 3.0: Empowering Your Web Applications With Async, Extensibility and More Rajiv Mordani, Jan Luehe Sun Microsystems Greg Wilkins Webtide / Jetty
  • 2. Agenda ● Overview ● Ease of Development ● Dynamic registration of Servlets and Filters ● Pluggability ● Asynchronous support ● Security enhancements ● Miscellaneous 2
  • 3. Overview ● Java Servlet 3.0 API – JSR 315 ● About 20 members in the expert group ● Good mix of representation from major Java EE vendors, web container vendors and individual web framework authors ● Main areas of focus ● Ease of Development ● Pluggability ● Asynchronous support ● Security 3
  • 4. Status ● Specification in Proposed Final Draft ● Final release aligned with Java EE 6 4
  • 5. Agenda ● Overview ● Ease of Development ● Dynamic registration of Servlets and Filters ● Pluggability ● Asynchronous support ● Security enhancements ● Miscellaneous 5
  • 6. Ease of Development (EoD) ● Focus on Ease of Development (EoD) in the Servlet 3.0 API ● Enhance API to use the new language features introduced since J2SE 5.0 ● Annotations for declarative style of programming ● No web.xml needed ● Generics for type safety in the API without breaking backwards compatibility ● Better defaults and convention over configuration 6
  • 7. Ease of Development Use of Annotations ● Annotations to declare Servlets, Filters, Listeners and security constraints ● @WebServlet – Define a Servlet ● @WebFilter – Define a Filter ● @WebListener – Define a Listener ● @WebInitParam – Define init params ● @MultipartConfig – Define fileupload properties ● Can use web.xml to override values specified in the annotations 7
  • 8. Ease of Development Use of Annotations (contd) ● @WebServlet for defining a Servlet ● The annotation MUST have at a minimum the URL pattern for the Servlet ● All other fields optional with reasonable defaults ● For example, the default name of the Servlet is the fully qualified class name ● Class MUST still extend HttpServlet ● Method contracts for doGet, doPost inherited from abstract class 8
  • 9. Servlet 2.5 example web.xml (intentionally left public class SimpleSample unreadable) extends HttpServlet { <web-app> <servlet> public void doGet <servlet-name>      MyServlet     (HttpServletRequest req, </servlet-name>      HttpServletResponse res) <servlet-class>     { samples.SimpleSample </servlet-class> </servlet> } <servlet-mapping> <servlet-name> } MyServlet </servlet-name> <url-pattern> /MyApp </url-pattern> </servlet-mapping> ... 9 </web-app>
  • 10. Servlet 3.0 example @WebServlet(“/foo”) public class SimpleSample extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res) { } } 10
  • 11. Servlet 3.0 example @WebServlet(urlPatterns=“/foo”, name=”MyServlet”, asyncSupported=true) public class SimpleSample extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res) { } } 11
  • 12. Agenda ● Overview ● Ease of Development ● Dynamic registration of Servlets and Filters ● Pluggability ● Asynchronous support ● Security enhancements ● Miscellaneous 12
  • 13. Dynamic registration of Servlets and Filters Register ● Performed during ServletContext initialization ● ServletContext#add[Servlet|Filter] ● Overloaded versions take [Servlet|Filter] name and ● Fully qualified [Servlet|Filter] class name OR ● Class<? extends [Servlet|Filter]> OR ● [Servlet|Filter] instance ● Use returned Registration handle to configure all aspects of [Servlet|Filter] 13
  • 14. Dynamic registration of Servlets and Filters Create and Register ● ServletContext#create[Servlet|Filter] ● Takes Class<? extends [Servlet|Filter]> argument ● Container responsible for instantiating the [Servlet |Filter] ● Supports resource injection by container ● Returned [Servlet|Filter] instance may be fully customized before it is registered via the ServletContext#add[Servlet|Filter] methods 14
  • 15. Dynamic registration of Servlets and Filters Lookup ● ServletContext#get[Servlet| Filter]Registration ● Takes [Servlet|Filter] name as argument ● Returned Registration handle provides subset of configuration methods ● May only be used to add initialization parameters and mappings ● Any conflicts returned as java.util.Set 15
  • 16. Dynamic registration of Servlets/Filters Register Example ServletRegistration.Dynamic dynamic = servletContext.addServlet( "DynamicServlet", "com.mycom.MyServlet"); dynamic.addMapping("/dynamicServlet"); dynamic.setAsyncSupported(true); 16
  • 17. Dynamic registration of Servlets/Filters Lookup Example ServletRegistration declared = servletContext.getServletRegistration("Declar edServlet"); declared.addMapping("/declaredServlet"); declared.setInitParameter("param", "value"); 17
  • 18. Agenda ● Overview ● Ease of Development ● Dynamic registration of Servlets and Filters ● Pluggability ● Asynchronous support ● Security enhancements ● Miscellaneous 18
  • 19. Pluggability ● Enable use of libraries and framework without boiler plate configuration in deployment descriptors ● Put the burden on the framework developer ● Modularize web.xml to allow frameworks to be self-contained within their own JAR file ● Programmatic configuration APIs ● Use of annotations 19
  • 20. Pluggability Motivation for web.xml modularization ● Use of framework requires (possibly complex) configuration in web.xml ● For example ● Declare a controller Servlet ● Logging and security Filters ● Declare Listeners to perform actions at various points in the lifecycle of the application ● Can get complex as dependencies increase ● Frameworks also need to document all the configuration that needs to be done 20
  • 21. Pluggability web-fragment.xml ● web-fragment.xml is descriptor for framework / library ● Included in META-INF directory ● Container responsible for discovering fragments and assembling the effective deployment descriptor ● Almost identical to web.xml ● Ordering related elements different ● Only JAR files in WEB-INF/lib considered as fragments 21
  • 22. Pluggability web-fragment.xml example <web-fragment> <servlet> <servlet-name>welcome</servlet-name> <servlet-class>com.mycom.WelcomeServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>welcome</servlet-name> <url-pattern>/Welcome</url-pattern> </servlet-mapping> ... </web-fragment> 22
  • 23. Pluggability Ordering ● Compatible with JavaServer™ Faces ● Fragments identified by <name> ● web.xml may declare absolute ordering of fragments via <absolute-ordering> ● Fragments may declare ordering preferences relative to other fragments via <ordering> with nested <before> and <after> ● Ignored if <absolute-ordering> specified ● Special <others/> element moves fragment to beginning or end of list of sorted fragments 23
  • 24. Pluggability Resource sharing ● Static and JavaServer™ Pages (JSP) resources no longer confined to web application's document root ● May be placed inside WEB-INF/lib/[*.jar]/ META-INF/resources ● Container must honor this new location when processing HTTP requests and calls to ServletContext#getResource[AsStream] ● Resources in document root take precedence over those in bundled JAR files 24
  • 25. Pluggability Resource sharing: Example mywebapp.war packaging: /index.jsp /WEB-INF/lib/shared.jar!/META- INF/resources/shared.jsp Request for: http://localhost:8080/mywebapp/shared.jsp will be served from: /path/to/mywebapp/WEB- INF/lib/shared.jar!/META- INF/resources/shared.jsp 25
  • 26. Pluggability Shared libraries ● Support plugging in of container installed JAR files ● Examples: JSF, JAX-WS, Spring ● Libraries may provide implementation of ServletContainerInitializer ● Looked up via the JAR Services API in JDK 6 ● Invoked before any Listeners during the initialization of the application 26
  • 27. Pluggability Shared libraries (contd) ● ServletContainerInitializer expresses interest in Classes via @HandlesTypes ● Container discovers classes that match @HandlesTypes and passes them to ServletContainerInitializer ● ServletContainerInitializer inspects passed in Classes and may register Servlets and Filters based on them 27
  • 28. Pluggability ServletContainerInitializer example @HandlesTypes(WebService.class) public class JAXWSInitializer implements ServletContainerInitializer { public void onStartup(Set<Class<?>> c, ServletContext ctx) { ctx.addServlet(“JAXWSServlet”, “com.sun.jaxws.JAXWSServlet”); } } 28
  • 29. Agenda ● Overview ● Ease of Development ● Dynamic registration of Servlets and Filters ● Pluggability ● Asynchronous support ● Security enhancements ● Miscellaneous 29
  • 30. Why Asynchronous Servlets? ● Not for Async IO! ● Requests mostly small (single packet) ● Hard to asynchronously produce large responses ● Async IO support waiting for NIO2 (Servlet 3.1?) ● Async Servlets are for: ● Waiting for resources (eg JDBC connection) ● Waiting for events (eg Chat) ● Waiting for responses (eg web services, QoS) 30
  • 31. Blocking waiting consumes resources ● Web Application using remote web services ● Handling 1000 requests / sec ● 50% requests call remote web service ● 500 threads in container thread pool ● If remote web service is slow (1000ms) ● Thread starvation in 1 second! ● 50% of requests use all 500 threads 31
  • 32. Waiting for Web Services Blocking Asynchronous Thread blocked WS request In parallel 32
  • 33. Asynchronous API ServletRequest ● ServletRequest#isAsyncSupported() ● True if ALL [Filter|Servlet]s support async in ● the Filter chain ● the RequestDispatch chain ● Configured in ● web.xml ● <async-supported>true</async-supported> ● With annotation ● @WebServlet(asyncSupported=true) ● Programmatic ● registration.setAsyncSupported(boolean) 33
  • 34. Asynchronous API ServletRequest ● AsyncContext ServletRequest#startAsync() ● Called by [Filter|Servlet] ● Response is NOT commited on return of: ● Servlet.service(request,response) ● Filter chain ● AsyncContext ServletRequest#startAsync (ServletRequest req, ServletResponse res) ● Variation that preserves wrappers 34
  • 35. Asynchronous API AsyncContext ● AsyncContext#dispatch() ● Called by your asynchronous handler ● Schedule async dispatch: DispatcherType.ASYNC ● Response generated by [Filter|Servlet] using: ● container thread pool ● JSP, JSF or other frameworks usable ● JNDI, JTA, EJBs usable ● AsyncContext#dispatch(String path) ● Variation to async dispatch to specific Servlet 35
  • 36. Asynchronous API AsyncContext ● AsyncContext#complete() ● Called by your asynchronous handler ● Response has been generated asynchronously ● without Servlet features, or ● with AsyncContext#start(Runnable r) ● for JNDI, classloader 36
  • 37. Asynchronous Web Service Server Webapp doGet() s t a rtA s y n c () WS call dis pa t c h () doGet() 37
  • 38. Multiple Usage Styles ● startAsync() … dispatch() ● Retry request after async wait ● Filters re-applied if on DispatcherType.ASYNC ● startAsync() … dispatch(path) ● Use specific Servlet handling after async wait ● startAsync() … complete() ● Generate response asynchronously 38
  • 39. Multiple Usage Styles ● startAsync(req,res) … dispatch() ● Retry request after async wait ● Wrappers are kept ● RequestDispatcher#forward target used ● startAsync(req,res) … dispatch(path) ● Specific Servlet handling after async wait ● startAsync(req,res) … complete() ● Generate wrapped response asynchronously 39
  • 40. Asynchronous API Details ● Timeouts ● ServletRequest#setAsyncTimeout(long ms) ● By default error dispatch on timeout ● Listeners ● AsyncListener#OnTimeout ● AsyncListener#OnComplete 40
  • 41. Demonstration Asynchronous eBay Web Service > EoD packaging ● META-INF ● web-fragment.xml ● Resources/* > Glassfish Container ● Async Serlvet > Jetty HTTP Client ● Async Client 41
  • 42. Agenda ● Overview ● Ease of Development ● Dynamic registration of Servlets and Filters ● Pluggability ● Asynchronous support ● Security enhancements ● Miscellaneous 42
  • 43. Security Security constraints via common annotations ● Support for common annotations ● @RolesAllowed -> auth-constraint with roles ● @DenyAll -> Empty auth-constraint ● @PermitAll -> No auth-constraint ● @TransportProtected -> user-data-constraint ● Annotations enforced on javax.http.Servlet class and doXXX methods of HttpServlet ● Method-targeted annotations take precedence over class-targeted annotations 43
  • 44. Security Security constraints via common annotations (contd) ● Security constraints in web.xml override annotations, metdata-complete disables annotations ● web-resource-collection enhanced with http- method-omission to ● Allow constraints to be specified on non- enumerable HTTP method subsets (i.e., all other methods) 44
  • 45. Security Programmatic container authentication and logout ● HttpServletRequest#login(String username, String password) ● Replacement for FBL ● Application supervises credential collection ● HttpServletRequest#authenticate(HttpServl etResponse) ● Application initiates container mediated authentication from a resource that is not covered by any authentication constraints ● Application decides when authentication must occur 45
  • 46. Security Programmatic container authentication and logout (contd) ● HttpServletRequest#logout ● Integration of additional container authentication modules via Servlet Profile of JSR 196 recommended 46
  • 47. Agenda ● Overview ● Ease of Development ● Dynamic registration of Servlets and Filters ● Pluggability ● Asynchronous support ● Security enhancements ● Miscellaneous 47
  • 48. Miscellaneous Features / APIs ● Session tracking cookie configuration ● Via web.xml ● Programmatic via javax.servlet.SessionCookieConfig ● Support for HttpOnly cookie attribute ● Example: servletContext.getSessionCookieConfig ().setHttpOnly(true) ● Default error page 48
  • 49. Miscellaneous Features / APIs (contd) ServletRequest#getServletContext ServletRequest#getDispatcherType Servlet[Request| Response]Wrapper#isWrapperFor HttpServletResponse#getStatus HttpServletResponse#getHeader HttpServletResponse#getHeaders HttpServletResponse#getHeaderNames 49
  • 50. Miscellaneous Features / APIs (contd) File upload APIs ServletRequest#getParts ServletRequest#getPart @MultipartConfig Changes to web.xml 50
  • 51. Summary ● Major revision since Servlet 2.4 ● Comprehensive set of new features enable modern style of web applications and greatly increases developer productivity ● Simplifies assembly of large applications from reusable components 51
  • 52. GlassFish Community Open Source and Enterprise Ready ● GlassFish V3 Preview Available now! ● Java EE 6 reference implementation • 24x7 Enterprise and Mission ● Modular OSGi architecture – easy to develop & deploy Critical Support ● Runs in-process and easy to extend •sun.com/glassfish ● Support for Ruby-on-Rails, Groovy and Grails, Python and Django • Tools Integration ● GlassFish V2 – Production Ready •NetBeans and Eclipse ● Best price/performance open source App server with Clustering, High Availability, Load Balancing glassfish.org ● Secure, Reliable, Transactional, .NET-interop Web svcs ● Support for Ajax and Comet ● GlassFish ESB ● SOA and Business Integration platform ● GlassFish Communications App Server ● SIP servlet technology for converged services Always free to download, deploy and distribute 52
  • 53. Webtide & Jetty > Status update > http://eclipse.org/jetty 53