SlideShare a Scribd company logo
1 of 26
Servlet 3.0




              Minh Hoang TO

              Portal Team
Servlet 3.0 Specification


 - Java Specification Request JSR-315



 - Part of Java Enterprise Edition 6



 - Compliant servers:

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




                     www.exoplatform.com - Copyright 2012 eXo Platform   2
Agenda

- Annotations

- Web Fragment

- Dynamic Registration

- Programmatic Login

- Asynchronous Servlet

- File Upload



                www.exoplatform.com - Copyright 2012 eXo Platform   3
Annotations


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


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


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




                       www.exoplatform.com - Copyright 2012 eXo Platform              4
Annotations

Declare servlet via deployment descriptor:

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

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

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



                      www.exoplatform.com - Copyright 2012 eXo Platform   5
Annotations

Declare servlet via annotated class



@WebServlet
(
  name = “hello”,

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

}




                           www.exoplatform.com - Copyright 2012 eXo Platform   6
Annotations

Declare filter via deployment descriptor:

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

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

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



                       www.exoplatform.com - Copyright 2012 eXo Platform   7
Annotations

Declare filter via annotated class



@WebFilter
(
  name = “hello”,

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

}




                           www.exoplatform.com - Copyright 2012 eXo Platform   8
Annotations


- Type safe and less error-prone

- Facilitate work of developers

- No need to master XSD of deployment descriptor


BUT

- Frequent recompilation is a big obstacle




                       www.exoplatform.com - Copyright 2012 eXo Platform   9
Web Fragment


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

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

  3. Order of fragment processing is manageable




                     www.exoplatform.com - Copyright 2012 eXo Platform      10
Web Fragment


Filter configuration in a web.xml

