SlideShare a Scribd company logo
1 of 26
Download to read offline
Sling Models Using Sightly
and JSP
DEEPAK KHETAWAT
About the Speaker
What & Why Sling Models?
- Introduction to Sling Models
- Need and Essence of Sling Models
- Design Goals
Sling Model Annotations
- Annotations Usage
Sling Model Injectors
- Injectors available in 1.0.x and 1.1.x
- Custom Injectors
- Injectors Usage
Agenda
Usage of Sling Models with Sightly and JSP
- Sling Models dependencies
- How to use Sling Models with JSP ?
- How to use Sling Models with Sightly?
Demo
- Functionality Demo
Appendix and Q&A
- Appendix
- Q&A
What & Why Sling Models
• Sling Models are POJO’s which are automatically
mapped from Sling objects, typically resources, request
objects. Sometimes these POJOs need OSGi services
as well
What are Sling Models?
• Entirely annotation driven. "Pure" POJOs
• Adapt multiple objects
• Work with existing Sling infrastructure
• Client doesn't know/care that these objects are different than any
other adapter factory
• Support both classes and interfaces
• Pluggable
Design Goals
• Saves from creating own adapters
• Context aware Dependency Injection Framework
• Do More with Less Code making Code Readable and Removing
Redundant (Boiler Plate) Code
• Highly Testable Code
- Sling Model Inject Annotations defines the dependency
contract
- Mock dependencies with tools like Mockito @InjectMocks
Why Sling Models ?
Sling Models Annotations
Annotations Usage
Sling Model Annotation Code Snippet Description
@Model @Model(adaptables = Resource.class) Class is annotated with @Model and the adaptable class
@Inject
@Inject private String propertyName; (class )
@Inject String getPropertyName(); (interface )
A property named "propertyName" will be looked up from the
Resource (after first adapting it to a ValueMap) and it is injected ,
else will return null if property not found .
@Default @Inject @Default(values = "AEM") private String technology; A default value (for Strings , Arrays , primitives etc. )
@Optional @Inject @Optional private String otherName.
@Injected fields/methods are assumed to be required. To mark
them as optional, use @Optional i.e resource or adaptable may or
may not have property .
Annotations Usage Cont...
Sling Model Annotation Code Snippet Description
@Named @Inject @Named("title") private String pageTitle;
Inject a property whose name does NOT match the Model field
name
@Via
@Model(adaptables=SlingHttpServletRequest.class)
public interface SlingModelDemo {
@Inject @Via("resource") String getPropertyName(); }
Use a JavaBean property of the adaptable as the source of the
injection
// Code Snippet will return
request.getResource().adaptTo(ValueMap.class).get("propertyNam
e", String.class)
@Source
@Model(adaptables=SlingHttpServletRequest.class)
@Inject @Source("script-bindings") Resource
getResource(); }
Explicitly tie an injected field or method to a particular injector (by
name). Can also be on other annotations
//Code snippet will ensure that "resource" is retrieved from the
bindings, not a request attribute
@PostConstruct
@PostConstruct
protected void sayHello() { logger.info("hello"); }
Methods to call upon model option creation (only for model classes)
Sling Model Injectors
• Injectors are OSGi services implementing the
org.apache.sling.models.spi.Injector interface
• Injectors are invoked in order of their service ranking, from lowest to
highest.
What are Injectors ?
• Script Bindings (script-bindings)
• Value Map (valuemap)
• Child Resources (child-resources)
• Request Attributes (request-attributes)
• OSGI Service References (osgi-services)
Standard Injectors in 1.0.x
Injectors (with @Source names)
Injects adaptable itself or an object that can be adapted from
adaptable
@Self privateResource resource;
@Model(adaptables = SlingHttpServletRequest.class)
public class SlingModelDemo {
@SlingObject private Resource resource;
@SlingObject private ResourceResolver resolver;
@SlingObject private SlingHttpServletRequest request;
}
Injects resource from given path
@ResourcePath(path="/path/to/resource")
• Self Injector (self)
• Sling Object Injector (sling-object)
• Resource Path Injector (resource-path)
Standard Injectors in 1.1.x
Injectors (with @Source names)
• Can use customized annotations with following advantages over
using the standard annotations:
- Less code to write (only one annotation is necessary in most of
the cases)
- More robust
• Injector Specific Annotation specifies source explicitly
• Example
@ValueMapValue String name;
@ValueMapValue (name="jcr:title", optional=true)
String title;
Injector-specific Annotations (Since
Sling Models Impl 1.0.6)
Annotation
Supported Optional
Elements
Injector
@ScriptVariable optional and name script-bindings
@ValueMapValue optional, name and via valuemap
@ChildResource optional, name and via child-resources
@RequestAttribute optional, name and via request-attributes
@ResourcePath
optional, path,
and name
resource-path
@OSGiService optional, filter osgi-services
@Self optional self
@SlingObject optional sling-object
Injectors depicted in Felix Console
Using Sling Models with Sightly and JSP
• OOTB supported in AEM 6 and above with
org.apache.sling.models.api package already present in AEM
instance
• For other version download package from
http://sling.apache.org/downloads.cgi and install in AEM instance
• Maven dependency can be found at
http://<host>:<port>/system/console/depfinder , search for
org.apache.sling.models.annotations.Model
<dependency> <groupId>org.apache.sling</groupId>
<artifactId>org.apache.sling.models.api</artifactId>
<version>1.0.0</version> <scope>provided</scope>
</dependency>
Dependency
• Search for maven-bundle-plugin in pom.xml file , update it with
following
- <Sling-Model-Packages> com.slingmodels.core </Sling-Model-
Packages>
- It is because for Sling Model classes to be picked up this header
must be added to the bundle's manifest
Dependency Cont…
• Sling Model class object can be used in JSP by either
- <c:set var ="mycomp" value="<%=
resource.adaptTo(SlingModelDemo.class)%>" />
Or by using
- <sling:adaptTo adaptable="${resource}"
adaptTo="com.slingmodels.core. SlingModelDemo"
var=“mycomp"/>
Sling Models with JSP
• Sightly is a beautiful mark up language providing advantages like
separation of concerns , prevents xss vulnerabilities .
• Sling Model class object can be used in Sightly by :
<div data-sly-use.mycomp="
com.slingmodels.core.SlingModelDemo">
Sling Models with Sightly
Demo
Code can be found at:
https://github.com/deepakkhetawat/SlingModel-Demo.git
Where is the Code
Appendix and Q&A
• https://sling.apache.org/documentation/bundles/models.html
• Google ..
Appendix
For more information contact:
DEEPAK KHETAWAT
M +91-9910941818
deepak.khetawat@tothenew.com
Thank you

