<Insert Picture Here>




Servlets 3.0
Asynchronous, Extensible, Ease-of-use
Arun Gupta, Java EE & GlassFish Guy
blogs.oracle.com/arungupta, @arungupta
The preceding is intended to outline our general product
direction. It is intended for information purposes only,
and may not be incorporated into any contract. It is
not a commitment to deliver any material, code, or
functionality, and should not be relied upon in making
purchasing decisions.
The development, release, and timing of any features
or functionality described for Oracle’s products remains
at the sole discretion of Oracle.


                                                           2
Agenda
• Overview
• Ease of Development
• Dynamic Registration of Servlets etc
• Pluggability
• Asynchronous Support
• Security Enhancements
• Miscellaneous




                                         3
Overview
l
    Java Servlet 3.0 done as part of JSR 315
l
    ~20 members in the expert group
    –Major Java EE vendors, open source web container developers, framework
     authors
l
    Main areas of focus
    –Ease of Development
    –Pluggability
    –Asynchronous support
    –Security



                                                                          4
Ease of Development

l
    Enhanced APIs to use new Java SE language features introduced
    since J2SE 5.0
    l
        Generics for type safety in API where possible
l
    Annotations for declarative style of programming
    l
        Optional web.xml
l
    Convention over configuration




                                                                5
Ease of Development
       Use of annotations

l
    Annotations to declare Servlets, Filters, Listeners and servlet
    security
    –@WebServlet – Define a Servlet
    –@WebFilter – Define a Filter
    –@WebListener – Define a Listener
    –@WebInitParam – Define init param
    –@MultipartConfig – Define file upload properties
    –@ServletSecurity – Define security constraints
l
    Can override using “web.xml”

                                                                      6
Servlet 2.5 example
      At least 2 files

