servlets 3.0 - asynchronous, easy, extensible @ silicon valley code camp 2010

46
1

Upload: arun-gupta

Post on 22-Nov-2014

1.549 views

Category:

Technology


4 download

DESCRIPTION

Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010

TRANSCRIPT

Page 1: Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010

1

Page 2: Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010

<Insert Picture Here>

Servlet 3.0, Asynchronous, Easy extensible

Rajiv [email protected]

Page 3: Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 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, Easy, Extensible @ Silicon Valley Code Camp 2010

4

Agenda

• Overview• Ease of Development• Dynamic registration• Pluggability• Asynchronous Support

• Security Enhancements• Miscellaneous

Page 5: Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010

5

Overview

• Final release done in December 2009.• ~20 members in the expert group

– Good mix of representation from major Java EE vendors, open source web container developers and framework authors

• Main areas of focus

– Ease of Development

– Pluggability

– Asynchronous support

– Security

Page 6: Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010

6

Ease of Development

• Focus on Ease of Development in the Servlet 3.0 API• Enhanced APIs to use new Java SE language features

introduced since J2SE 5.0• Annotations for declarative style of programming

– web.xml optional

• Generics for type safety in API where possible• Better defaults • Convention over configuration

Page 7: Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010

7

Ease of DevelopmentUse of annotations

• 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• Can use web.xml to override values specified in

annotations

Page 8: Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010

8

Ease of DevelopmentUse of annotations (contd)

• @WebServlet for defining a Servlet

– Annotations MUST have at a minimum a URL pattern for the Servlet

– All other attributes 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 (and others)

derived from HttpServlet

Page 9: Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010

9

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 clas s MyServlet extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res)

{

...

}

...

}

Page 10: Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010

10

Servlet 3.0 example

@WebServlet(“/foo”)

public class SimpleSample extends HttpServlet

{

public void doGet(HttpServletRequest req,HttpServletResponse res)

{

}

}

Page 11: Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010

11

Servlet 3.0 example

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

public class SimpleSample extends HttpServlet

{

public void doGet(HttpServletRequest req,HttpServletResponse res)

{

}

}

Page 12: Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010

12

Dynamic Registration 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

– User returned Registration handle to configure all aspects of [Servlet | Filter]

Page 13: Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010

13

Dynamic Registration Create and register

• 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 via the • ServletContext.add[Servlet | Filter]

methods

Page 14: Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010

14

Dynamic Registration 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

– Conflict returned as • java.util.Set

Page 15: Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010

15

Dynamic Registration Register example

ServletRegistration.Dynamic dynamic =

servletContext.addServlet(

"DynamicServlet",

"com.mycom.MyServlet");

dynamic.addMapping("/dynamicServlet");

dynamic.setAsyncSupported(true);

Page 16: Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010

16

Dynamic Registration Lookup example

ServletRegistration declared = servletContext.getServletRegistration("DeclaredServlet");

declared.addMapping("/declaredServlet");

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

Page 17: Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010

17

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

Page 18: Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010

18

PluggabilityMotivation 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

Page 19: Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010

19

Pluggabilityweb-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

Page 20: Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010

20

Pluggabilityweb-fragment.xml

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

Page 21: Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010

21

PluggabilityOrdering

• 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

Page 22: Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010

22

PluggabilityShared 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

Page 23: Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010

23

PluggabilityShared 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

Page 24: Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010

24

PluggabilityServletContainerInitializer example

@HandlesTypes(WebService.class)

public class JAXWSInitializer implements ServletContainerInitializer {

public void onStartup(Set<Class<?>> c, ServletContext ctx)

{

ctx.addServlet(“JAXWSServlet”, “com.sun.jaxws.JAXWSServlet”);

}

}

Page 25: Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010

25

PluggabilityResource 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

Page 26: Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010

26

PluggabilityResource 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

Page 27: Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010

27

Why Asynchronous Servlets?

• Async Servlets are for:

– Waiting for resources (eg JDBC connection)

– Waiting for events (eg Chat)

– Waiting for responses (eg web services)• Not for Async IO!

– Requests mostly small (single packet)

– Hard to asynchronously produce large responses

– Async IO support waiting for NIO2

Page 28: Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010

28

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

Page 29: Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010

29

Asynchronous APIEnable asynchronous support

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

Page 30: Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010

30

Asynchronous APIStart asynchronous processing

• 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

Page 31: Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010

31

Asynchronous APIAsyncContext

• 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

Page 32: Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010

32

Asynchronous APIAsyncContext (contd)

• AsyncContext#complete()– Called by your asynchronous handler

– Signals Response has been generated • without [Filter|Servlet] dispatch• without Servlet features• Or with AsyncContext#start(Runnable r)

Page 33: Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010

33

Asynchronous API 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

Page 34: Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010

34

Asynchronous API 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

Page 35: Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010

35

Asynchronous APITimeout

• Timeouts

– AsyncContext#setAsyncTimeout(long ms)– By default error dispatch on timeout

• Listeners

– AsyncListener#OnTimeout– AsyncListener#OnComplete

Page 36: Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010

36

SecurityAnnotations to define security constraints

• @ServletSecurity used to define access control constraints

• Can specify constraint for all HTTP methods via the @HttpConstraint

• Or specify constraint for specific HTTP methods via the @HttpMethodConstraint

• If both specified in the @ServletSecurity, the @HttpConstraint applies to those methods not specifically specified via the @HttpMethodConstraint

Page 37: Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010

37

SecurityExample

@ServletSecurity((httpMethodConstraints = {

@HttpMethodConstraint(value = "GET", rolesAllowed = "R1"),

@HttpMethodConstraint(value = "POST", rolesAllowed = "R1",

transportGuarantee = TransportGuarantee.CONFIDENTIAL)

})

public class Example5 extends HttpServlet {

}

Page 38: Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010

38

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 39: Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010

39

SecurityProgrammatic container authentication and logout

• Integration of additional container authentication modules via Servlet Profile of JSR 196 recommended

• HttpServletRequest#logout

Page 40: Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010

40

Miscellaneous Features / API enhancements

• 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

Page 41: Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010

41

Miscellaneous Features / API enhancements (contd)

• ServletRequest#getServletContext• ServletRequest#getDispatcherType• Servlet[Request|Response]Wrapper#isWrapperFor

• HttpServletResponse#getStatus• HttpServletResponse#getHeader• HttpServletResponse#getHeaders• HttpServletResponse#getHeaderNames

Page 42: Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010

42

Miscellaneous Features / API (contd)File upload

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

Page 43: Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010

43

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

Page 44: Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010

44

Resources

• http://jcp.org/en/jsr/summary?id=315

• https://glassfish.dev.java.net• http://java.sun.com/javaee

Page 45: Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010

45

Q&A

Page 46: Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010

<Insert Picture Here>

Servlet 3.0, Asynchronous, Easy extensible

Rajiv [email protected]