``Servlet 3.0
Rajiv MordaniServlet Specification leadSenior Staff Engineer
Sun Proprietary/Confidential: Internal Use Only 2
Agenda
• Overview• Pluggability• Ease of Development• Async support• Security• Status• Summary
Sun Proprietary/Confidential: Internal Use Only 3
Overview
• Java Servlet 3.0 API – JSR 315• Has about 20 members in the expert group with a good mix of
representation from the major Java™ EE vendors, web container vendors and individual web framework authors• Main areas of improvements and additions are -> Pluggability> Ease of Development> Async support> Security
• Specification in Public Review and things can change
Sun Proprietary/Confidential: Internal Use Only 4
Agenda
• Overview• Pluggability• Ease of Development• Async support• Security• Status• Summary
Sun Proprietary/Confidential: Internal Use Only 5
Pluggability
• Make it possible to use frameworks / libraries without boiler plate configuration that needs to be added to the descriptor• Modularize web.xml to allow frameworks to have their own artifacts
defined and self-contained within the framework jar• Add APIs to ServletContext that allow addition of Servlets and
Filters at context initialization time• Alternately use annotations to declare components that will be
discovered at deployment / runtime by the container
Sun Proprietary/Confidential: Internal Use Only 6
Pluggability – Modularization of web.xml• Current users of frameworks today need to have boiler plate
configuration in the web.xml, the deployment descriptor for the application, to use a framework• For example, > to use a framework the developer needs to define a servlet, typically a controller
servlet.> Define Filters, to do logging or a filter to implement security constraints> Define listeners so that appropriate action can be taken at different points in the
application / component's life cycle.• Monolithic web.xml can become complex as dependencies increase• Frameworks need to document the boiler plate configuration
Sun Proprietary/Confidential: Internal Use Only 7
Pluggability - web-fragment.xml
• In servlet 3.0 we now have a web-fragment.xml, that a framework / library can bundle• Defines all the artifacts it needs (ala boiler plate configuration)• Included in the framework in the META-INF/services directory• Container responsible for discovering the fragments and assembling the
deployment descriptor for the application• Essentially almost identical to the web.xml but the top level element is
web-fragment as opposed to web-app• Frameworks now have the deployment configuration included in itself• Container scans WEB-INF/lib of the application for these fragments and
assembles the descriptor for the application
Sun Proprietary/Confidential: Internal Use Only 8
Pluggability – web-fragment.xml sample<web-fragment> <servlet> <servlet-name>welcome</servlet-name> <servlet-class> WelcomeServlet </servlet-class> </servlet> <servlet-mapping> <servlet-name>welcome</servlet-name> <url-pattern>/Welcome</url-pattern> </servlet-mapping>...</web-fragment>
Sun Proprietary/Confidential: Internal Use Only 9
Rules for merging• Defined in the public review of the specification• web.xml takes precedence over web-fragment.xml• No ordering defined for web-fragment.xml• If ordering of listeners / filters are important then they MUST be defined
in the web.xml• Container scans for the fragments• If you don't want fragments to be scanned, everything MUST be
specified in the web.xml and the metadata-complete MUST be set to true in the web.xml• This will also turn off scanning of annotations> Works in a mode compatible with servlet 2.5> Can be used in production systems when you are no longer changing any of
these features• Can enable / disable certain servlets if you don't want them deployed
from a framework using the enable flag in web.xml
Sun Proprietary/Confidential: Internal Use Only 10
Pluggability – Configuration methods added to ServletContext• In addition to the modularization of web.xml, new methods have been
added to ServletContext to declare and configure Servlets and Filters• Can only be invoked at context initialization time• Allows a (framework) developer to > Declare a new Servlet programatically> Define the parameters for it (init params, urlPatterns, etc)> Declare a Filter> Define the parameters for it (init params, urlPatterns, etc)
• Enables applications / frameworks to be able to dynamically add Servlets and Fiters.
Sun Proprietary/Confidential: Internal Use Only 11
ServletContext API usage sample@WebServletContextListenerpublic class MyListener { public void contextInitialized (ServletContextEvent sce) { ServletContext sc = sce.getServletContext(); sc.addServlet("myServlet", "Sample servlet", "foo.bar.MyServlet",
null, -1); sc.addServletMapping("myServlet", new String[] {"/urlpattern/*"}); }}
Sun Proprietary/Confidential: Internal Use Only 12
ServletContext API usage sample – changes post public review@WebServletContextListenerpublic class MyListener { public void contextInitialized (ServletContextEvent sce) { ServletContext sc = sce.getServletContext(); ServletRegistration sr = sc.addServlet("NewServlet", "test.NewServlet"); sr.setInitParameter("servletInitName", "servletInitValue"); sc.addServletMapping("NewServlet", new String[] {"/newServlet"});
FilterRegistration fr = sc.addFilter("NewFilter", "test.NewFilter"); fr.setInitParameter("filterInitName", "filterInitValue"); sc.addFilterMappingForServletNames("NewFilter", EnumSet.of(DispatcherType.REQUEST), true, "NewServlet");
}}
Sun Proprietary/Confidential: Internal Use Only 13
Agenda
• Overview• Pluggability• Ease of Development• Async support• Security• Status• Summary
Sun Proprietary/Confidential: Internal Use Only 14
Ease of Development
• Focus on Ease of Development in the Servlet 3.0 API• Enhance the API to use the new language features introduced since
Java SE 5• Annotations for declarative style of programming• Generics for better type safety in the API where possible without
breaking backwards compatibility• Make descriptors optional• Better defaults and conventions for configuration
Sun Proprietary/Confidential: Internal Use Only 15
Ease of Development – use of annotations• Specification defines annotations to declare, Servlet, Filter, ServletContextListener and security constraints.• @WebServlet annotation for defining a servlet• The servlet annotation MUST contain at a minimum the url pattern for
the servlet.• All other fields optional with reasonable defaults> For example, the default name of the servlet, if not specified, is the fully qualified
class name• Class MUST still extends HttpServlet> Method contracts for doGet, doPost etc still derived from the abstract
class• Can use the web.xml to override values specified in the annotations> Don't need to recompile code to change configuration at deployment time
Sun Proprietary/Confidential: Internal Use Only 16
Servlet example - 2.5
public class SimpleSample extends HttpServlet { public void doGet (HttpServletRequest req, HttpServletResponse res) {
}}
web.xml<web-app> <servlet> <servlet-name> MyServlet </servlet-name> <servlet-class> samples.SimpleSample </servlet-class> </servlet> <servlet-mapping> <servlet-name> MyServlet </servlet-name> <url-pattern> /MyApp </url-pattern> </servlet-mapping>...</web-app>
Sun Proprietary/Confidential: Internal Use Only 17
Servlet example - 3.0
@Servlet(“/foo”)public class SimpleSample extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) {
}}
Sun Proprietary/Confidential: Internal Use Only 18
Agenda
• Overview• Pluggability• Ease of Development• Async support• Security• Status• Summary
Sun Proprietary/Confidential: Internal Use Only 19
Async Support – Use cases
• Wait for a resource to become available (JDBC, call to webservice)• Generate response asynchronously• Use the existing frameworks to generate responses after waiting for the
async operation to complete
Sun Proprietary/Confidential: Internal Use Only 20
Async - API
• Annotation attributes in the @WebServlet and @ServletFilter annotations that indicates if a Servlet or a Filter supports async. The attribute is asyncSupported.• To initiate an async operation there are methods on ServletRequest - startAsync(req, res) and startAsync()• Call to startAsync returns an AsyncContext initialized with
the request and response objects passed to the startAsync call.• AsyncContext.forward(path) and AsyncContext.forward() that forwards the request back to the container so you can use frameworks like JSP to generate the response.• AsyncContext.complete() indicates that the developer is
done processing the request and generating the appropriate response.
Sun Proprietary/Confidential: Internal Use Only 21
Async API - contd.
• There are a few more methods in ServletRequest like isAsyncSupported and isAsyncStarted that can be used by applications to determine if async operations are supported or started.• There is also a new listener - AsyncListener that applications can
use to get notified of when async processing is completed or if a timeout occurs.
Sun Proprietary/Confidential: Internal Use Only 22
Async API usage
• Initiate async processing using > startAsync(req, res)> startAsync().
• startAsync() with no parameters implicitly uses the original request and response • startAsync(req, res) uses the request and response
objects passed in. • The request and response passed in can be wrapped by filters or other
servlets earlier in the request processing chain. • AsyncContext is initialized appropriately with the request and
response depending on the method used. • When wrapping the response and calling the no arguments startAsync() if any data has been written to the wrapped
response and not flushed to the underlying response stream you could lose the data..
Sun Proprietary/Confidential: Internal Use Only 23
Async API usage - contd
• After the async processing is over you can forward the request back to run in the context of the web container. • there are three methods that are available in the AsyncContext
that enable this. > forward() no args forwards back to the "original url" or if a forward
(AsyncContext or RequestDispatcher forward) has occured after an async context has been initialized then the no args forward will forward to the path that was used by the AsyncContext / RequestDispatcher to forward to.
> forward(path) forwards to the path relative to the context of the request> forward(ServletContext, path) forwards to the path relative to
the context specified. Below is an example that shows a simple web application that is waiting for a webservice call to return and then rendering the response
Sun Proprietary/Confidential: Internal Use Only 24
Async API example
@WebServlet(“/foo”, asyncSupported=true)public class SimpleSample extends HttpServlet { public void doGet (HttpServletRequest req, HttpServletResponse res) { ...AsyncContext aCtx = request.startAsync(req, res);ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(10); executor.execute(new AsyncWebService(aCtx)); }}
public class AsyncWebService implements Runnable {
AsyncContext ctx; public AsyncWebService(AsyncContext ctx) {
this.ctx = ctx; } public void run() { // Invoke web service and save result in request attribute
// Forward the request to render the result to a JSP. ctx.forward("/render.jsp");
}}
Sun Proprietary/Confidential: Internal Use Only 25
Agenda
• Overview• Pluggability• Ease of Development• Async support• Security• Status• Summary
Sun Proprietary/Confidential: Internal Use Only 26
Security• Not in the public review of the spec – still not closed in the EG• Looking to add programattic login and logout• Method can be used to force a login and ability to logout• Proposal is to add login and logout methods to HttpServletRequest, HttpSession (logout only)• Login method intended to allow an application or framework to force a
container mediated authentication from within an unconstrained request context• Login requires access to the HttpResponse object to set the www-authenticate header. > Available through new methods added to the request to give access to the
corresponding response object• Logout methods are provided to allow an application to reset the
authentication state of a request without requiring that authentication be bound to an HttpSession
Sun Proprietary/Confidential: Internal Use Only 27
Security - contd.
• Add support for annotations defined in Java EE 5 - @RolesAllowed, @PermitAll, @DenyAll • Added support for HttpOnlyCookies• Prevents access to the cookie from client side scripting code• Prevents cross-site scripting attacks.• Method added to Cookie to set and query if it is an
HttpOnly cookie
Sun Proprietary/Confidential: Internal Use Only 28
Agenda
• Overview• Pluggability• Ease of Development• Async support• Security• Status• Summary
Sun Proprietary/Confidential: Internal Use Only 29
Status
• Specification currently in Public Review• Proposed final draft and final release will be aligned with Java EE 6• Implementation of a lot of the Public Review version of the specification
is available today in the GlassFish trunk build. > Shing Wai and I are thinking of doing a screencast to demo the features
available today after the holidays
Sun Proprietary/Confidential: Internal Use Only 30
Summary
• Lot of exciting things happening in the Java™ Servlet 3.0 API> Pluggability for frameworks> Ease of Development for developers> Async support> Security enhancements
• Make the life of the framework developer and users of the frameworks much easier• Implementation being done in the open source as part of GlassFish
project.
Sun Proprietary/Confidential: Internal Use Only 31
Resources
• JCP page> http://jcp.org/en/jsr/detail?id=315
• Feedback alias> [email protected]
• Mailing list for GlassFish related webtier issues> [email protected]
• Blogs> Rajiv - http://weblogs.java.net/blog/mode> Shing Wai - http://blogs.sun.com/swchan> Jan Luehe - http://blogs.sun.com/jluehe> Jeanfrancois Arcand - http://weblogs.java.net/blog/jfarcand> Aggregated feed for GlassFish webtier -
http://planets.sun.com/glassfishwebtier/group/blogs/ or http://feeds.feedburner.com/GlassFish-Webtier
``Servlet 3.0
Rajiv MordaniServlet Specification leadSenior Staff Engineer