More Related Content

What's hot

HTL(Sightly) - All you need to know
HTL(Sightly) - All you need to knowHTL(Sightly) - All you need to know
HTL(Sightly) - All you need to know
Prabhdeep Singh
 
Rest and Sling Resolution
Rest and Sling ResolutionRest and Sling Resolution
Rest and Sling Resolution
DEEPAK KHETAWAT
 

What's hot (20)

HTL(Sightly) - All you need to know
HTL(Sightly) - All you need to knowHTL(Sightly) - All you need to know
HTL(Sightly) - All you need to know
 
AEM and Sling
AEM and SlingAEM and Sling
AEM and Sling
 
JCR, Sling or AEM? Which API should I use and when?
JCR, Sling or AEM? Which API should I use and when?JCR, Sling or AEM? Which API should I use and when?
JCR, Sling or AEM? Which API should I use and when?
 
AEM Rich Text Editor (RTE) Deep Dive
AEM Rich Text Editor (RTE) Deep DiveAEM Rich Text Editor (RTE) Deep Dive
AEM Rich Text Editor (RTE) Deep Dive
 
Introduction to Sightly and Sling Models
Introduction to Sightly and Sling ModelsIntroduction to Sightly and Sling Models
Introduction to Sightly and Sling Models
 
Adobe Experience Manager Core Components
Adobe Experience Manager Core ComponentsAdobe Experience Manager Core Components
Adobe Experience Manager Core Components
 
Rest and Sling Resolution
Rest and Sling ResolutionRest and Sling Resolution
Rest and Sling Resolution
 
Heap Dump Analysis - AEM: Real World Issues
Heap Dump Analysis - AEM: Real World IssuesHeap Dump Analysis - AEM: Real World Issues
Heap Dump Analysis - AEM: Real World Issues
 
Web assembly: a brief overview
Web assembly: a brief overviewWeb assembly: a brief overview
Web assembly: a brief overview
 
Omnisearch in AEM 6.2 - Search All the Things
Omnisearch in AEM 6.2 - Search All the ThingsOmnisearch in AEM 6.2 - Search All the Things
Omnisearch in AEM 6.2 - Search All the Things
 
