Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010

34
<Insert Picture Here> Servlets 3.0 Asynchronous, Extensiblity, Ease-of-use Arun Gupta, Java EE & GlassFish Guy blogs.sun.com/arungupta, @arungupta

description

Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010

Transcript of Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010

Page 1: Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010

<Insert Picture Here>

Servlets 3.0Asynchronous, Extensiblity, Ease-of-use

Arun Gupta, Java EE & GlassFish Guyblogs.sun.com/arungupta, @arungupta

Page 2: Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010

2

Beijing 2010

December 13–16, 2010

Page 3: Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010

3

The following 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.

Page 4: Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010

4

Agenda

• Overview• Ease of Development• Dynamic Registration of Servlets and

Filters• Pluggability• Asynchronous Support• Security Enhancements• Miscellaneous

Page 5: Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010

5

Overview

l Java Servlet 3.0 done as part of JSR 315– Final release done in December 2009.

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

Page 6: Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010

6

Ease of Development

l Enhanced APIs to use new Java SE language features introduced since J2SE 5.0– Generics for type safety in API where possible

l Annotations for declarative style of programming– web.xml optional

l Convention over configuration

Page 7: Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010

7

Ease of DevelopmentUse 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”

Page 8: Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010

8

Servlet 2.5 exampleAt least 2 files

<!--Deployment descriptor web.xml -->

<web-app><servlet> <servlet-name>MyServlet

</servlet-name> <servlet-class> com.sun.MyServlet </servlet-class> </servlet> <servlet-mapping> <servlet-name>MyServlet </servlet-name> <url-pattern>/myApp/* </url-pattern> </servlet-mapping> ... </web-app>

/* Code in Java Class */

package com.sun;public class MyServlet extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res)

{

...

}

...

}

Page 9: Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010

9

@WebServlet – Sample Code

@WebServlet(urlPatterns={“/myApp”})

public class SimpleSample extends HttpServlet

{

public void doGet(HttpServletRequest req,HttpServletResponse res)

{

}

}

Page 10: Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010

10

@WebServlet Async – Sample Code

@WebServlet(urlPatterns=“/myApp”, name=”MyServlet”, asyncSupported=true)

public class SimpleSample extends HttpServlet

{

public void doGet(HttpServletRequest req,HttpServletResponse res)

{

}

}

Page 11: Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010

11

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

Page 12: Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010

12

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

Page 13: Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010

13

Dynamic Registration Register example

ServletRegistration.Dynamic dynamic =

servletContext.addServlet(

"DynamicServlet",

"com.mycom.MyServlet");

dynamic.addMapping("/dynamicServlet");

dynamic.setAsyncSupported(true);

Page 14: Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010

14

Dynamic Registration Lookup example

ServletRegistration declared =

servletContext.getServletRegistration("DeclaredServlet");

declared.addMapping("/declaredServlet");

declared.setInitParameter("param", "value");

Page 15: Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010

15

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

Page 16: Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010

16

<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.sun.com/arungupta/entry/totd_91_applying_java_ee

Pluggability – Sample Code

Page 17: Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010

17

<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.sun.com/arungupta/entry/totd_101_applying_servlet_3

Pluggability – Sample Code

Page 18: Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010

18

ExtensibilityServletContainerInitializer

• Container installed JARs– App or Library

• Discovered using the service provider API• Expresses interest in classes via

@HandlesTypes• 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”

Page 19: Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010

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();

Page 20: Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010

20

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);

Dynamic RegistrationJava Server Faces

Page 21: Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010

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]

Page 22: Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010

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

Page 23: Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010

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)

Page 24: Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010

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

Page 25: Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010

25

Asynchronous APIEnable asynchronous support

l Configured in– web.xml:

<async-supported>true</async-supported>

– With annotation: @WebServlet(asyncSupported=true)

– Programmatic: registration.setAsyncSupported(true)

Page 26: Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010

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.sun.com/arungupta/entry/totd_139_asynchronous_request_processing

Page 27: Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010

27

SecurityAnnotations to define security constraints

l @ServletSecurity used to define access control constraints

l @HttpConstraint for all HTTP methodsl @HttpMethodConstraint for specific HTTP

methodsl More specific wins

Page 28: Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010

28

Security – Sample Code

@ServletSecurity( httpMethodConstraints = { @HttpMethodConstraint(value = "GET", rolesAllowed = "R1"), @HttpMethodConstraint(value = "POST", rolesAllowed = "R2") })

public class MyServlet extends HttpServlet {

// Servlet methods

}

Page 29: Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010

29

SecurityProgrammatic container authentication and logout

> HttpServletRequest#login(String username, String password)– Replacement for FBL– Application supervises credential collection

> HttpServletRequest#authenticate(HttpServletResponse)– Application initiates container mediated authentication from a

resource that is not covered by any authentication constraints– Application decides when authentication must occur

Page 30: Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010

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>

Page 31: Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010

31

Miscellaneous Features / API (contd)

ServletRequest#getServletContext

ServletRequest#getDispatcherType

Servlet[Request|Response]Wrapper#isWrapperFor

HttpServletResponse#getStatus

HttpServletResponse#getHeader

HttpServletResponse#getHeaders

HttpServletResponse#getHeaderNames

Page 32: Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010

32

Miscellaneous Features / API (contd)File upload

ServletRequest#getParts

ServletRequest#getPart

@MultipartConfig

Changes to web.xml

Page 33: Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010

33

Summary

l Major revision since Servlet 2.5l 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

Page 34: Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010

34

References

• glassfish.org• blogs.sun.com/theaquarium• youtube.com/user/GlassFishVideos• facebook.com/glassfish• Follow @glassfish