Your SlideShare is downloading. ×
0
<Insert Picture Here>Servlets 3.0Asynchronous, Extensible, Ease-of-useArun Gupta, Java EE & GlassFish Guyblogs.oracle.com/...
The preceding is intended to outline our general productdirection. It is intended for information purposes only,and may no...
Agenda• Overview• Ease of Development• Dynamic Registration of Servlets etc• Pluggability• Asynchronous Support• Security ...
Overviewl    Java Servlet 3.0 done as part of JSR 315l    ~20 members in the expert group    –Major Java EE vendors, open ...
Ease of Developmentl    Enhanced APIs to use new Java SE language features introduced    since J2SE 5.0    l        Generi...
Ease of Development       Use of annotationsl    Annotations to declare Servlets, Filters, Listeners and servlet    securi...
Servlet 2.5 example      At least 2 files<!--Deployment descriptor web.xml -->   /* Code in Java Class */<web-app>  <servl...
@WebServlet – Sample Code@WebServlet(urlPatterns={“/myApp”})public class SimpleSample extends HttpServlet {    public void...
@WebServlet Async – Sample Code@WebServlet(urlPatterns=“/myApp”, name=”MyServlet”, asyncSupported=true)public class Simple...
Dynamic Registration        Create and/or register• ServletContext#add[Servlet | Filter]        • Overloaded versions take...
Dynamic Registration       Lookupl    ServletContext#find[Servlet |Filter]Registration    –Takes [Servlet | Filter] name a...
Dynamic Registration  Register exampleServletRegistration.Dynamic dynamic =    servletContext.addServlet(         "Dynamic...
Dynamic Registration    Lookup exampleServletRegistration declared =    servletContext.getServletRegistration("DeclaredSer...
Pluggability• Plugin libraries using web fragments  – Modular web.xml  – Absolute ordering: <absolute-ordering>  – Relativ...
Pluggability – Sample Code<web-fragment>    <filter>           <filter-name>wicket.helloworld</filter-name>           <fil...
Pluggability – Sample Code<web-fragment>  <filter>     <filter-name>LiftFilter</filter-name>      <display-name>Lift Filte...
Extensibility  ServletContainerInitializer• Shared copies of frameworks• Container installed JARs  – App or Library• Disco...
Extensibility  ServletContainerInitializer• Who uses it ?  – Mojarra (JSF2) is bootstrapped into GlassFish     • No “faces...
Dynamic RegistrationJava Server Faces@SuppressWarnings({"UnusedDeclaration"})@HandlesTypes({ManagedBean.class,FacesCompone...
Dynamic RegistrationJava Server Facespublic void onStartup(Set<Class<?>> classes, ServletContext servletContext)throws Ser...
Resource Sharing• Static and JSP not confined to document root of the web  application• May be placed in WEB-INF/lib/[*.ja...
Resource Sharing – Sample Codemyapp.war  WEB-INF/lib/catalog.jar             /META-INF/resources/catalog/books.htmlhttp://...
Why Asynchronous Servlets?l    Not for Async IO    –Requests mostly small (single packet)    –Hard to asynchronously produ...
Blocking waiting consumes resourcesl    Web Application using remote web services    –Handling 1000 requests / sec    –50%...
Asynchronous API    Enable asynchronous supportl    Configured in    –web.xml:     <async-supported>true</async-supported>...
Asynchronous Servlets – Sample Code    AsyncContext context = request.startAsync();    context.addListener(new AsyncListen...
Security    Annotations to define security constraintsl  @ServletSecurity used to define access control constraintsl  @Htt...
Security – Sample Code@ServletSecurity(  httpMethodConstraints = {      @HttpMethodConstraint(value = "GET", rolesAllowed ...
Security   Programmatic container authentication and logout>HttpServletRequest#login(String username, String password)–Rep...
Miscellaneous Featuresl    Session tracking cookie configuration    –Via web.xml    –Programmatic via javax.servlet.Sessio...
Miscellaneous Features / API (contd)ServletRequest#getServletContextServletRequest#getDispatcherTypeServlet[Request|Respon...
Miscellaneous Features / API (contd) File uploadServletRequest#getPartsServletRequest#getPart@MultipartConfigChanges to we...
Summaryl  Major revision since Servlet 2.5l  Comprehensive set of new features enable modern style of web  applications an...
Servlets 3.1 (JSR 340)    http://jcp.org/en/jsr/detail?id=340                                                        NEW• ...
References•   oracle.com/javaee•   glassfish.org•   oracle.com/goto/glassfish•   blogs.oracle.com/theaquarium•   youtube.c...
<Insert Picture Here>Servlets 3.0Asynchronous, Extensible, Ease-of-useArun Gupta, Java EE & GlassFish Guyblogs.oracle.com/...
Upcoming SlideShare
Loading in...5
×

JavaOne India 2011 - Servlets 3.0

1,682

Published on

Servlets 3.0 - JavaOne India 2011

Published in: Technology, Education
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
1,682
On Slideshare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
104
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Transcript of "JavaOne India 2011 - Servlets 3.0"

  1. 1. <Insert Picture Here>Servlets 3.0Asynchronous, Extensible, Ease-of-useArun Gupta, Java EE & GlassFish Guyblogs.oracle.com/arungupta, @arungupta
  2. 2. The preceding is intended to outline our general productdirection. It is intended for information purposes only,and may not be incorporated into any contract. It isnot a commitment to deliver any material, code, orfunctionality, and should not be relied upon in makingpurchasing decisions.The development, release, and timing of any featuresor functionality described for Oracle’s products remainsat the sole discretion of Oracle. 2
  3. 3. Agenda• Overview• Ease of Development• Dynamic Registration of Servlets etc• Pluggability• Asynchronous Support• Security Enhancements• Miscellaneous 3
  4. 4. Overviewl Java Servlet 3.0 done as part of JSR 315l ~20 members in the expert group –Major Java EE vendors, open source web container developers, framework authorsl Main areas of focus –Ease of Development –Pluggability –Asynchronous support –Security 4
  5. 5. Ease of Developmentl Enhanced APIs to use new Java SE language features introduced since J2SE 5.0 l Generics for type safety in API where possiblel Annotations for declarative style of programming l Optional web.xmll Convention over configuration 5
  6. 6. Ease of Development Use of annotationsl 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 constraintsl Can override using “web.xml” 6
  7. 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. 8. @WebServlet – Sample Code@WebServlet(urlPatterns={“/myApp”})public class SimpleSample extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) { }} 8
  9. 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. 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. 11. Dynamic Registration Lookupl 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. 12. Dynamic Registration Register exampleServletRegistration.Dynamic dynamic = servletContext.addServlet( "DynamicServlet", "com.mycom.MyServlet");dynamic.addMapping("/dynamicServlet");dynamic.setAsyncSupported(true); 12
  13. 13. Dynamic Registration Lookup exampleServletRegistration declared = servletContext.getServletRegistration("DeclaredServlet");declared.addMapping("/declaredServlet");declared.setInitParameter("param", "value"); 13
  14. 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. 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. 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. 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. 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. 19. Dynamic RegistrationJava 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. 20. Dynamic RegistrationJava Server Facespublic 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 were // 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. 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. 22. Resource Sharing – Sample Codemyapp.war WEB-INF/lib/catalog.jar /META-INF/resources/catalog/books.htmlhttp://localhost:8080/myapp/catalog/books.html 22
  23. 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 NIO2l Async Servlets are for: –Waiting for resources (eg JDBC connection) –Waiting for events (eg Chat) –Waiting for responses (eg web services) 23
  24. 24. Blocking waiting consumes resourcesl Web Application using remote web services –Handling 1000 requests / sec –50% requests call remote web service –500 threads in container thread pooll If remote web service is slow (1000ms) –Thread starvation in 1 second! –50% of requests use all 500 threads 24
  25. 25. Asynchronous API Enable asynchronous supportl Configured in –web.xml: <async-supported>true</async-supported> –With annotation: @WebServlet(asyncSupported=true) –Programmatic: registration.setAsyncSupported(true) 25
  26. 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. 27. Security Annotations to define security constraintsl @ServletSecurity used to define access control constraintsl @HttpConstraint for all HTTP methodsl @HttpMethodConstraint for specific HTTP methodsl More specific wins 27
  28. 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. 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. 30. Miscellaneous Featuresl Session tracking cookie configuration –Via web.xml –Programmatic via javax.servlet.SessionCookieConfigl 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. 31. Miscellaneous Features / API (contd)ServletRequest#getServletContextServletRequest#getDispatcherTypeServlet[Request|Response]Wrapper#isWrapperForHttpServletResponse#getStatusHttpServletResponse#getHeaderHttpServletResponse#getHeadersHttpServletResponse#getHeaderNames 31
  32. 32. Miscellaneous Features / API (contd) File uploadServletRequest#getPartsServletRequest#getPart@MultipartConfigChanges to web.xml 32
  33. 33. Summaryl Major revision since Servlet 2.5l Comprehensive set of new features enable modern style of web applications and greatly increases developer productivityl Simplifies assembly of large applications from reusable components 33
  34. 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. 35. References• oracle.com/javaee• glassfish.org• oracle.com/goto/glassfish• blogs.oracle.com/theaquarium• youtube.com/GlassFishVideos• Follow @glassfish 35
  36. 36. <Insert Picture Here>Servlets 3.0Asynchronous, Extensible, Ease-of-useArun Gupta, Java EE & GlassFish Guyblogs.oracle.com/arungupta, @arungupta
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×