WebAssembly WASM Introduction Presentation
WebAssembly WASM Introduction PresentationWebAssembly WASM Introduction Presentation
WebAssembly WASM Introduction Presentation
 
Aem Training Tutorials for Beginners
Aem  Training Tutorials for BeginnersAem  Training Tutorials for Beginners
Aem Training Tutorials for Beginners
 
Javascript best practices
Javascript best practicesJavascript best practices
Javascript best practices
 
Spring boot
Spring bootSpring boot
Spring boot
 
JavaScript for ABAP Programmers - 1/7 Introduction
JavaScript for ABAP Programmers - 1/7 IntroductionJavaScript for ABAP Programmers - 1/7 Introduction
JavaScript for ABAP Programmers - 1/7 Introduction
 
Spring ppt
Spring pptSpring ppt
Spring ppt
 
Spring Framework - MVC
Spring Framework - MVCSpring Framework - MVC
Spring Framework - MVC
 
AEM (CQ) Dispatcher Security and CDN+Browser Caching
AEM (CQ) Dispatcher Security and CDN+Browser CachingAEM (CQ) Dispatcher Security and CDN+Browser Caching
AEM (CQ) Dispatcher Security and CDN+Browser Caching
 
Aem dispatcher – tips & tricks
Aem dispatcher – tips & tricksAem dispatcher – tips & tricks
Aem dispatcher – tips & tricks
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with Spring
 

Similar to Sling Models Using Sightly and JSP by Deepak Khetawat

13 java beans
13 java beans13 java beans
13 java beans
snopteck
 
Pluggable patterns
Pluggable patternsPluggable patterns
Pluggable patterns
Corey Oordt
 
Playing with Java Classes and Bytecode
Playing with Java Classes and BytecodePlaying with Java Classes and Bytecode
Playing with Java Classes and Bytecode
Yoav Avrahami
 
Ajax Tags Advanced
Ajax Tags AdvancedAjax Tags Advanced
Ajax Tags Advanced
AkramWaseem
 
Session 3 - Object oriented programming with Objective-C (part 1)
Session 3 - Object oriented programming with Objective-C (part 1)Session 3 - Object oriented programming with Objective-C (part 1)
Session 3 - Object oriented programming with Objective-C (part 1)
Vu Tran Lam
 
070517 Jena
070517 Jena070517 Jena
070517 Jena
yuhana
 

Similar to Sling Models Using Sightly and JSP by Deepak Khetawat (20)

Deepak khetawat sling_models_sightly_jsp
Deepak khetawat sling_models_sightly_jspDeepak khetawat sling_models_sightly_jsp
Deepak khetawat sling_models_sightly_jsp
 
Eclipse e4
Eclipse e4Eclipse e4
Eclipse e4
 
Eclipse 40 - Eclipse Summit Europe 2010
Eclipse 40 - Eclipse Summit Europe 2010Eclipse 40 - Eclipse Summit Europe 2010
Eclipse 40 - Eclipse Summit Europe 2010
 
How to train the jdt dragon
How to train the jdt dragonHow to train the jdt dragon
How to train the jdt dragon
 
Handlebars & Require JS
Handlebars  & Require JSHandlebars  & Require JS
Handlebars & Require JS
 
Learn about Eclipse e4 from Lars Vogel at SF-JUG
Learn about Eclipse e4 from Lars Vogel at SF-JUGLearn about Eclipse e4 from Lars Vogel at SF-JUG
Learn about Eclipse e4 from Lars Vogel at SF-JUG
 
Design patterns
Design patternsDesign patterns
Design patterns
 
13 java beans
13 java beans13 java beans
13 java beans
 
Prototype-1
Prototype-1Prototype-1
Prototype-1
 
Prototype-1
Prototype-1Prototype-1
Prototype-1
 
A Dexterity Intro for Recovering Archetypes Addicts
A Dexterity Intro for Recovering Archetypes AddictsA Dexterity Intro for Recovering Archetypes Addicts
A Dexterity Intro for Recovering Archetypes Addicts
 
Handlebars and Require.js
Handlebars and Require.jsHandlebars and Require.js
Handlebars and Require.js
 
Pluggable patterns
Pluggable patternsPluggable patterns
Pluggable patterns
 
Field injection, type safe configuration, and more new goodies in Declarative...
Field injection, type safe configuration, and more new goodies in Declarative...Field injection, type safe configuration, and more new goodies in Declarative...
Field injection, type safe configuration, and more new goodies in Declarative...
 
Playing with Java Classes and Bytecode
Playing with Java Classes and BytecodePlaying with Java Classes and Bytecode
Playing with Java Classes and Bytecode
 
