servlet 3.0

26
S ervlet3.0 Minh Hoang TO Portal Team

Upload: minh-hoang

Post on 17-May-2015

1.192 views

Category:

Technology


0 download

TRANSCRIPT

Page 1: Servlet 3.0

Servlet 3.0

Minh Hoang TO

Portal Team

Page 2: Servlet 3.0

www.exoplatform.com - Copyright 2012 eXo Platform 2

Servlet 3.0 Specification

- Java Specification Request JSR-315- Java Specification Request JSR-315

- Part of Java Enterprise Edition 6- Part of Java Enterprise Edition 6

- Compliant servers:- Compliant servers:

Apache Tomcat 7, JBoss AS 7, Jetty 8, GlassFish 3, ...Apache Tomcat 7, JBoss AS 7, Jetty 8, GlassFish 3, ...

Page 3: Servlet 3.0

www.exoplatform.com - Copyright 2012 eXo Platform 3

Agenda

-- AnnotationsAnnotations

- Web Fragment- Web Fragment

- Dynamic Registration- Dynamic Registration

- Programmatic Login- Programmatic Login

- Asynchronous Servlet- Asynchronous Servlet

- File Upload - File Upload

Page 4: Servlet 3.0

www.exoplatform.com - Copyright 2012 eXo Platform 4

Annotations

- Use annotations to declare servlet, filter, listener and specify metadata for the - Use annotations to declare servlet, filter, listener and specify metadata for the declared componentdeclared component

@WebServlet@WebServlet @WebFilter @WebFilter @WebInitParam @WebInitParam @WebListener @WebListener @ServletSecurity @ServletSecurity @HttpConstraint @HttpConstraint

- Servlet container detects annotated class and injects metadata into declared - Servlet container detects annotated class and injects metadata into declared components at deploy timecomponents at deploy time

Page 5: Servlet 3.0

www.exoplatform.com - Copyright 2012 eXo Platform 5

Annotations

Declare servlet via deployment descriptor:Declare servlet via deployment descriptor:

<servlet><servlet> <servlet-name>hello</servlet-name><servlet-name>hello</servlet-name> <servlet-class>com.mto.presentation.HelloServlet</servlet-class><servlet-class>com.mto.presentation.HelloServlet</servlet-class></servlet></servlet>