<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-mapping>
  <filter-name>filterA</filter-name>
  <url-pattern>/testWebFragment/*</url-pattern>
</filter-mapping>

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




                        www.exoplatform.com - Copyright 2012 eXo Platform             11
Web Fragment

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

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

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

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


                        www.exoplatform.com - Copyright 2012 eXo Platform             12
Web Fragment

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

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

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

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


                        www.exoplatform.com - Copyright 2012 eXo Platform             13
Web Fragment

- Base to implement pluggable/extensible configuration


BUT


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




                       www.exoplatform.com - Copyright 2012 eXo Platform   14
Dynamic Registration

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

 Use cases:

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

 2. Register callbacks for deploy/undeploy events on web applications containing
    gatein-resources.xml

- Prior to Servlet 3.0, dynamic registration has to handler native work to
containers (WCI project)

- Doable in a portable manner with Servlet 3.0




                       www.exoplatform.com - Copyright 2012 eXo Platform            15
Dynamic Registration

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



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



- Complex dynamic registration could be plugged to onStartup entry point




                       www.exoplatform.com - Copyright 2012 eXo Platform          16
Dynamic Registration

- Simple implementation for dynamic registration

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

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


                      www.exoplatform.com - Copyright 2012 eXo Platform            17
Dynamic Registration


- Portable code for dynamic registration


BUT


- Class loading issues must be handled gracefully

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




                       www.exoplatform.com - Copyright 2012 eXo Platform           18
Programmatic Login

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

 1. j_security_check
 2. j_username
 3. j_password

Container intercepts that request and delegates to JAAS

- From Servlet 3.0

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

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




                       www.exoplatform.com - Copyright 2012 eXo Platform          19
Asynchronous Servlet

- Use in server-push communication model:

   1. 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 data
   3. As there is update on real time data, server loops through queued request
     and respond to client



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


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




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

    //Typically event from a messaging service
    public void onServerEvent(EventObject obj)
    {
       //Loop over queue and send response to client
    }
}
                       www.exoplatform.com - Copyright 2012 eXo Platform             21
Asynchronous Servlet


<script type=”text/javascript”>

   var url = //url intercepted by livescore servlet
   var updateScore = function()
   {
       $.getJSON(url, function(data)
       {
          //Update HTML with received data
          setTimeout(updateScore, 1000);
       });
   };

   updateScore();
</script>




                       www.exoplatform.com - Copyright 2012 eXo Platform   22
Asynchronous Servlet

- Scalable threading model

BUT

- Header fields of HTTP protocol results in unnecessary network throughput

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




                      www.exoplatform.com - Copyright 2012 eXo Platform         23
File Upload

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


                       www.exoplatform.com - Copyright 2012 eXo Platform          24
File Upload




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




                 www.exoplatform.com - Copyright 2012 eXo Platform   25
File Upload


- Nice API for uploading files


BUT


- Lack of public API to monitor upload progress




                       www.exoplatform.com - Copyright 2012 eXo Platform   26

More Related Content

What's hot

An Introduction To Java Web Technology
An Introduction To Java Web TechnologyAn Introduction To Java Web Technology
An Introduction To Java Web Technology
vikram singh
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
vamsi krishna
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jsp
Jafar Nesargi
 
Servlet api &amp; servlet http package
Servlet api &amp; servlet http packageServlet api &amp; servlet http package
Servlet api &amp; servlet http package
renukarenuka9
 
Html servlet example
Html   servlet exampleHtml   servlet example
Html servlet example
rvpprash
 
Javax.servlet,http packages
Javax.servlet,http packagesJavax.servlet,http packages
Javax.servlet,http packages
vamsi krishna
 

What's hot (20)

Lecture 7 Web Services JAX-WS & JAX-RS
Lecture 7   Web Services JAX-WS & JAX-RSLecture 7   Web Services JAX-WS & JAX-RS
Lecture 7 Web Services JAX-WS & JAX-RS
 
JAVA Servlets
JAVA ServletsJAVA Servlets
JAVA Servlets
 
Lecture 3: Servlets - Session Management
Lecture 3:  Servlets - Session ManagementLecture 3:  Servlets - Session Management
Lecture 3: Servlets - Session Management
 
An Introduction To Java Web Technology
An Introduction To Java Web TechnologyAn Introduction To Java Web Technology
An Introduction To Java Web Technology
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servlet
 
Tomcat
TomcatTomcat
Tomcat
 
Soa installation
Soa installationSoa installation
Soa installation
 
What is play
What is playWhat is play
What is play
 
JDBC
JDBCJDBC
JDBC
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
 
WEB TECHNOLOGIES Servlet
WEB TECHNOLOGIES ServletWEB TECHNOLOGIES Servlet
WEB TECHNOLOGIES Servlet
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jsp
 
Knowledge Sharing : Java Servlet
Knowledge Sharing : Java ServletKnowledge Sharing : Java Servlet
Knowledge Sharing : Java Servlet
 
JAX-WS Basics
JAX-WS BasicsJAX-WS Basics
JAX-WS Basics
 
Servlet
Servlet Servlet
Servlet
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Servlet api &amp; servlet http package
Servlet api &amp; servlet http packageServlet api &amp; servlet http package
Servlet api &amp; servlet http package
 
Servlets - filter, listeners, wrapper, internationalization
Servlets -  filter, listeners, wrapper, internationalizationServlets -  filter, listeners, wrapper, internationalization
Servlets - filter, listeners, wrapper, internationalization
 
Html servlet example
Html   servlet exampleHtml   servlet example
Html servlet example
 
Javax.servlet,http packages
Javax.servlet,http packagesJavax.servlet,http packages
Javax.servlet,http packages
 

Similar to Servlet 3.0

Java EE 6 - Deep Dive - Indic Threads, Pune - 2010
Java EE 6 - Deep Dive - Indic Threads, Pune - 2010Java EE 6 - Deep Dive - Indic Threads, Pune - 2010
Java EE 6 - Deep Dive - Indic Threads, Pune - 2010
Jagadish Prasath
 
Java EE 6 = Less Code + More Power (Tutorial) [5th IndicThreads Conference O...
Java EE 6 = Less Code + More Power (Tutorial)  [5th IndicThreads Conference O...Java EE 6 = Less Code + More Power (Tutorial)  [5th IndicThreads Conference O...
Java EE 6 = Less Code + More Power (Tutorial) [5th IndicThreads Conference O...
IndicThreads
 
Building+restful+webservice
Building+restful+webserviceBuilding+restful+webservice
Building+restful+webservice
lonegunman
 

Similar to Servlet 3.0 (20)

Java Portlet 2.0 (JSR 286) Specification
Java Portlet 2.0 (JSR 286) SpecificationJava Portlet 2.0 (JSR 286) Specification
Java Portlet 2.0 (JSR 286) Specification
 
Java EE 6 - Deep Dive - Indic Threads, Pune - 2010
Java EE 6 - Deep Dive - Indic Threads, Pune - 2010Java EE 6 - Deep Dive - Indic Threads, Pune - 2010
Java EE 6 - Deep Dive - Indic Threads, Pune - 2010
 
Java EE 6 = Less Code + More Power (Tutorial) [5th IndicThreads Conference O...
Java EE 6 = Less Code + More Power (Tutorial)  [5th IndicThreads Conference O...Java EE 6 = Less Code + More Power (Tutorial)  [5th IndicThreads Conference O...
Java EE 6 = Less Code + More Power (Tutorial) [5th IndicThreads Conference O...
 
Web sockets in Java
Web sockets in JavaWeb sockets in Java
Web sockets in Java
 
Rich Portlet Development in uPortal
Rich Portlet Development in uPortalRich Portlet Development in uPortal
Rich Portlet Development in uPortal
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/Servlet
 
Annotation-Based Spring Portlet MVC
Annotation-Based Spring Portlet MVCAnnotation-Based Spring Portlet MVC
Annotation-Based Spring Portlet MVC
 
Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010
Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010
Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010
 
Java servlet technology
Java servlet technologyJava servlet technology
Java servlet technology
 
Java servlets
Java servletsJava servlets
Java servlets
 
1 java servlets and jsp
1   java servlets and jsp1   java servlets and jsp
1 java servlets and jsp
 
SCWCD : Servlet web applications : CHAP : 3
SCWCD : Servlet web applications : CHAP : 3SCWCD : Servlet web applications : CHAP : 3
SCWCD : Servlet web applications : CHAP : 3
 
Apache Stratos Hangout VI
Apache Stratos Hangout VIApache Stratos Hangout VI
Apache Stratos Hangout VI
 
HTTP Whiteboard - OSGI Compendium 6.0 - How web apps should have been! - R Auge
HTTP Whiteboard - OSGI Compendium 6.0 - How web apps should have been! - R AugeHTTP Whiteboard - OSGI Compendium 6.0 - How web apps should have been! - R Auge
HTTP Whiteboard - OSGI Compendium 6.0 - How web apps should have been! - R Auge
 
Developing JSR 286 Portlets
Developing JSR 286 PortletsDeveloping JSR 286 Portlets
Developing JSR 286 Portlets
 
SCWCD : Servlet web applications : CHAP 3
SCWCD : Servlet web applications : CHAP 3SCWCD : Servlet web applications : CHAP 3
SCWCD : Servlet web applications : CHAP 3
 
Introduction to java servlet 3.0 api javaone 2008
Introduction to java servlet 3.0 api javaone 2008Introduction to java servlet 3.0 api javaone 2008
Introduction to java servlet 3.0 api javaone 2008
 
Building+restful+webservice
Building+restful+webserviceBuilding+restful+webservice
Building+restful+webservice
 
Day7
Day7Day7
Day7
 
Http Server Programming in JAVA - Handling http requests and responses
Http Server Programming in JAVA - Handling http requests and responsesHttp Server Programming in JAVA - Handling http requests and responses
Http Server Programming in JAVA - Handling http requests and responses
 

More from Minh Hoang (7)

Yolo Family TechTalk
Yolo Family TechTalkYolo Family TechTalk
Yolo Family TechTalk
 
ElasticSearch Introduction
ElasticSearch IntroductionElasticSearch Introduction
ElasticSearch Introduction
 
Modularize JavaScript with RequireJS
Modularize JavaScript with RequireJSModularize JavaScript with RequireJS
Modularize JavaScript with RequireJS
 
Zero redeployment with JRebel
Zero redeployment with JRebelZero redeployment with JRebel
Zero redeployment with JRebel
 
Regular Expression
Regular ExpressionRegular Expression
Regular Expression
 
Java Performance Tuning
Java Performance TuningJava Performance Tuning
Java Performance Tuning
 
Gatein Presentation
Gatein PresentationGatein Presentation
Gatein Presentation
 

Recently uploaded

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Recently uploaded (20)

AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 

Servlet 3.0

  • 1. Servlet 3.0 Minh Hoang TO Portal Team
  • 2. Servlet 3.0 Specification - Java Specification Request JSR-315 - Part of Java Enterprise Edition 6 - Compliant servers: Apache Tomcat 7, JBoss AS 7, Jetty 8, GlassFish 3, ... www.exoplatform.com - Copyright 2012 eXo Platform 2
  • 3. Agenda - Annotations - Web Fragment - Dynamic Registration - Programmatic Login - Asynchronous Servlet - File Upload www.exoplatform.com - Copyright 2012 eXo Platform 3
  • 4. Annotations - Use annotations to declare servlet, filter, listener and specify metadata for the declared component @WebServlet @WebFilter @WebInitParam @WebListener @ServletSecurity @HttpConstraint - Servlet container detects annotated class and injects metadata into declared components at deploy time www.exoplatform.com - Copyright 2012 eXo Platform 4
  • 5. Annotations Declare servlet via deployment descriptor: <servlet> <servlet-name>hello</servlet-name> <servlet-class>com.mto.presentation.HelloServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/greeting/*</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/sayhello/*</url-pattern> </servlet-mapping> www.exoplatform.com - Copyright 2012 eXo Platform 5
  • 6. Annotations Declare servlet via annotated class @WebServlet ( name = “hello”, urlPatterns = {“/greeting/*“, “/sayhello/*“} ) public class HelloServlet extends HttpServlet { } www.exoplatform.com - Copyright 2012 eXo Platform 6
  • 7. Annotations Declare filter via deployment descriptor: <filter> <filter-name>hello</filter-name> <filter-class>com.mto.presentation.HelloFilter</filter-class> </filter> <filter-mapping> <filter-name>hello</filter-name> <url-pattern>/greeting/*</url-pattern> </filter-mapping> <filter-mapping> <filter-name>hello</filter-name> <url-pattern>/sayhello/*</url-pattern> </filter-mapping> www.exoplatform.com - Copyright 2012 eXo Platform 7
  • 8. Annotations Declare filter via annotated class @WebFilter ( name = “hello”, urlPatterns = {“/greeting/*“, “/sayhello/*“} ) public class HelloFilter implements Filter { } www.exoplatform.com - Copyright 2012 eXo Platform 8
  • 9. Annotations - Type safe and less error-prone - Facilitate work of developers - No need to master XSD of deployment descriptor BUT - Frequent recompilation is a big obstacle www.exoplatform.com - Copyright 2012 eXo Platform 9
  • 10. Web Fragment - 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/lib 2. Web application components could be declared in web-fragment.xml 3. Order of fragment processing is manageable www.exoplatform.com - Copyright 2012 eXo Platform 10
  • 11. Web Fragment Filter configuration in a web.xml <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-mapping> <filter-name>filterA</filter-name> <url-pattern>/testWebFragment/*</url-pattern> </filter-mapping> <filter-mapping> <filter-name>filterB</filter-name> <url-pattern>/testWebFragment/*</url-pattern> </filter-mapping> www.exoplatform.com - Copyright 2012 eXo Platform 11
  • 12. Web Fragment META-INF/web-fragment.xml under filterA.jar <web-fragment> <name>A</name> <filter><filter-name>filterA</filter-name><filter-class>FilterA</filter-class></filter> <filter-mapping> <filter-name>filterA</filter-name> <url-pattern>/testWebFragment/*</url-pattern> </filter-mapping> <ordering> <before> <others/> </before> </ordering> </web-fragment> www.exoplatform.com - Copyright 2012 eXo Platform 12
  • 13. Web Fragment META-INF/web-fragment.xml under filterB.jar <web-fragment> <name>B</name> <filter><filter-name>filterB</filter-name><filter-class>FilterB</filter-class></filter> <filter-mapping> <filter-name>filterB</filter-name> <url-pattern>/testWebFragment/*</url-pattern> </filter-mapping> <ordering> <after> <name>A</name> </after> </ordering> </web-fragment> www.exoplatform.com - Copyright 2012 eXo Platform 13
  • 14. Web Fragment - Base to implement pluggable/extensible configuration BUT - Quite limit as relevant .jar artifacts must be under WEB-INF/lib www.exoplatform.com - Copyright 2012 eXo Platform 14
  • 15. Dynamic Registration - Inject dynamically components, callbacks to ServletContext object on starting the context Use cases: 1. Inject a PortletProducerServlet servlet to ServletContext object of each web- application containing WEB-INF/portlet.xml 2. Register callbacks for deploy/undeploy events on web applications containing gatein-resources.xml - Prior to Servlet 3.0, dynamic registration has to handler native work to containers (WCI project) - Doable in a portable manner with Servlet 3.0 www.exoplatform.com - Copyright 2012 eXo Platform 15
  • 16. Dynamic Registration - As container starts, it detects all implementations of ServletContainerInitializer thanks to java.util.ServiceLoader mechanism, then invokes the method onStartup on each initializing ServletContext public interface ServletContainerInitializer { public void onStartup(Set<Class<?>> c, ServletContext ctx); } - Complex dynamic registration could be plugged to onStartup entry point www.exoplatform.com - Copyright 2012 eXo Platform 16
  • 17. Dynamic Registration - Simple implementation for dynamic registration public SimpleInitializer implements ServletContainerInitializer{ public void onStartup(Set<Class<?>> c, ServletContext ctx) { if(“/sample”.equals(ctx.getContextPath()) { //Code handling ClassLoader elided from example Class clazz = ctx.getClassLoader().loadClass(“abc.DynamicServlet”); ServletRegistration.Dynamic reg = ctx.addServlet(“dynamicServlet”, clazz); reg.addMapping(“/dynamic/*”); } } } - Declare fully-qualified name of implementation class in META- INF/services/javax.servlet.ServletContainerInitializer www.exoplatform.com - Copyright 2012 eXo Platform 17
  • 18. Dynamic Registration - Portable code for dynamic registration BUT - Class loading issues must be handled gracefully - Container detects ServletContainerInitializer via service loader, so the .jar containing ServletContainerInitializer must be visible to container 's bootstrap class loader www.exoplatform.com - Copyright 2012 eXo Platform 18
  • 19. Programmatic Login - Prior to Servlet 3.0, any authentication flow must pass through a redirect request with predefined params 1. j_security_check 2. j_username 3. j_password Container intercepts that request and delegates to JAAS - From Servlet 3.0 request.login(“root”, “gtn”); The whole authentication process could be managed in the scope of a single request www.exoplatform.com - Copyright 2012 eXo Platform 19
  • 20. Asynchronous Servlet - Use in server-push communication model: 1. 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 data 3. As there is update on real time data, server loops through queued request and respond to client - 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 lifecycle. - In Servlet 3.0, request handling thread could be released before the end of request lifecycle www.exoplatform.com - Copyright 2012 eXo Platform 20
  • 21. Asynchronous Servlet @WebServlet( name=”livescore”, asyncSupported=true, urlPatterns = {“/livescore/*”} ) public class LivescoreServlet extends HttpServlet { //Synchronization code elided from example public void doGet(HttpServletRequest req, HttpServletResponse res) { AsyncContext ctx = req.startAsync(req, res); //Thread handling request is released here but the res object is still alive queue.add(ctx); } //Typically event from a messaging service public void onServerEvent(EventObject obj) { //Loop over queue and send response to client } } www.exoplatform.com - Copyright 2012 eXo Platform 21
  • 22. Asynchronous Servlet <script type=”text/javascript”> var url = //url intercepted by livescore servlet var updateScore = function() { $.getJSON(url, function(data) { //Update HTML with received data setTimeout(updateScore, 1000); }); }; updateScore(); </script> www.exoplatform.com - Copyright 2012 eXo Platform 22
  • 23. Asynchronous Servlet - Scalable threading model BUT - Header fields of HTTP protocol results in unnecessary network throughput - WebSocket – better solution is going to appear in future version of Servlet Specification www.exoplatform.com - Copyright 2012 eXo Platform 23
  • 24. File Upload @WebServlet( name = “uploadServlet”, urlPatterns = {“/uploadFile/*”} ) @MultipartConfig public class UploadServlet extends HttpServlet { public void doPost(HttpServletRequest req, HttpServletResponse res) { Collection<Part> parts = req.getParts(); for(Part part : parts) { …....... part.write(System.getProperty(“java.io.tmpdir”) + “/” + part.getName()); …....... } } } www.exoplatform.com - Copyright 2012 eXo Platform 24
  • 25. File Upload <form action=”/uploadFile/ method=”post”> <input type=”file” name=”part_name”/> <input type=”submit” value=”Upload”/> </form> www.exoplatform.com - Copyright 2012 eXo Platform 25
  • 26. File Upload - Nice API for uploading files BUT - Lack of public API to monitor upload progress www.exoplatform.com - Copyright 2012 eXo Platform 26