Ajax Tags Advanced
Ajax Tags AdvancedAjax Tags Advanced
Ajax Tags Advanced
 
Session 3 - Object oriented programming with Objective-C (part 1)
Session 3 - Object oriented programming with Objective-C (part 1)Session 3 - Object oriented programming with Objective-C (part 1)
Session 3 - Object oriented programming with Objective-C (part 1)
 
Spring Framework Presantation Part 1-Core
Spring Framework Presantation Part 1-CoreSpring Framework Presantation Part 1-Core
Spring Framework Presantation Part 1-Core
 
070517 Jena
070517 Jena070517 Jena
070517 Jena
 
Aem best practices
Aem best practicesAem best practices
Aem best practices
 

More from AEM HUB

Socialize your Exceptional Web Experience – Adobe AEM & IBM Connections by He...
Socialize your Exceptional Web Experience – Adobe AEM & IBM Connections by He...Socialize your Exceptional Web Experience – Adobe AEM & IBM Connections by He...
Socialize your Exceptional Web Experience – Adobe AEM & IBM Connections by He...
AEM HUB
 
Sightly Beautiful Markup by Senol Tas
Sightly Beautiful Markup by Senol Tas Sightly Beautiful Markup by Senol Tas
Sightly Beautiful Markup by Senol Tas
AEM HUB
 

More from AEM HUB (20)

Microservices for AEM by Maciej Majchrzak
Microservices for AEM by Maciej MajchrzakMicroservices for AEM by Maciej Majchrzak
Microservices for AEM by Maciej Majchrzak
 
When dispatcher caching is not enough by Jakub Wądołowski
When dispatcher caching is not enough by Jakub WądołowskiWhen dispatcher caching is not enough by Jakub Wądołowski
When dispatcher caching is not enough by Jakub Wądołowski
 
PhoneGap Enterprise Viewer by Anthony Rumsey
PhoneGap Enterprise Viewer by Anthony RumseyPhoneGap Enterprise Viewer by Anthony Rumsey
PhoneGap Enterprise Viewer by Anthony Rumsey
 
Integrating Apache Wookie with AEM by Rima Mittal and Ankit Gubrani
Integrating Apache Wookie with AEM by Rima Mittal and Ankit GubraniIntegrating Apache Wookie with AEM by Rima Mittal and Ankit Gubrani
Integrating Apache Wookie with AEM by Rima Mittal and Ankit Gubrani
 
Mastering the Sling Rewriter by Justin Edelson
Mastering the Sling Rewriter by Justin EdelsonMastering the Sling Rewriter by Justin Edelson
Mastering the Sling Rewriter by Justin Edelson
 
Building Quality into the AEM Publication Workflow with Active Standards by D...
Building Quality into the AEM Publication Workflow with Active Standards by D...Building Quality into the AEM Publication Workflow with Active Standards by D...
Building Quality into the AEM Publication Workflow with Active Standards by D...
 
Touching the AEM component dialog by Mateusz Chromiński
Touching the AEM component dialog by Mateusz ChromińskiTouching the AEM component dialog by Mateusz Chromiński
Touching the AEM component dialog by Mateusz Chromiński
 
How to build a Social Intranet with Adobe Sites and 3rd Party products ... us...
How to build a Social Intranet with Adobe Sites and 3rd Party products ... us...How to build a Social Intranet with Adobe Sites and 3rd Party products ... us...
How to build a Social Intranet with Adobe Sites and 3rd Party products ... us...
 
How do you build flexible platforms that focuses on business needs? by Fahim...
How do you build flexible platforms that focuses on business needs?  by Fahim...How do you build flexible platforms that focuses on business needs?  by Fahim...
How do you build flexible platforms that focuses on business needs? by Fahim...
 
AEM Apps Enhanced: In-app Messaging and Beacons by John Fait
AEM Apps Enhanced: In-app Messaging and Beacons by John FaitAEM Apps Enhanced: In-app Messaging and Beacons by John Fait
AEM Apps Enhanced: In-app Messaging and Beacons by John Fait
 
Effectively Scale and Operate AEM with MongoDB by Norberto Leite
Effectively Scale and Operate AEM with MongoDB by Norberto LeiteEffectively Scale and Operate AEM with MongoDB by Norberto Leite
Effectively Scale and Operate AEM with MongoDB by Norberto Leite
 
