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)

Testing RESTful Webservices using the REST-assured framework
Testing RESTful Webservices using the REST-assured frameworkTesting RESTful Webservices using the REST-assured framework
Testing RESTful Webservices using the REST-assured framework
 
Introduction to Sightly and Sling Models
Introduction to Sightly and Sling ModelsIntroduction to Sightly and Sling Models
Introduction to Sightly and Sling Models
 
AEM Sightly Template Language
AEM Sightly Template LanguageAEM Sightly Template Language
AEM Sightly Template Language
 
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 Sightly Deep Dive
AEM Sightly Deep DiveAEM Sightly Deep Dive
AEM Sightly Deep Dive
 
Sling Models Overview
Sling Models OverviewSling Models Overview
Sling Models Overview
 
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
 
Rest and Sling Resolution
Rest and Sling ResolutionRest and Sling Resolution
Rest and Sling Resolution
 
JUnit 5
JUnit 5JUnit 5
JUnit 5
 
Aem dispatcher – tips & tricks
Aem dispatcher – tips & tricksAem dispatcher – tips & tricks
Aem dispatcher – tips & tricks
 
Dynamic Components using Single-Page-Application Concepts in AEM/CQ
Dynamic Components using Single-Page-Application Concepts in AEM/CQDynamic Components using Single-Page-Application Concepts in AEM/CQ
Dynamic Components using Single-Page-Application Concepts in AEM/CQ
 
Spring andspringboot training
Spring andspringboot trainingSpring andspringboot training
Spring andspringboot training
 
Using hilt in a modularized project
Using hilt in a modularized projectUsing hilt in a modularized project
Using hilt in a modularized project
 
Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans
 
Osgi
OsgiOsgi
Osgi
 
Test Design and Automation for REST API
Test Design and Automation for REST APITest Design and Automation for REST API
Test Design and Automation for REST API
 
Spring annotations notes
Spring annotations notesSpring annotations notes
Spring annotations notes
 
Managing user's data with Spring Session
Managing user's data with Spring SessionManaging user's data with Spring Session
Managing user's data with Spring Session
 
Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.
 
Integration patterns in AEM 6
Integration patterns in AEM 6Integration patterns in AEM 6
Integration patterns in AEM 6
 

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

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 

Recently uploaded (20)

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech 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
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
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
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
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
 
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
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 

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