<servlet-mapping><servlet-mapping> <servlet-name>hello</servlet-name><servlet-name>hello</servlet-name> <url-pattern>/greeting/*</url-pattern><url-pattern>/greeting/*</url-pattern></servlet-mapping></servlet-mapping>

<servlet-mapping><servlet-mapping> <servlet-name>hello</servlet-name><servlet-name>hello</servlet-name> <url-pattern>/sayhello/*</url-pattern><url-pattern>/sayhello/*</url-pattern></servlet-mapping></servlet-mapping>

Page 6: Servlet 3.0

www.exoplatform.com - Copyright 2012 eXo Platform 6

Annotations

Declare servlet via annotated classDeclare servlet via annotated class

@WebServlet@WebServlet( ( name = “hello”,name = “hello”,

urlPatterns = {“/greeting/*“, “/sayhello/*“}urlPatterns = {“/greeting/*“, “/sayhello/*“}))public class HelloServlet extends HttpServlet {public class HelloServlet extends HttpServlet {

}}

Page 7: Servlet 3.0

www.exoplatform.com - Copyright 2012 eXo Platform 7

Annotations

Declare filter via deployment descriptor:Declare filter via deployment descriptor:

<filter><filter> <filter-name>hello</filter-name><filter-name>hello</filter-name> <filter-class>com.mto.presentation.HelloFilter</filter-class><filter-class>com.mto.presentation.HelloFilter</filter-class></filter></filter>

<filter-mapping><filter-mapping> <filter-name>hello</filter-name><filter-name>hello</filter-name> <url-pattern>/greeting/*</url-pattern><url-pattern>/greeting/*</url-pattern></filter-mapping></filter-mapping>

<filter-mapping><filter-mapping> <filter-name>hello</filter-name><filter-name>hello</filter-name> <url-pattern>/sayhello/*</url-pattern><url-pattern>/sayhello/*</url-pattern></filter-mapping></filter-mapping>

Page 8: Servlet 3.0

www.exoplatform.com - Copyright 2012 eXo Platform 8

Annotations

Declare filter via annotated classDeclare filter via annotated class

@WebFilter@WebFilter( ( name = “hello”,name = “hello”,

urlPatterns = {“/greeting/*“, “/sayhello/*“}urlPatterns = {“/greeting/*“, “/sayhello/*“}))public class HelloFilter implements Filter {public class HelloFilter implements Filter {

}}

Page 9: Servlet 3.0

www.exoplatform.com - Copyright 2012 eXo Platform 9

Annotations

- Type safe and less error-prone- Type safe and less error-prone

- Facilitate work of developers- Facilitate work of developers

- No need to master XSD of deployment descriptor- No need to master XSD of deployment descriptor

BUTBUT

- Frequent recompilation is a big obstacle- Frequent recompilation is a big obstacle

Page 10: Servlet 3.0

www.exoplatform.com - Copyright 2012 eXo Platform 10

Web Fragment

- Divide WEB-INF/web.xml into multiples META-INF/web-fragment.xml :- Divide WEB-INF/web.xml into multiples META-INF/web-fragment.xml :

1. Each web-fragment.xml is packed in a .jar artifact under WEB-INF/lib1. Each web-fragment.xml is packed in a .jar artifact under WEB-INF/lib

2. Web application components could be declared in web-fragment.xml2. Web application components could be declared in web-fragment.xml

3. Order of fragment processing is manageable 3. Order of fragment processing is manageable

Page 11: Servlet 3.0

www.exoplatform.com - Copyright 2012 eXo Platform 11

Web Fragment

Filter configuration in a web.xml Filter configuration in a web.xml

<filter><filter-name>filterA</filter-name><filter-class>FilterA</filter-class></filter><filter><filter-name>filterA</filter-name><filter-class>FilterA</filter-class></filter><filter><filter-name>filterB</filter-name><filter-class>FilterB</filter-class></filter><filter><filter-name>filterB</filter-name><filter-class>FilterB</filter-class></filter>

<filter-mapping><filter-mapping> <filter-name>filterA</filter-name><filter-name>filterA</filter-name> <url-pattern>/testWebFragment/*</url-pattern><url-pattern>/testWebFragment/*</url-pattern></filter-mapping></filter-mapping>

<filter-mapping><filter-mapping> <filter-name>filterB</filter-name><filter-name>filterB</filter-name> <url-pattern>/testWebFragment/*</url-pattern><url-pattern>/testWebFragment/*</url-pattern></filter-mapping></filter-mapping>

Page 12: Servlet 3.0

www.exoplatform.com - Copyright 2012 eXo Platform 12

Web Fragment

META-INF/web-fragment.xml under filterA.jarMETA-INF/web-fragment.xml under filterA.jar

<web-fragment><web-fragment> <name>A</name><name>A</name> <filter><filter-name>filterA</filter-name><filter-class>FilterA</filter-class></filter><filter><filter-name>filterA</filter-name><filter-class>FilterA</filter-class></filter>

<filter-mapping><filter-mapping> <filter-name>filterA</filter-name><filter-name>filterA</filter-name> <url-pattern>/testWebFragment/*</url-pattern><url-pattern>/testWebFragment/*</url-pattern> </filter-mapping></filter-mapping>

<ordering><ordering> <before><before> <others/><others/> </before></before> </ordering></ordering></web-fragment></web-fragment>

Page 13: Servlet 3.0

www.exoplatform.com - Copyright 2012 eXo Platform 13

Web Fragment

META-INF/web-fragment.xml under filterB.jarMETA-INF/web-fragment.xml under filterB.jar

<web-fragment><web-fragment> <name>B</name><name>B</name> <filter><filter-name>filterB</filter-name><filter-class>FilterB</filter-class></filter><filter><filter-name>filterB</filter-name><filter-class>FilterB</filter-class></filter>

<filter-mapping><filter-mapping> <filter-name>filterB</filter-name><filter-name>filterB</filter-name> <url-pattern>/testWebFragment/*</url-pattern><url-pattern>/testWebFragment/*</url-pattern> </filter-mapping></filter-mapping>

<ordering><ordering> <after><after> <name>A</name><name>A</name> </after></after> </ordering></ordering></web-fragment></web-fragment>

Page 14: Servlet 3.0

www.exoplatform.com - Copyright 2012 eXo Platform 14

Web Fragment

- Base to implement pluggable/extensible configuration- Base to implement pluggable/extensible configuration

BUTBUT

- Quite limit as relevant .jar artifacts must be under WEB-INF/lib- Quite limit as relevant .jar artifacts must be under WEB-INF/lib

Page 15: Servlet 3.0

www.exoplatform.com - Copyright 2012 eXo Platform 15

Dynamic Registration

- Inject dynamically components, callbacks to ServletContext object on starting - Inject dynamically components, callbacks to ServletContext object on starting the contextthe context

Use cases:Use cases:

1. Inject a PortletProducerServlet servlet to ServletContext object of each web-1. Inject a PortletProducerServlet servlet to ServletContext object of each web- application containing WEB-INF/portlet.xml application containing WEB-INF/portlet.xml

2. Register callbacks for deploy/undeploy events on web applications containing 2. Register callbacks for deploy/undeploy events on web applications containing gatein-resources.xml gatein-resources.xml - Prior to Servlet 3.0, dynamic registration has to handler native work to - Prior to Servlet 3.0, dynamic registration has to handler native work to containers (WCI project)containers (WCI project)

- Doable in a portable manner with Servlet 3.0- Doable in a portable manner with Servlet 3.0

Page 16: Servlet 3.0

www.exoplatform.com - Copyright 2012 eXo Platform 16

Dynamic Registration

- As container starts, it detects all implementations of ServletContainerInitializer - As container starts, it detects all implementations of ServletContainerInitializer thanks to java.util.ServiceLoader mechanism, then invokes the method onStartup thanks to java.util.ServiceLoader mechanism, then invokes the method onStartup on each initializing ServletContext on each initializing ServletContext

public interface ServletContainerInitializerpublic interface ServletContainerInitializer{{ public void onStartup(Set<Class<?>> c, ServletContext ctx);public void onStartup(Set<Class<?>> c, ServletContext ctx);}}

- Complex dynamic registration could be plugged to onStartup entry point- Complex dynamic registration could be plugged to onStartup entry point

Page 17: Servlet 3.0

www.exoplatform.com - Copyright 2012 eXo Platform 17

Dynamic Registration

- Simple implementation for dynamic registration- Simple implementation for dynamic registration

public SimpleInitializer implements ServletContainerInitializer{public SimpleInitializer implements ServletContainerInitializer{ public void onStartup(Set<Class<?>> c, ServletContext ctx)public void onStartup(Set<Class<?>> c, ServletContext ctx) {{ if(“/sample”.equals(ctx.getContextPath())if(“/sample”.equals(ctx.getContextPath()) {{ //Code handling ClassLoader elided from example//Code handling ClassLoader elided from example Class clazz = ctx.getClassLoader().loadClass(“abc.DynamicServlet”);Class clazz = ctx.getClassLoader().loadClass(“abc.DynamicServlet”); ServletRegistration.Dynamic reg = ctx.addServlet(“dynamicServlet”, clazz);ServletRegistration.Dynamic reg = ctx.addServlet(“dynamicServlet”, clazz); reg.addMapping(“/dynamic/*”); reg.addMapping(“/dynamic/*”); } } }}}}

- Declare fully-qualified name of implementation class in - Declare fully-qualified name of implementation class in META-INF/services/javax.servlet.ServletContainerInitializerMETA-INF/services/javax.servlet.ServletContainerInitializer

Page 18: Servlet 3.0

www.exoplatform.com - Copyright 2012 eXo Platform 18

Dynamic Registration

- Portable code for dynamic registration- Portable code for dynamic registration

BUTBUT

- Class loading issues must be handled gracefully- Class loading issues must be handled gracefully

- Container detects ServletContainerInitializer via service loader, so the .jar - Container detects ServletContainerInitializer via service loader, so the .jar containing ServletContainerInitializer must be visible to container 's bootstrap containing ServletContainerInitializer must be visible to container 's bootstrap class loaderclass loader

Page 19: Servlet 3.0

www.exoplatform.com - Copyright 2012 eXo Platform 19

Programmatic Login

- Prior to Servlet 3.0, any authentication flow must pass through a redirect request - Prior to Servlet 3.0, any authentication flow must pass through a redirect request with predefined paramswith predefined params

1. j_security_check1. j_security_check 2. j_username2. j_username 3. j_password3. j_password

Container intercepts that request and delegates to JAASContainer intercepts that request and delegates to JAAS

- From Servlet 3.0- From Servlet 3.0

request.login(“root”, “gtn”);request.login(“root”, “gtn”);

The whole authentication process could be managed in the scope of a single The whole authentication process could be managed in the scope of a single requestrequest

Page 20: Servlet 3.0

www.exoplatform.com - Copyright 2012 eXo Platform 20

Asynchronous Servlet

- Use in server-push communication model:- Use in server-push communication model:

1. Client sends request for real time data such as: livescore, exchange rate1. Client sends request for real time data such as: livescore, exchange rate 2. Server queues the request as there is no event on real time data2. Server queues the request as there is no event on real time data 3. As there is update on real time data, server loops through queued request3. As there is update on real time data, server loops through queued request and respond to client and respond to client

- Prior to Servlet 3.0, implementation of such communication model (using Servlet - Prior to Servlet 3.0, implementation of such communication model (using Servlet API) is not scalable as request handling thread is not released during request API) is not scalable as request handling thread is not released during request lifecycle.lifecycle.

- In Servlet 3.0, request handling thread could be released before the end of - In Servlet 3.0, request handling thread could be released before the end of request lifecyclerequest lifecycle

Page 21: Servlet 3.0

www.exoplatform.com - Copyright 2012 eXo Platform 21

Asynchronous Servlet@WebServlet(@WebServlet( name=”livescore”,name=”livescore”, asyncSupported=true, asyncSupported=true, urlPatterns = {“/livescore/*”}urlPatterns = {“/livescore/*”}))public class LivescoreServlet extends HttpServletpublic class LivescoreServlet extends HttpServlet{{ //Synchronization code elided from example//Synchronization code elided from example public void doGet(HttpServletRequest req, HttpServletResponse res)public void doGet(HttpServletRequest req, HttpServletResponse res) {{ AsyncContext ctx = req.startAsync(req, res);AsyncContext ctx = req.startAsync(req, res); //Thread handling request is released here but the res object is still alive//Thread handling request is released here but the res object is still alive queue.add(ctx);queue.add(ctx); }}

//Typically event from a messaging service//Typically event from a messaging service public void onServerEvent(EventObject obj)public void onServerEvent(EventObject obj) {{ //Loop over queue and send response to client//Loop over queue and send response to client }}}}

Page 22: Servlet 3.0

www.exoplatform.com - Copyright 2012 eXo Platform 22

Asynchronous Servlet

<script type=”text/javascript”> <script type=”text/javascript”> var url = //url intercepted by livescore servletvar url = //url intercepted by livescore servlet var updateScore = function()var updateScore = function() {{ $.getJSON(url, function(data)$.getJSON(url, function(data) {{ //Update HTML with received data//Update HTML with received data setTimeout(updateScore, 1000);setTimeout(updateScore, 1000); });}); };};

updateScore();updateScore(); </script></script>

Page 23: Servlet 3.0

www.exoplatform.com - Copyright 2012 eXo Platform 23

Asynchronous Servlet

- Scalable threading model- Scalable threading model

BUTBUT

- Header fields of HTTP protocol results in unnecessary network throughput- Header fields of HTTP protocol results in unnecessary network throughput

- WebSocket – better solution is going to appear in future version of Servlet - WebSocket – better solution is going to appear in future version of Servlet SpecificationSpecification

Page 24: Servlet 3.0

www.exoplatform.com - Copyright 2012 eXo Platform 24

File Upload

@WebServlet(@WebServlet( name = “uploadServlet”, urlPatterns = {“/uploadFile/*”}name = “uploadServlet”, urlPatterns = {“/uploadFile/*”}))@MultipartConfig@MultipartConfigpublic class UploadServlet extends HttpServletpublic class UploadServlet extends HttpServlet{{ public void doPost(HttpServletRequest req, HttpServletResponse res)public void doPost(HttpServletRequest req, HttpServletResponse res) {{ Collection<Part> parts = req.getParts();Collection<Part> parts = req.getParts(); for(Part part : parts)for(Part part : parts) {{ … ….............. part.write(System.getProperty(“java.io.tmpdir”) + “/” + part.getName());part.write(System.getProperty(“java.io.tmpdir”) + “/” + part.getName()); … ….............. }} }}}}

Page 25: Servlet 3.0

www.exoplatform.com - Copyright 2012 eXo Platform 25

File Upload

<form action=”/uploadFile/ method=”post”><form action=”/uploadFile/ method=”post”> <input type=”file” name=”part_name”/><input type=”file” name=”part_name”/> <input type=”submit” value=”Upload”/><input type=”submit” value=”Upload”/> </form> </form>

Page 26: Servlet 3.0

www.exoplatform.com - Copyright 2012 eXo Platform 26

File Upload

- Nice API for uploading files- Nice API for uploading files

BUTBUT

- Lack of public API to monitor upload progress- Lack of public API to monitor upload progress