Adobe Managed Services: Complicated Cloud Deployments by Adam Pazik, Mike Til...
Adobe Managed Services: Complicated Cloud Deployments by Adam Pazik, Mike Til...Adobe Managed Services: Complicated Cloud Deployments by Adam Pazik, Mike Til...
Adobe Managed Services: Complicated Cloud Deployments by Adam Pazik, Mike Til...
 
Adobe Marketing Cloud Integrations: Myth or Reality? by Holger Marsen
Adobe Marketing Cloud Integrations: Myth or Reality? by Holger MarsenAdobe Marketing Cloud Integrations: Myth or Reality? by Holger Marsen
Adobe Marketing Cloud Integrations: Myth or Reality? by Holger Marsen
 
Responsive Websites and Grid-Based Layouts by Gabriel Walt
Responsive Websites and Grid-Based Layouts by Gabriel Walt Responsive Websites and Grid-Based Layouts by Gabriel Walt
Responsive Websites and Grid-Based Layouts by Gabriel Walt
 
When Sightly Meets Slice by Tomasz Niedźwiedź
When Sightly Meets Slice by Tomasz NiedźwiedźWhen Sightly Meets Slice by Tomasz Niedźwiedź
When Sightly Meets Slice by Tomasz Niedźwiedź
 
Creativity without comprise by Cleve Gibbon
Creativity without comprise by Cleve Gibbon Creativity without comprise by Cleve Gibbon
Creativity without comprise by Cleve Gibbon
 
REST in AEM by Roy Fielding
REST in AEM by Roy FieldingREST in AEM by Roy Fielding
REST in AEM by Roy Fielding
 
Adobe Summit 2015 - Penguin Random House - Accelerating Digital Transformation
Adobe Summit 2015 - Penguin Random House - Accelerating Digital TransformationAdobe Summit 2015 - Penguin Random House - Accelerating Digital Transformation
Adobe Summit 2015 - Penguin Random House - Accelerating Digital Transformation
 
Socialize your Exceptional Web Experience – Adobe AEM & IBM Connections by He...
Socialize your Exceptional Web Experience – Adobe AEM & IBM Connections by He...Socialize your Exceptional Web Experience – Adobe AEM & IBM Connections by He...
Socialize your Exceptional Web Experience – Adobe AEM & IBM Connections by He...
 
Sightly Beautiful Markup by Senol Tas
Sightly Beautiful Markup by Senol Tas Sightly Beautiful Markup by Senol Tas
Sightly Beautiful Markup by Senol Tas
 

Recently uploaded

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
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
 

Recently uploaded (20)

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
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
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
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
 
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...
 
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
 
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
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
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
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 