<!--Deployment descriptor web.xml -->   /* Code in Java Class */
<web-app>
  <servlet>                             package com.sun;
    <servlet-name>MyServlet             public class MyServlet extends HttpServlet
                   </servlet-name>      {
        <servlet-class>                     public void
          com.sun.MyServlet                 doGet(HttpServletRequest
        </servlet-class>                    req,HttpServletResponse res)
   </servlet>                                {
   <servlet-mapping>
                                                  ...
     <servlet-name>MyServlet
        </servlet-name>                      }
     <url-pattern>/myApp/*                  ...
        </url-pattern>
   </servlet-mapping>                   }
    ...
 </web-app>




                                                                                     7
@WebServlet – Sample Code
@WebServlet(urlPatterns={“/myApp”})
public class SimpleSample extends HttpServlet {
    public void doGet(HttpServletRequest req, HttpServletResponse res) {


    }
}




                                                                           8
@WebServlet Async – Sample Code
@WebServlet(urlPatterns=“/myApp”, name=”MyServlet”, asyncSupported=true)
public class SimpleSample extends HttpServlet {
    public void doGet(HttpServletRequest req, HttpServletResponse res) {


    }
}




                                                                           9
Dynamic Registration
        Create and/or register
• 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
        • User returned Registration handle to configure all aspects of [Servlet |
          Filter]
l
    ServletContext#create[Servlet | Filter]
    –Takes Class<? Extends [Servlet | Filter]> argument
    –Supports resource injection by container
    –Returned [Servlet | Filter] instance may be fully customized before it is registered

                                                                                      10
Dynamic Registration
       Lookup


l
    ServletContext#find[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
    –Conflict returned as java.util.Set




                                                                             11
Dynamic Registration
  Register example


ServletRegistration.Dynamic dynamic =
    servletContext.addServlet(
         "DynamicServlet",
         "com.mycom.MyServlet");
dynamic.addMapping("/dynamicServlet");
dynamic.setAsyncSupported(true);




                                         12
Dynamic Registration
    Lookup example


ServletRegistration declared =
    servletContext.getServletRegistration("DeclaredServlet");
declared.addMapping("/declaredServlet");
declared.setInitParameter("param", "value");




                                                                13
Pluggability
• Plugin libraries using web fragments
  – Modular web.xml
  – Absolute ordering: <absolute-ordering>
  – Relative ordering: <ordering>, <before>, <after>
• Bundled in framework *.jar/META-INF
• Zero-configuration, drag-and-drop for web frameworks
  – Servlets, servlet filters, context listeners for a framework get discovered
    and registered by the container
• Only JAR files in WEB-INF/lib are used


                                                                                  14
Pluggability – Sample Code


<web-fragment>
    <filter>
           <filter-name>wicket.helloworld</filter-name>
           <filter-class>org.apache.wicket.protocol.http.WicketFilter</filter-class>
           <init-param>
                 <param-name>applicationClassName</param-name>
                 <param-value>...</param-value>
           </init-param>
    </filter>
    <filter-mapping>
           <filter-name>wicket.helloworld</filter-name>
           <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-fragment>


http://blogs.oracle.com/arungupta/entry/totd_91_applying_java_ee


                                                                                       15
Pluggability – Sample Code

<web-fragment>
  <filter>
     <filter-name>LiftFilter</filter-name>
      <display-name>Lift Filter</display-name>
      <description>The Filter that intercepts lift calls</description>
      <filter-class>net.liftweb.http.LiftFilter</filter-class>
  </filter>
   <filter-mapping>
     <filter-name>LiftFilter</filter-name>
     <url-pattern>/*</url-pattern>
   </filter-mapping>
</web-fragment>

http://blogs.oracle.com/arungupta/entry/totd_101_applying_servlet_3


                                                                         16
Extensibility
  ServletContainerInitializer

• Shared copies of frameworks
• Container installed JARs
  – App or Library
• Discovered using the service provider API
  – META-INF/services/javax.servlet.ServletContainerInitializer
• Expresses interest in classes via @HandlesTypes




                                                                  17
Extensibility
  ServletContainerInitializer

• Who uses it ?
  – Mojarra (JSF2) is bootstrapped into GlassFish
     • No “faces-config.xml” or “web.xml”
  – Jersey (JAX-RS) registers root Application
     • No (or portable) “web.xml”




                                                    18
Dynamic Registration
Java Server Faces
@SuppressWarnings({"UnusedDeclaration"})
@HandlesTypes({
ManagedBean.class,
FacesComponent.class,
FacesValidator.class,
FacesConverter.class,
FacesBehaviorRenderer.class,
ResourceDependency.class,
ResourceDependencies.class,
ListenerFor.class,
ListenersFor.class,
UIComponent.class,
Validator.class,
Converter.class,
Renderer.class
})
public class FacesInitializer implements ServletContainerInitializer {
    // NOTE: Loggins should not be used with this class.
    private static final String FACES_SERVLET_CLASS = FacesServlet.class.getName();




                                                                                      19
Dynamic Registration
Java Server Faces


public void onStartup(Set<Class<?>> classes, ServletContext servletContext)
throws ServletException {
       if (shouldCheckMappings(classes, servletContext)) {
            Map<String,? extends ServletRegistration> existing =
servletContext.getServletRegistrations();
            for (ServletRegistration registration : existing.values()) {
                if (FACES_SERVLET_CLASS.equals(registration.getClassName())) {
                    // FacesServlet has already been defined, so we're
                    // not going to add additional mappings;
                    return;
                }
            }
            ServletRegistration reg =
                  servletContext.addServlet("FacesServlet",
                                            "javax.faces.webapp.FacesServlet");
            reg.addMapping("/faces/*", "*.jsf", "*.faces");
            servletContext.setAttribute(RIConstants.FACES_INITIALIZER_MAPPINGS_ADDED,
Boolean.TRUE);




                                                                                        20
Resource Sharing

• Static and JSP not confined to document root of the web
  application
• May be placed in WEB-INF/lib/[*.jar]/META-
  INF/resources
• Resources in root take precedence over those in bundled JAR
• Container must honor this new location when
  – Processing HTTP requests
  – Calls to ServletContext#getResource[AsStream]



                                                                21
Resource Sharing – Sample Code




myapp.war
  WEB-INF/lib/catalog.jar
             /META-INF/resources/catalog/books.html



http://localhost:8080/myapp/catalog/books.html




                                                      22
Why Asynchronous Servlets?

l
    Not for Async IO
    –Requests mostly small (single packet)
    –Hard to asynchronously produce large responses
    –Async IO support waiting for NIO2

l
    Async Servlets are for:
    –Waiting for resources (eg JDBC connection)
    –Waiting for events (eg Chat)
    –Waiting for responses (eg web services)


                                                      23
Blocking waiting consumes resources

l
    Web Application using remote web services
    –Handling 1000 requests / sec
    –50% requests call remote web service
    –500 threads in container thread pool

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




                                                24
Asynchronous API
    Enable asynchronous support


l
    Configured in
    –web.xml:
     <async-supported>true</async-supported>
    –With annotation: @WebServlet(asyncSupported=true)
    –Programmatic: registration.setAsyncSupported(true)




                                                          25
Asynchronous Servlets – Sample Code

    AsyncContext context = request.startAsync();
    context.addListener(new AsyncListener() { … });
    context.dispatch(“/request.jsp”);
    //context.start(Runnable action);
    . . .
    context.complete();




http://blogs.oracle.com/arungupta/entry/totd_139_asynchronous_request_processing


                                                                                   26
Security
    Annotations to define security constraints

l
  @ServletSecurity used to define access control constraints
l
  @HttpConstraint for all HTTP methods
l
  @HttpMethodConstraint for specific HTTP methods
l
  More specific wins




                                                               27
Security – Sample Code


@ServletSecurity(
  httpMethodConstraints = {
      @HttpMethodConstraint(value = "GET", rolesAllowed = "R1"),
      @HttpMethodConstraint(value = "POST", rolesAllowed = "R2")
    }
)
public class MyServlet extends HttpServlet {
    // Servlet methods
}




                                                                   28
Security
   Programmatic container authentication and logout


>HttpServletRequest#login(String username, String
 password)
–Replacement for FBL
–Application supervises credential collection
>HttpServletRequest#authenticate(HttpServletRespo
 nse)
–Application initiates container mediated authentication from a resource that is
 not covered by any authentication constraints
–Application decides when authentication must occur


                                                                                   29
Miscellaneous Features
l
    Session tracking cookie configuration
    –Via web.xml
    –Programmatic via javax.servlet.SessionCookieConfig
l
    Support for HttpOnly cookie attribute
    –Example:
     servletContext.getSessionCookieConfig().setHttpOnly(true)
l
    Default error page                        <error-page>
                                       <error-code>...</error-code>
                                  <exception-type>...</exception-type>
                                     <location>/404.html</location>
                                             </error-page>



                                                                         30
Miscellaneous Features / API (contd)


ServletRequest#getServletContext
ServletRequest#getDispatcherType
Servlet[Request|
Response]Wrapper#isWrapperFor
HttpServletResponse#getStatus
HttpServletResponse#getHeader
HttpServletResponse#getHeaders
HttpServletResponse#getHeaderNames

                                        31
Miscellaneous Features / API (contd)
 File upload


ServletRequest#getParts
ServletRequest#getPart
@MultipartConfig
Changes to web.xml




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




                                                                 33
Servlets 3.1 (JSR 340)
    http://jcp.org/en/jsr/detail?id=340
                                                        NEW

• Cloud support
• Multi-tenancy
     – Security / Session state / Resources isolation
•   Asynchronous IO based on NIO2
•   Simplified Asynchronous Servlets
•   Utilize Java EE concurrency utilities
•   Enable support for Web Sockets


                                                              34
References


•   oracle.com/javaee
•   glassfish.org
•   oracle.com/goto/glassfish
•   blogs.oracle.com/theaquarium
•   youtube.com/GlassFishVideos
•   Follow @glassfish




                                   35
<Insert Picture Here>




Servlets 3.0
Asynchronous, Extensible, Ease-of-use
Arun Gupta, Java EE & GlassFish Guy
blogs.oracle.com/arungupta, @arungupta

More Related Content

PDF
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010
PDF
Introduction to java servlet 3.0 api javaone 2009
PDF
Introduction to java servlet 3.0 api javaone 2008
PDF
Jsp servlets
PDF
5050 dev nation
DOC
Java Servlets & JSP
PPT
Servlet 3.0
PDF
Lecture 3: Servlets - Session Management
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010
Introduction to java servlet 3.0 api javaone 2009
Introduction to java servlet 3.0 api javaone 2008
Jsp servlets
5050 dev nation
Java Servlets & JSP
Servlet 3.0
Lecture 3: Servlets - Session Management

What's hot (20)

KEY
Multi Client Development with Spring
ODP
RESTing with JAX-RS
KEY
Multi Client Development with Spring
PDF
RESTful Web services using JAX-RS
PDF
Java EE 6 & GlassFish = Less Code + More Power at CEJUG
ODP
Spring Portlet MVC
PDF
Weblogic Administration Managed Server migration
PPT
Knowledge Sharing : Java Servlet
DOC
KEY
Multi client Development with Spring
PDF
Spring mvc
PDF
Lecture 5 JSTL, custom tags, maven
PDF
Weblogic
PPTX
Servlet api &amp; servlet http package
PDF
Spring Framework - MVC
PDF
Arun Gupta: London Java Community: Java EE 6 and GlassFish 3
PDF
java servlet and servlet programming
PPSX
Java server pages
PPT
Java Server Faces (JSF) - Basics
PPT
Web Tech Java Servlet Update1
Multi Client Development with Spring
RESTing with JAX-RS
Multi Client Development with Spring
RESTful Web services using JAX-RS
Java EE 6 & GlassFish = Less Code + More Power at CEJUG
Spring Portlet MVC
Weblogic Administration Managed Server migration
Knowledge Sharing : Java Servlet
Multi client Development with Spring
Spring mvc
Lecture 5 JSTL, custom tags, maven
Weblogic
Servlet api &amp; servlet http package
Spring Framework - MVC
Arun Gupta: London Java Community: Java EE 6 and GlassFish 3
java servlet and servlet programming
Java server pages
Java Server Faces (JSF) - Basics
Web Tech Java Servlet Update1
Ad

Viewers also liked (17)

PDF
S314168 - What's New in Enterprise Java Bean Technology @ JavaOne Brazil 2010
PDF
XML-Free Programming : Java Server and Client Development without &lt;>
PDF
GlassFish in the Virtual World
PDF
Jfokus 2012: PaaSing a Java EE Application
PPT
Sarah grier passport1
PPTX
Cregg Laws having+what+it+takes
PPTX
Alex global+education
PDF
Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010
PPTX
leadership beyond words-nspra
PDF
Healthcare Reform Seminar May 2010
PPT
Power Csba
PDF
Basketball Camp Spanien 2011
PDF
Stage baskete Epagne flyer
PDF
2013 03-12 Change – How long does it take?
PDF
Jfokus 2012 : The Java EE 7 Platform: Developing for the Cloud
PDF
Kindercamps in Spanien 2009
S314168 - What's New in Enterprise Java Bean Technology @ JavaOne Brazil 2010
XML-Free Programming : Java Server and Client Development without &lt;>
GlassFish in the Virtual World
Jfokus 2012: PaaSing a Java EE Application
Sarah grier passport1
Cregg Laws having+what+it+takes
Alex global+education
Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010
leadership beyond words-nspra
Healthcare Reform Seminar May 2010
Power Csba
Basketball Camp Spanien 2011
Stage baskete Epagne flyer
2013 03-12 Change – How long does it take?
Jfokus 2012 : The Java EE 7 Platform: Developing for the Cloud
Kindercamps in Spanien 2009
Ad

Similar to JavaOne India 2011 - Servlets 3.0 (20)

ODP
Java EE 6 = Less Code + More Power (Tutorial) [5th IndicThreads Conference O...
PDF
Java EE 6 - Deep Dive - Indic Threads, Pune - 2010
PDF
Boston 2011 OTN Developer Days - Java EE 6
PDF
Servlet30 20081218
PDF
Java EE 6 & GlassFish 3: Light-weight, Extensible, and Powerful @ Silicon Val...
PDF
Java EE 6 & GlassFish = Less Code + More Power @ DevIgnition
PDF
Java EE 6 = Less Code + More Power
PDF
Java EE 6 & GlassFish 3: Light-weight, Extensible, and Powerful @ JAX London ...
PDF
Java EE 6 & GlassFish v3 @ DevNexus
PDF
Coursejspservlets00
PDF
Jeetrainers.com coursejspservlets00
PDF
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 5...
PDF
Java Enterprise Edition 6 Overview
PDF
Building Next-Gen Web Applications with the Spring 3 Web Stack
PDF
Java EE 6 & GlassFish v3: Paving the path for the future - Tech Days 2010 India
PDF
Java EE 6 : Paving The Path For The Future
PDF
Java EE 6 & GlassFish v3 at Vancouver JUG, Jan 26, 2010
DOCX
Html servlet example
PPT
Spring 3.1: a Walking Tour
PPTX
SCWCD : Servlet web applications : CHAP : 3
Java EE 6 = Less Code + More Power (Tutorial) [5th IndicThreads Conference O...
Java EE 6 - Deep Dive - Indic Threads, Pune - 2010
Boston 2011 OTN Developer Days - Java EE 6
Servlet30 20081218
Java EE 6 & GlassFish 3: Light-weight, Extensible, and Powerful @ Silicon Val...
Java EE 6 & GlassFish = Less Code + More Power @ DevIgnition
Java EE 6 = Less Code + More Power
Java EE 6 & GlassFish 3: Light-weight, Extensible, and Powerful @ JAX London ...
Java EE 6 & GlassFish v3 @ DevNexus
Coursejspservlets00
Jeetrainers.com coursejspservlets00
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 5...
Java Enterprise Edition 6 Overview
Building Next-Gen Web Applications with the Spring 3 Web Stack
Java EE 6 & GlassFish v3: Paving the path for the future - Tech Days 2010 India
Java EE 6 : Paving The Path For The Future
Java EE 6 & GlassFish v3 at Vancouver JUG, Jan 26, 2010
Html servlet example
Spring 3.1: a Walking Tour
SCWCD : Servlet web applications : CHAP : 3

More from Arun Gupta (20)

PDF
5 Skills To Force Multiply Technical Talents.pdf
PPTX
Machine Learning using Kubernetes - AI Conclave 2019
PDF
Machine Learning using Kubeflow and Kubernetes
PPTX
Secure and Fast microVM for Serverless Computing using Firecracker
PPTX
Building Java in the Open - j.Day at OSCON 2019
PPTX
Why Amazon Cares about Open Source
PDF
Machine learning using Kubernetes
PDF
Building Cloud Native Applications
PDF
Chaos Engineering with Kubernetes
PDF
How to be a mentor to bring more girls to STEAM
PDF
Java in a World of Containers - DockerCon 2018
PPTX
The Serverless Tidal Wave - SwampUP 2018 Keynote
PDF
Introduction to Amazon EKS - KubeCon 2018
PDF
Mastering Kubernetes on AWS - Tel Aviv Summit
PDF
Top 10 Technology Trends Changing Developer's Landscape
PDF
Container Landscape in 2017
PDF
Java EE and NoSQL using JBoss EAP 7 and OpenShift
PDF
Docker, Kubernetes, and Mesos recipes for Java developers
PDF
Thanks Managers!
PDF
Migrate your traditional VM-based Clusters to Containers
5 Skills To Force Multiply Technical Talents.pdf
Machine Learning using Kubernetes - AI Conclave 2019
Machine Learning using Kubeflow and Kubernetes
Secure and Fast microVM for Serverless Computing using Firecracker
Building Java in the Open - j.Day at OSCON 2019
Why Amazon Cares about Open Source
Machine learning using Kubernetes
Building Cloud Native Applications
Chaos Engineering with Kubernetes
How to be a mentor to bring more girls to STEAM
Java in a World of Containers - DockerCon 2018
The Serverless Tidal Wave - SwampUP 2018 Keynote
Introduction to Amazon EKS - KubeCon 2018
Mastering Kubernetes on AWS - Tel Aviv Summit
Top 10 Technology Trends Changing Developer's Landscape
Container Landscape in 2017
Java EE and NoSQL using JBoss EAP 7 and OpenShift
Docker, Kubernetes, and Mesos recipes for Java developers
Thanks Managers!
Migrate your traditional VM-based Clusters to Containers

Recently uploaded (20)

PDF
Peak of Data & AI Encore: Scalable Design & Infrastructure
PDF
EGCB_Solar_Project_Presentation_and Finalcial Analysis.pdf
PPTX
Report in SIP_Distance_Learning_Technology_Impact.pptx
PDF
Intravenous drug administration application for pediatric patients via augmen...
PDF
ment.tech-How to Develop an AI Agent Healthcare App like Sully AI (1).pdf
PDF
Human Computer Interaction Miterm Lesson
PPTX
Slides World Game (s) Great Redesign Eco Economic Epochs.pptx
PDF
Domain-specific knowledge and context in large language models: challenges, c...
PDF
The Digital Engine Room: Unlocking APAC’s Economic and Digital Potential thro...
PDF
ELLIE29.pdfWETWETAWTAWETAETAETERTRTERTER
PDF
Optimizing bioinformatics applications: a novel approach with human protein d...
PDF
Altius execution marketplace concept.pdf
PDF
“Introduction to Designing with AI Agents,” a Presentation from Amazon Web Se...
PPTX
Presentation - Principles of Instructional Design.pptx
PDF
Be ready for tomorrow’s needs with a longer-lasting, higher-performing PC
PDF
GDG Cloud Southlake #45: Patrick Debois: The Impact of GenAI on Development a...
PDF
Introduction to c language from lecture slides
PDF
1_Keynote_Breaking Barriers_한계를 넘어서_Charith Mendis.pdf
PDF
Rooftops detection with YOLOv8 from aerial imagery and a brief review on roof...
PDF
Uncertainty-aware contextual multi-armed bandits for recommendations in e-com...
Peak of Data & AI Encore: Scalable Design & Infrastructure
EGCB_Solar_Project_Presentation_and Finalcial Analysis.pdf
Report in SIP_Distance_Learning_Technology_Impact.pptx
Intravenous drug administration application for pediatric patients via augmen...
ment.tech-How to Develop an AI Agent Healthcare App like Sully AI (1).pdf
Human Computer Interaction Miterm Lesson
Slides World Game (s) Great Redesign Eco Economic Epochs.pptx
Domain-specific knowledge and context in large language models: challenges, c...
The Digital Engine Room: Unlocking APAC’s Economic and Digital Potential thro...
ELLIE29.pdfWETWETAWTAWETAETAETERTRTERTER
Optimizing bioinformatics applications: a novel approach with human protein d...
Altius execution marketplace concept.pdf
“Introduction to Designing with AI Agents,” a Presentation from Amazon Web Se...
Presentation - Principles of Instructional Design.pptx
Be ready for tomorrow’s needs with a longer-lasting, higher-performing PC
GDG Cloud Southlake #45: Patrick Debois: The Impact of GenAI on Development a...
Introduction to c language from lecture slides
1_Keynote_Breaking Barriers_한계를 넘어서_Charith Mendis.pdf
Rooftops detection with YOLOv8 from aerial imagery and a brief review on roof...
Uncertainty-aware contextual multi-armed bandits for recommendations in e-com...

JavaOne India 2011 - Servlets 3.0

  • 1. <Insert Picture Here> Servlets 3.0 Asynchronous, Extensible, Ease-of-use Arun Gupta, Java EE & GlassFish Guy blogs.oracle.com/arungupta, @arungupta
  • 2. The preceding is intended to outline our general product direction. It is intended for information purposes only, and may not be incorporated into any contract. It is not a commitment to deliver any material, code, or functionality, and should not be relied upon in making purchasing decisions. The development, release, and timing of any features or functionality described for Oracle’s products remains at the sole discretion of Oracle. 2
  • 3. Agenda • Overview • Ease of Development • Dynamic Registration of Servlets etc • Pluggability • Asynchronous Support • Security Enhancements • Miscellaneous 3
  • 4. Overview l Java Servlet 3.0 done as part of JSR 315 l ~20 members in the expert group –Major Java EE vendors, open source web container developers, framework authors l Main areas of focus –Ease of Development –Pluggability –Asynchronous support –Security 4
  • 5. Ease of Development l Enhanced APIs to use new Java SE language features introduced since J2SE 5.0 l Generics for type safety in API where possible l Annotations for declarative style of programming l Optional web.xml l Convention over configuration 5
  • 6. Ease of Development Use of annotations l Annotations to declare Servlets, Filters, Listeners and servlet security –@WebServlet – Define a Servlet –@WebFilter – Define a Filter –@WebListener – Define a Listener –@WebInitParam – Define init param –@MultipartConfig – Define file upload properties –@ServletSecurity – Define security constraints l Can override using “web.xml” 6
  • 7. Servlet 2.5 example At least 2 files <!--Deployment descriptor web.xml --> /* Code in Java Class */ <web-app> <servlet> package com.sun; <servlet-name>MyServlet public class MyServlet extends HttpServlet </servlet-name> { <servlet-class> public void com.sun.MyServlet doGet(HttpServletRequest </servlet-class> req,HttpServletResponse res) </servlet> { <servlet-mapping> ... <servlet-name>MyServlet </servlet-name> } <url-pattern>/myApp/* ... </url-pattern> </servlet-mapping> } ... </web-app> 7
  • 8. @WebServlet – Sample Code @WebServlet(urlPatterns={“/myApp”}) public class SimpleSample extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) { } } 8
  • 9. @WebServlet Async – Sample Code @WebServlet(urlPatterns=“/myApp”, name=”MyServlet”, asyncSupported=true) public class SimpleSample extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) { } } 9
  • 10. Dynamic Registration Create and/or register • 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 • User returned Registration handle to configure all aspects of [Servlet | Filter] l ServletContext#create[Servlet | Filter] –Takes Class<? Extends [Servlet | Filter]> argument –Supports resource injection by container –Returned [Servlet | Filter] instance may be fully customized before it is registered 10
  • 11. Dynamic Registration Lookup l ServletContext#find[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 –Conflict returned as java.util.Set 11
  • 12. Dynamic Registration Register example ServletRegistration.Dynamic dynamic = servletContext.addServlet( "DynamicServlet", "com.mycom.MyServlet"); dynamic.addMapping("/dynamicServlet"); dynamic.setAsyncSupported(true); 12
  • 13. Dynamic Registration Lookup example ServletRegistration declared = servletContext.getServletRegistration("DeclaredServlet"); declared.addMapping("/declaredServlet"); declared.setInitParameter("param", "value"); 13
  • 14. Pluggability • Plugin libraries using web fragments – Modular web.xml – Absolute ordering: <absolute-ordering> – Relative ordering: <ordering>, <before>, <after> • Bundled in framework *.jar/META-INF • Zero-configuration, drag-and-drop for web frameworks – Servlets, servlet filters, context listeners for a framework get discovered and registered by the container • Only JAR files in WEB-INF/lib are used 14
  • 15. Pluggability – Sample Code <web-fragment> <filter> <filter-name>wicket.helloworld</filter-name> <filter-class>org.apache.wicket.protocol.http.WicketFilter</filter-class> <init-param> <param-name>applicationClassName</param-name> <param-value>...</param-value> </init-param> </filter> <filter-mapping> <filter-name>wicket.helloworld</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-fragment> http://blogs.oracle.com/arungupta/entry/totd_91_applying_java_ee 15
  • 16. Pluggability – Sample Code <web-fragment> <filter> <filter-name>LiftFilter</filter-name> <display-name>Lift Filter</display-name> <description>The Filter that intercepts lift calls</description> <filter-class>net.liftweb.http.LiftFilter</filter-class> </filter> <filter-mapping> <filter-name>LiftFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-fragment> http://blogs.oracle.com/arungupta/entry/totd_101_applying_servlet_3 16
  • 17. Extensibility ServletContainerInitializer • Shared copies of frameworks • Container installed JARs – App or Library • Discovered using the service provider API – META-INF/services/javax.servlet.ServletContainerInitializer • Expresses interest in classes via @HandlesTypes 17
  • 18. Extensibility ServletContainerInitializer • Who uses it ? – Mojarra (JSF2) is bootstrapped into GlassFish • No “faces-config.xml” or “web.xml” – Jersey (JAX-RS) registers root Application • No (or portable) “web.xml” 18
  • 19. Dynamic Registration Java Server Faces @SuppressWarnings({"UnusedDeclaration"}) @HandlesTypes({ ManagedBean.class, FacesComponent.class, FacesValidator.class, FacesConverter.class, FacesBehaviorRenderer.class, ResourceDependency.class, ResourceDependencies.class, ListenerFor.class, ListenersFor.class, UIComponent.class, Validator.class, Converter.class, Renderer.class }) public class FacesInitializer implements ServletContainerInitializer { // NOTE: Loggins should not be used with this class. private static final String FACES_SERVLET_CLASS = FacesServlet.class.getName(); 19
  • 20. Dynamic Registration Java Server Faces public void onStartup(Set<Class<?>> classes, ServletContext servletContext) throws ServletException { if (shouldCheckMappings(classes, servletContext)) { Map<String,? extends ServletRegistration> existing = servletContext.getServletRegistrations(); for (ServletRegistration registration : existing.values()) { if (FACES_SERVLET_CLASS.equals(registration.getClassName())) { // FacesServlet has already been defined, so we're // not going to add additional mappings; return; } } ServletRegistration reg = servletContext.addServlet("FacesServlet", "javax.faces.webapp.FacesServlet"); reg.addMapping("/faces/*", "*.jsf", "*.faces"); servletContext.setAttribute(RIConstants.FACES_INITIALIZER_MAPPINGS_ADDED, Boolean.TRUE); 20
  • 21. Resource Sharing • Static and JSP not confined to document root of the web application • May be placed in WEB-INF/lib/[*.jar]/META- INF/resources • Resources in root take precedence over those in bundled JAR • Container must honor this new location when – Processing HTTP requests – Calls to ServletContext#getResource[AsStream] 21
  • 22. Resource Sharing – Sample Code myapp.war WEB-INF/lib/catalog.jar /META-INF/resources/catalog/books.html http://localhost:8080/myapp/catalog/books.html 22
  • 23. Why Asynchronous Servlets? l Not for Async IO –Requests mostly small (single packet) –Hard to asynchronously produce large responses –Async IO support waiting for NIO2 l Async Servlets are for: –Waiting for resources (eg JDBC connection) –Waiting for events (eg Chat) –Waiting for responses (eg web services) 23
  • 24. Blocking waiting consumes resources l Web Application using remote web services –Handling 1000 requests / sec –50% requests call remote web service –500 threads in container thread pool l If remote web service is slow (1000ms) –Thread starvation in 1 second! –50% of requests use all 500 threads 24
  • 25. Asynchronous API Enable asynchronous support l Configured in –web.xml: <async-supported>true</async-supported> –With annotation: @WebServlet(asyncSupported=true) –Programmatic: registration.setAsyncSupported(true) 25
  • 26. Asynchronous Servlets – Sample Code AsyncContext context = request.startAsync(); context.addListener(new AsyncListener() { … }); context.dispatch(“/request.jsp”); //context.start(Runnable action); . . . context.complete(); http://blogs.oracle.com/arungupta/entry/totd_139_asynchronous_request_processing 26
  • 27. Security Annotations to define security constraints l @ServletSecurity used to define access control constraints l @HttpConstraint for all HTTP methods l @HttpMethodConstraint for specific HTTP methods l More specific wins 27
  • 28. Security – Sample Code @ServletSecurity( httpMethodConstraints = { @HttpMethodConstraint(value = "GET", rolesAllowed = "R1"), @HttpMethodConstraint(value = "POST", rolesAllowed = "R2") } ) public class MyServlet extends HttpServlet { // Servlet methods } 28
  • 29. Security Programmatic container authentication and logout >HttpServletRequest#login(String username, String password) –Replacement for FBL –Application supervises credential collection >HttpServletRequest#authenticate(HttpServletRespo nse) –Application initiates container mediated authentication from a resource that is not covered by any authentication constraints –Application decides when authentication must occur 29
  • 30. Miscellaneous Features l Session tracking cookie configuration –Via web.xml –Programmatic via javax.servlet.SessionCookieConfig l Support for HttpOnly cookie attribute –Example: servletContext.getSessionCookieConfig().setHttpOnly(true) l Default error page <error-page> <error-code>...</error-code> <exception-type>...</exception-type> <location>/404.html</location> </error-page> 30
  • 31. Miscellaneous Features / API (contd) ServletRequest#getServletContext ServletRequest#getDispatcherType Servlet[Request| Response]Wrapper#isWrapperFor HttpServletResponse#getStatus HttpServletResponse#getHeader HttpServletResponse#getHeaders HttpServletResponse#getHeaderNames 31
  • 32. Miscellaneous Features / API (contd) File upload ServletRequest#getParts ServletRequest#getPart @MultipartConfig Changes to web.xml 32
  • 33. Summary l Major revision since Servlet 2.5 l Comprehensive set of new features enable modern style of web applications and greatly increases developer productivity l Simplifies assembly of large applications from reusable components 33
  • 34. Servlets 3.1 (JSR 340) http://jcp.org/en/jsr/detail?id=340 NEW • Cloud support • Multi-tenancy – Security / Session state / Resources isolation • Asynchronous IO based on NIO2 • Simplified Asynchronous Servlets • Utilize Java EE concurrency utilities • Enable support for Web Sockets 34
  • 35. References • oracle.com/javaee • glassfish.org • oracle.com/goto/glassfish • blogs.oracle.com/theaquarium • youtube.com/GlassFishVideos • Follow @glassfish 35
  • 36. <Insert Picture Here> Servlets 3.0 Asynchronous, Extensible, Ease-of-use Arun Gupta, Java EE & GlassFish Guy blogs.oracle.com/arungupta, @arungupta