Sling Models Using Sightly and JSP by Deepak Khetawat

  • 1. Sling Models Using Sightly and JSP DEEPAK KHETAWAT
  • 3. What & Why Sling Models? - Introduction to Sling Models - Need and Essence of Sling Models - Design Goals Sling Model Annotations - Annotations Usage Sling Model Injectors - Injectors available in 1.0.x and 1.1.x - Custom Injectors - Injectors Usage Agenda Usage of Sling Models with Sightly and JSP - Sling Models dependencies - How to use Sling Models with JSP ? - How to use Sling Models with Sightly? Demo - Functionality Demo Appendix and Q&A - Appendix - Q&A
  • 4. What & Why Sling Models
  • 5. • Sling Models are POJO’s which are automatically mapped from Sling objects, typically resources, request objects. Sometimes these POJOs need OSGi services as well What are Sling Models?
  • 6. • Entirely annotation driven. "Pure" POJOs • Adapt multiple objects • Work with existing Sling infrastructure • Client doesn't know/care that these objects are different than any other adapter factory • Support both classes and interfaces • Pluggable Design Goals
  • 7. • Saves from creating own adapters • Context aware Dependency Injection Framework • Do More with Less Code making Code Readable and Removing Redundant (Boiler Plate) Code • Highly Testable Code - Sling Model Inject Annotations defines the dependency contract - Mock dependencies with tools like Mockito @InjectMocks Why Sling Models ?
  • 9. Annotations Usage Sling Model Annotation Code Snippet Description @Model @Model(adaptables = Resource.class) Class is annotated with @Model and the adaptable class @Inject @Inject private String propertyName; (class ) @Inject String getPropertyName(); (interface ) A property named "propertyName" will be looked up from the Resource (after first adapting it to a ValueMap) and it is injected , else will return null if property not found . @Default @Inject @Default(values = "AEM") private String technology; A default value (for Strings , Arrays , primitives etc. ) @Optional @Inject @Optional private String otherName. @Injected fields/methods are assumed to be required. To mark them as optional, use @Optional i.e resource or adaptable may or may not have property .
  • 10. Annotations Usage Cont... Sling Model Annotation Code Snippet Description @Named @Inject @Named("title") private String pageTitle; Inject a property whose name does NOT match the Model field name @Via @Model(adaptables=SlingHttpServletRequest.class) public interface SlingModelDemo { @Inject @Via("resource") String getPropertyName(); } Use a JavaBean property of the adaptable as the source of the injection // Code Snippet will return request.getResource().adaptTo(ValueMap.class).get("propertyNam e", String.class) @Source @Model(adaptables=SlingHttpServletRequest.class) @Inject @Source("script-bindings") Resource getResource(); } Explicitly tie an injected field or method to a particular injector (by name). Can also be on other annotations //Code snippet will ensure that "resource" is retrieved from the bindings, not a request attribute @PostConstruct @PostConstruct protected void sayHello() { logger.info("hello"); } Methods to call upon model option creation (only for model classes)
  • 12. • Injectors are OSGi services implementing the org.apache.sling.models.spi.Injector interface • Injectors are invoked in order of their service ranking, from lowest to highest. What are Injectors ?
  • 13. • Script Bindings (script-bindings) • Value Map (valuemap) • Child Resources (child-resources) • Request Attributes (request-attributes) • OSGI Service References (osgi-services) Standard Injectors in 1.0.x Injectors (with @Source names)
  • 14. Injects adaptable itself or an object that can be adapted from adaptable @Self privateResource resource; @Model(adaptables = SlingHttpServletRequest.class) public class SlingModelDemo { @SlingObject private Resource resource; @SlingObject private ResourceResolver resolver; @SlingObject private SlingHttpServletRequest request; } Injects resource from given path @ResourcePath(path="/path/to/resource") • Self Injector (self) • Sling Object Injector (sling-object) • Resource Path Injector (resource-path) Standard Injectors in 1.1.x Injectors (with @Source names)
  • 15. • Can use customized annotations with following advantages over using the standard annotations: - Less code to write (only one annotation is necessary in most of the cases) - More robust • Injector Specific Annotation specifies source explicitly • Example @ValueMapValue String name; @ValueMapValue (name="jcr:title", optional=true) String title; Injector-specific Annotations (Since Sling Models Impl 1.0.6) Annotation Supported Optional Elements Injector @ScriptVariable optional and name script-bindings @ValueMapValue optional, name and via valuemap @ChildResource optional, name and via child-resources @RequestAttribute optional, name and via request-attributes @ResourcePath optional, path, and name resource-path @OSGiService optional, filter osgi-services @Self optional self @SlingObject optional sling-object
  • 16. Injectors depicted in Felix Console
  • 17. Using Sling Models with Sightly and JSP
  • 18. • OOTB supported in AEM 6 and above with org.apache.sling.models.api package already present in AEM instance • For other version download package from http://sling.apache.org/downloads.cgi and install in AEM instance • Maven dependency can be found at http://<host>:<port>/system/console/depfinder , search for org.apache.sling.models.annotations.Model <dependency> <groupId>org.apache.sling</groupId> <artifactId>org.apache.sling.models.api</artifactId> <version>1.0.0</version> <scope>provided</scope> </dependency> Dependency
  • 19. • Search for maven-bundle-plugin in pom.xml file , update it with following - <Sling-Model-Packages> com.slingmodels.core </Sling-Model- Packages> - It is because for Sling Model classes to be picked up this header must be added to the bundle's manifest Dependency Cont…
  • 20. • Sling Model class object can be used in JSP by either - <c:set var ="mycomp" value="<%= resource.adaptTo(SlingModelDemo.class)%>" /> Or by using - <sling:adaptTo adaptable="${resource}" adaptTo="com.slingmodels.core. SlingModelDemo" var=“mycomp"/> Sling Models with JSP
  • 21. • Sightly is a beautiful mark up language providing advantages like separation of concerns , prevents xss vulnerabilities . • Sling Model class object can be used in Sightly by : <div data-sly-use.mycomp=" com.slingmodels.core.SlingModelDemo"> Sling Models with Sightly
  • 22. Demo
  • 23. Code can be found at: https://github.com/deepakkhetawat/SlingModel-Demo.git Where is the Code
  • 26. For more information contact: DEEPAK KHETAWAT M +91-9910941818 deepak.khetawat@tothenew.com Thank you