SlideShare a Scribd company logo
Building Enterprise Web Applications with Spring 3.0 and Spring 3.0 MVC JavaOne 2010ByAbdelmonaimRemaniabdelmonaim.remani@gmail.com
Creative Commons Attribution-NonCommercial 3.0 Unportedhttp://creativecommons.org/licenses/by-nc/3.0/License
Software Engineer at Overstock.comParticularly interested in technology evangelism and enterprise software development and architecturePresident and Founder of a number of organizationsThe Chico Java User GroupThe Chico Flex User Group,The Chico Google Technology User Group.LinkedInhttp://www.linkedin.com/in/polymathiccoderTwitterhttp://twitter.com/polymathiccoderWho Am I?
WarningThis presentation is very long and covers a lot of material
Introduction
ComplexIn terms of requirementsFunctionalNon-FunctionalExecutionPerformanceReliabilitySecurityEvolutionTestabilityMaintainabilityExtendibilityScalability (Horizontal and Vertical)Enterprise Application Software (EAS)
In the words of Edsger W. Dijkstra:[…] The Separation of Concerns […] is yet the only available technique for effective ordering of one’s thoughts […]Artificially Reducing complexity by means of AbstractionSpecific Choices of abstractionProduces a architecturesEnterprise Application Software (EAS)
The ArchitectureLayered / N-TieredPresentation LayerWeb LayerService LayerPersistence LayerAspectsMiddlewareOtherModern Enterprise Application
A Framework is an architectureA well-defined structure to solve a problemA pre-existing hierarchy to be extendedLibraryFramework vs. LibraryInvoking vs. being invokedGeneric vs. specificToolsCompiler, debugger, etc…Scaffolding and other utilitiesEtc…Frameworks
Heavyweight vs. LightweightThe need for a platform or a stack (JEE as example)The ability to load in-demand necessary componentsThe memory footprintThe build sizeDeployment easeEtc…Frameworks
The Spring Framework
Application FrameworkJavaOther implementations are available (Spring .NET)Open-SourceLightweightNon-Invasive (POJO Based)ExtendibleA platform with well-defined extension points for other frameworksBy Rod JohnsonExpert One-on-One J2EE Design and Development, 2002J2EE without EJB, 2004Became the De facto standard of Java Enterprise ApplicationsWhat is Spring?
20 ModulesSpringSource:  Spring 3.0.x Framework Referencehttp://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/htmlsingle/spring-framework-reference.html
Wrappers for most popular frameworksAllowing injection of dependencies into standard implementationStrutsJSFApache TapestryEtc…Full Integration with the JEE stackLibraries
The Address Book
The Address Book from polymathic-coder.comA web application for Contact managementThe Address Book
Details:As a user I should be able to view, add, delete, and edit personal contacts data on my address book including:First NameLast NameEmailPhone NumberImagePrimary Actors: Regular user / AdministratorAssumptions: The user is authenticated and has proper privileges to access the Contact Management AreaAccess is granted both through the web interface and a RESTful APIFunctional RequirementsUse Case 1 - Contact Management
Business RulesA First Names are requiredPhone Numbers must be valid US phone numbersEmails must be validFunctional RequirementsUse Case 1 - Contact Management
Details:As an administrator I should be able to view, add, delete, and edit the user data including:UsernamePasswordRole (Regular or Administrator)Whether the account is enabled or notEmailPrimary Actors: AdministratorAssumptions:The user is authenticated and has proper privileges to access the User Administration AreaAccess is granted through the web interfaceFunctional RequirementsUse Case 2 - User Management
Business RulesUsername is required and must be uniquePasswords must be complex (The should contains at least 1 lowercase letter, 1 uppercase letter, 1 digit, and 1 special character)Emails must be validAn email must be sent to the newly created userFunctional RequirementsUse Case 2 - User Management
Details:As an administrator I should be able to view audit and health check reportsPrimary Actors: AdministratorAssumptions:The user is authenticated and has proper privileges to access the Reporting AreaAccess is granted through the web interfaceThe reports are periodically generated by the systemFunctional RequirementsUse Case 3 - Reporting
RBAC (Role-based access control)AuthenticationForm-basedHttp BasicAuthorizationSecurity RolesRegular UserAccess to personal contact management areaAdministratorsAccess to personal contact management areaAccess to user administration areaAccess to reporting areaAccess ControlNo RulesTransport SecurityNot requiredNon-Functional Requirements Security
Spring Core
The problem:Acquiring Resources viaInstantiation of a concrete classUsing a static method of a singleton factoryUsing a Directory Services API that allows for discovery and lookup (JNDI for example)Etc..Creates hard dependenciesCoupled code is hard to reuse (DRYness)Painful Unit TestingInversion of Control
The Solution:Coding against InterfacesInversion of Control: Dependency InjectionReflectively supply external dependency at runtimeThe Hollywood principle: “Don’t call us, we’ll call you”Wait a minute this a lot of work!Spring to the rescueInversion of Control
Container POJOConfiguration MetadataXML-BasedAnnotation-BasedJava-basedSpring CoreSource:  Spring 3.0.x Framework Referencehttp://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/htmlsingle/spring-framework-reference.html
JSR 330 – Dependency Injection for Java JSR 330@Inject@NamedSpring Annotations@Autowire@QualifierJSR 250 -  Common Annotationsjavax.annotationJSR 299 – Contexts and Dependency InjectionScopes and contexts: javax.contextDependency injection service: javax.injectFramework integration SPI: javax.inject.managerEvent notification service: javax.event
Used to mark a class that fulfills a role or a stereotypeStereotyped classes can be automatically detectedSpring Stereotypes@Component@Repository@Service@ControllerStereotypical Spring
Domain Model
Domain Model
A model of the “concepts” involved in the system and their relationshipsAnemic Domain ModelPOJOs (Plain Old Java Objects) or VOs (Value Objects)Clear separation between logic and dataParallel object hierarchies are evilMetadata is interpreted depending on the context as the object moves across the layers of the applicationObject-Relational mapping to persistent entitiesValidationMarshaling / Un-marshalingEtc…Domain Model
Ensuring the correctness of data based on a set predefined rulesJSR 303 - Bean ValidationSource:  Hibernate Validator Reference Guide 4.1.0.Finalhttp://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/
javax.validationReference Implementation: Hibernate ValidatorJSR 303 - Bean ValidationSource:  Hibernate Validator Reference Guide 4.1.0.Finalhttp://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/
Instantiation (Items 1 & 2 of Josh Bloch’s Effective Java)Static FactoriesTelescopingProvide buildersOverride the default implementations of hashCode(), toString(), and equals(Object) methodsUse Pojomatic at http://pojomatic.sourceforge.net/Be aware of any circular dependency in your modelVersioning@Version  of JSR 317 – JPA 2.0Domain Model
Persistence Layer
A logical encapsulation of classes and interfaces whose responsibilities fall within the scope of:Create, Read, Update, and Delete (CRUD) operations on persistence storage mechanisms such as file systems and Database Management Systems (DBMS)Interacting with Message-Oriented Middleware (MOM) infrastructures or Message Transfer Agents (MTA) such as JMS or mail serversPersistence Layer
javax.persistenceReference Implementation EclipseLinkPrimerA persistence entity is a POJO whose state is persisted to a table in a relational database according to predefined ORM metadataAn entity is managed by an Entity ManagerDo we still need a Persistence Layer?HighlightsSupport for JSR 303 validationJSR 317 – JPA 2.0
Beans Stereotyped with @RepositoryEnables exception translation to a consistent exception hierarchyRun-time exceptions and do not have to be declared or caughtUse JPA annotations to inject EntityManager and EntityManagerFactory@PersistenceContext@PersistenceUnitFollow a convention (I suggest CRUD)Declaring transaction semantics@TransactionalSpring Data Access / Integration
Java Mail APIjavax.mailSpring Helpers for various Templating EnginesVelocityFreeMarkerSpring Data Access / Integration
TestingJUnitTake advantage of what JUnit 4.7 has to offer (Explore Theories, Rules, Etc…) LibrariesDbUnithttp://www.dbunit.org/Dumpster http://quintanasoft.com/dumbster/Consider HADES http://redmine.synyx.org/projects/show/hadesPersistence Layer
Service Layer
A logical encapsulation of classes and interfaces that provide the system functionality consolidating Units of work. Service layer classes should be:Transactional StatelessBeans Stereotyped with @ServiceFollow a convention (I suggest VADER)Service Layer
Web Layer
A logical encapsulation of classes and interfaces whose responsibilities fall within the scope of:Navigational logicRendering page views in the proper orderAs simple as mapping a single URL to a single pageAs complex as a full work flow engineWeb concerns (Request variables, session variables, HTTP methods, HTTP response codes, Etc…) should be separated from business logicWeb Layer
Two types of Web FrameworksRequest / Response Web FrameworksWrap the Servlet APIAdopt push modelCompile resultPush it out to be rendered in a viewStruts, Spring MVC, Etc…Component Web FrameworksDot only hide the Servlet APIEvent-driven componentJSF, Tapestry, Etc…Web Layer
Spring MVC
Request / Response Web FrameworksA Front Controller PatternOne Dispatcher servletApplication ContextsApplication ContextWeb Application ContextSpring MVC
The promise Non-invasivenessFully annotation-drivenNo extension of framework classes No overriding methodsControllersBeans (Spring Managed-POJOs) Stereotyped with @ControllerSpring MVC - Controllers
Mapping Rules@RequestMappingByPathHTTP methodQuery ParametersRequest  HeadersSpring MVC - Controllers
Handler MethodsParameters are request inputsRequest data@RequestParam@PathVariable@RequestHeader@CookieValueCommand Objects (Domain Objects)Injection of standard objectsAutomatic Type ConversionCustom Type ConversionJSR 303 Support@ValidExposing reference data to the views@ModelAttributeSpring MVC - Controllers
RESTfulSpring MVC 3.0
Representational State TransferArchitectural StyleIdentifiable ResourcesEverything is a resource accessible URIUniform Interface based on HTTP methodsGET /contacts 		reads all contactsGET /contacts/1 		reads the contact whose id is 1POST /contacts		creates a contact PUT /contacts/1	updates the contact whose id is 1DELETE /contacts/1	deletes the contact whose id is 1	RESTful Architecture
Architectural StyleResource RepresentationsMultiple data representation (MIME types) can be specifiedRequestAccept HTTP header field or file extensionResponseContent-Type HTTP header fieldStateless ConversionNo sessionScalableLoosely coupledRESTful Architecture
Annotations@RequestMapping@PathVariable@RequestBody@ResponceBodySpring OXM (Object-XML Mapping)Marshaling / UnmarshalingRESTful Spring
Presentation Layer
“Deciding to use Velocity or XSLT in place of an existing JSP is primarily a matter of configuration” Spring 3.0 DocumentationView technologiesJSP & JSTLTilesVelocityFreeMarkerXSLTJasperReportsEtc…Spring MVC - Views
Views are rendered based on handler methods return@ResponseBody or ResponseEntity<T>Many HttpMessageConvertersStringHttpMessageConverterJaxb2RootElementHttpMessageConverterMappingJacksonHttpMessageConverterAtomFeed/RssChannelHttpMessageConverterEtc…Register your ownStringView Resolver and a ViewSpring MVC - Views
View ResolversInternalResourceViewResolverContentNegotiatingViewResolverBeanNameViewResolverJasperReportsViewResolverTilesViewResolverEtc…Spring MVC - Views
JSP & JSTLSpring Tag LibrarySpring Form Tag LibraryRefer to spring-form.tldThemesOverall look-and-feel of your applicationA collection of style sheets and images<spring:theme />Theme resolversI18NSpring MVC - Views
Spring Web FlowFor Web Application that areMore dynamicNon-linear without arbitrary end pointsSpring Portlet MVCA JSR 168 compliant Portlet environnentLarge web application composed with subcomponents on the same web pageSpring MVC Complements
Aspects
Spring AOP
OOP creates a hierarchical object model by natureCross cutting concernsAre not necessarily a part of the application logicOccur across the object hierarchy in unrelated partsExamplesLoggingSecurityTransaction managementEtc…Aspect-Oriented Programming
The ProblemCode TanglingNo CohesionCode ScatteringNot DRYThe SolutionAspect Oriented ProgrammingAspectJModulation of Aspects and weaving into the application codeAspect Oriented Programming
Spring AOPJava based AOP FrameworkBuilt on top of AspectJInterception basedSpring APO
Joint PointA point in the execution of the programPoint CutAn expression that selects one or more joint pointAspectJ Expression LanguageAdviceThe code to be weaved at a joint pointAspectPoint Cut + AdviceAOP Terminology
AnnotationsBeforeAfterReturningAfterThrowingAfterAroundTypes of Advices
Spring Security
Authenticationthe verification of the user identityAuthorizationPermissions granted to the identified userAccess ControlBy arbitrary conditions that may depend to Attributes of clientsTemporal and Local ConditionHuman User DetectionOtherChannel or Transport SecurityEncryptionSecurity Terminology
RealmA Defined the authentication policyUserA defined individual in the Application ServerGroupA defined classification of users by common traits in the Application Server.RoleAn abstract name of the permissions to access a particular set of resources in an applicationSecurity Terminology
Spring SecurityJAAS (Java Authentication and Authorization Service)jGuardApache ShiroAvailable Frameworks
Security is your responsibilityFeatures:It is not the standardNo class loader authorization capabilitiesSimple configurationPortable across containersCustomizable and extendablePluggable authentication and web request URI securitySupport method interception, Single Sign-On, and Swing clientsSpring Security
AuthenticationForm-BasedBasicDigestLDAPNTLM (NT LAN Manager)SSO (Single Sign-On)JA-SIG CASOpen IDAtlassian CrowdSiteMinderX.509Authentication
MechanismsInteract with the userProvidersCheck credentialsBundles details in a Thread Local security context holderRepositoriesStore roles and profile infoIn MemoryJDBCLDAPEtc…Authentication
Web AuthorizationURL-BasedWhich URL patterns and HTTP methods are allowed to be accessed by which roleMethod AuthorizationReusableProtocol AgnosticUses AOPAnnotations SupportJSR 250Spring @SecuredSpring Security ELAuthorization
Other
Job SchedulingBulk Processing IntegrationEtc…Other
If you are interested inThe full-source code of the Address Book ApplicationA Step-By-Step tutorialPossibly a screen castGo tohttp://bit.ly/ad4VGhSupport Material
The Silicon Valley Spring User Grouphttp://www.meetup.com/sv-sug
Q & A
Thank You!

More Related Content

PPTX
How RESTful Is Your REST?
PPTX
Introduction To Building Enterprise Web Application With Spring Mvc
PDF
Rest web service
PDF
Spring aop
PDF
Exploring Maven SVN GIT
PPTX
J2ee seminar
DOCX
Hibernate notes
PPTX
Introduction to Ibatis by Rohit
How RESTful Is Your REST?
Introduction To Building Enterprise Web Application With Spring Mvc
Rest web service
Spring aop
Exploring Maven SVN GIT
J2ee seminar
Hibernate notes
Introduction to Ibatis by Rohit

What's hot (20)

PDF
Hibernate Advance Interview Questions
PDF
Java j2ee interview_questions
DOCX
J2EE Architecture Explained
PPT
Dh2 Apps Training Part2
PDF
Devoid Web Application From SQL Injection Attack
PPTX
J2ee architecture
PPT
Innovate2011 Keys to Building OSLC Integrations
DOCX
Complete java syllabus 7448062045 Yesdo Sddd
DOCX
Unit 1st and 3rd notes of java
PDF
Lecture 8 Enterprise Java Beans (EJB)
PDF
J2EE Introduction
PDF
Hibernate complete notes_by_sekhar_sir_javabynatara_j
PDF
AMF Testing Made Easy! DeepSec 2012
PPT
Java J2EE
ODP
Spring User Guide
PPTX
Best Practices for JSF, Gameduell 2013
PPTX
Spring Framework Rohit
PPTX
Security Issues in HTML 5
PDF
Core java interview questions
Hibernate Advance Interview Questions
Java j2ee interview_questions
J2EE Architecture Explained
Dh2 Apps Training Part2
Devoid Web Application From SQL Injection Attack
J2ee architecture
Innovate2011 Keys to Building OSLC Integrations
Complete java syllabus 7448062045 Yesdo Sddd
Unit 1st and 3rd notes of java
Lecture 8 Enterprise Java Beans (EJB)
J2EE Introduction
Hibernate complete notes_by_sekhar_sir_javabynatara_j
AMF Testing Made Easy! DeepSec 2012
Java J2EE
Spring User Guide
Best Practices for JSF, Gameduell 2013
Spring Framework Rohit
Security Issues in HTML 5
Core java interview questions
Ad

Similar to Building enterprise web applications with spring 3 (20)

PDF
Yii Framework Security
PPTX
Java J2EE Interview Questions Part 2
PPTX
Java J2EE Interview Question Part 2
PPT
Struts Ppt 1
PPT
Struts
PDF
IRJET- Lightweight MVC Framework in PHP
PDF
Railsplitter: Simplify Your CRUD
PPT
Software Architecture in Architecture design .ppt
PPTX
Design patterns fast track
DOC
College information management system.doc
PDF
IRJET- A Review On - Controlchain: Access Control using Blockchain
PPT
Struts N E W
PDF
Introduction to Java Enterprise Edition
PPTX
Lecture 10.pptx
PPTX
Oracle Identity Manager Basics
DOCX
Repository Pattern in MVC3 Application with Entity Framework
PPTX
Introduction to ejb and struts framework
PPT
Spring training
PPT
Case Study For Data Governance Portal
PDF
College information management system.pdf
Yii Framework Security
Java J2EE Interview Questions Part 2
Java J2EE Interview Question Part 2
Struts Ppt 1
Struts
IRJET- Lightweight MVC Framework in PHP
Railsplitter: Simplify Your CRUD
Software Architecture in Architecture design .ppt
Design patterns fast track
College information management system.doc
IRJET- A Review On - Controlchain: Access Control using Blockchain
Struts N E W
Introduction to Java Enterprise Edition
Lecture 10.pptx
Oracle Identity Manager Basics
Repository Pattern in MVC3 Application with Entity Framework
Introduction to ejb and struts framework
Spring training
Case Study For Data Governance Portal
College information management system.pdf
Ad

More from Abdelmonaim Remani (6)

PDF
The Eschatology of Java
PPT
The Economies of Scaling Software
PPTX
The Rise of NoSQL and Polyglot Persistence
PPTX
The Art of Metaprogramming in Java
PPTX
Le Tour de xUnit
PPT
Introduction To Rich Internet Applications
The Eschatology of Java
The Economies of Scaling Software
The Rise of NoSQL and Polyglot Persistence
The Art of Metaprogramming in Java
Le Tour de xUnit
Introduction To Rich Internet Applications

Recently uploaded (20)

PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Machine learning based COVID-19 study performance prediction
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Encapsulation theory and applications.pdf
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Review of recent advances in non-invasive hemoglobin estimation
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Encapsulation_ Review paper, used for researhc scholars
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Electronic commerce courselecture one. Pdf
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Unlocking AI with Model Context Protocol (MCP)
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Machine learning based COVID-19 study performance prediction
Per capita expenditure prediction using model stacking based on satellite ima...
Encapsulation theory and applications.pdf
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Diabetes mellitus diagnosis method based random forest with bat algorithm
Review of recent advances in non-invasive hemoglobin estimation
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Dropbox Q2 2025 Financial Results & Investor Presentation
NewMind AI Weekly Chronicles - August'25 Week I
Encapsulation_ Review paper, used for researhc scholars
MYSQL Presentation for SQL database connectivity
Electronic commerce courselecture one. Pdf
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
Reach Out and Touch Someone: Haptics and Empathic Computing
CIFDAQ's Market Insight: SEC Turns Pro Crypto
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
Chapter 3 Spatial Domain Image Processing.pdf
Unlocking AI with Model Context Protocol (MCP)
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx

Building enterprise web applications with spring 3

  • 1. Building Enterprise Web Applications with Spring 3.0 and Spring 3.0 MVC JavaOne 2010ByAbdelmonaimRemaniabdelmonaim.remani@gmail.com
  • 2. Creative Commons Attribution-NonCommercial 3.0 Unportedhttp://creativecommons.org/licenses/by-nc/3.0/License
  • 3. Software Engineer at Overstock.comParticularly interested in technology evangelism and enterprise software development and architecturePresident and Founder of a number of organizationsThe Chico Java User GroupThe Chico Flex User Group,The Chico Google Technology User Group.LinkedInhttp://www.linkedin.com/in/polymathiccoderTwitterhttp://twitter.com/polymathiccoderWho Am I?
  • 4. WarningThis presentation is very long and covers a lot of material
  • 6. ComplexIn terms of requirementsFunctionalNon-FunctionalExecutionPerformanceReliabilitySecurityEvolutionTestabilityMaintainabilityExtendibilityScalability (Horizontal and Vertical)Enterprise Application Software (EAS)
  • 7. In the words of Edsger W. Dijkstra:[…] The Separation of Concerns […] is yet the only available technique for effective ordering of one’s thoughts […]Artificially Reducing complexity by means of AbstractionSpecific Choices of abstractionProduces a architecturesEnterprise Application Software (EAS)
  • 8. The ArchitectureLayered / N-TieredPresentation LayerWeb LayerService LayerPersistence LayerAspectsMiddlewareOtherModern Enterprise Application
  • 9. A Framework is an architectureA well-defined structure to solve a problemA pre-existing hierarchy to be extendedLibraryFramework vs. LibraryInvoking vs. being invokedGeneric vs. specificToolsCompiler, debugger, etc…Scaffolding and other utilitiesEtc…Frameworks
  • 10. Heavyweight vs. LightweightThe need for a platform or a stack (JEE as example)The ability to load in-demand necessary componentsThe memory footprintThe build sizeDeployment easeEtc…Frameworks
  • 12. Application FrameworkJavaOther implementations are available (Spring .NET)Open-SourceLightweightNon-Invasive (POJO Based)ExtendibleA platform with well-defined extension points for other frameworksBy Rod JohnsonExpert One-on-One J2EE Design and Development, 2002J2EE without EJB, 2004Became the De facto standard of Java Enterprise ApplicationsWhat is Spring?
  • 13. 20 ModulesSpringSource: Spring 3.0.x Framework Referencehttp://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/htmlsingle/spring-framework-reference.html
  • 14. Wrappers for most popular frameworksAllowing injection of dependencies into standard implementationStrutsJSFApache TapestryEtc…Full Integration with the JEE stackLibraries
  • 16. The Address Book from polymathic-coder.comA web application for Contact managementThe Address Book
  • 17. Details:As a user I should be able to view, add, delete, and edit personal contacts data on my address book including:First NameLast NameEmailPhone NumberImagePrimary Actors: Regular user / AdministratorAssumptions: The user is authenticated and has proper privileges to access the Contact Management AreaAccess is granted both through the web interface and a RESTful APIFunctional RequirementsUse Case 1 - Contact Management
  • 18. Business RulesA First Names are requiredPhone Numbers must be valid US phone numbersEmails must be validFunctional RequirementsUse Case 1 - Contact Management
  • 19. Details:As an administrator I should be able to view, add, delete, and edit the user data including:UsernamePasswordRole (Regular or Administrator)Whether the account is enabled or notEmailPrimary Actors: AdministratorAssumptions:The user is authenticated and has proper privileges to access the User Administration AreaAccess is granted through the web interfaceFunctional RequirementsUse Case 2 - User Management
  • 20. Business RulesUsername is required and must be uniquePasswords must be complex (The should contains at least 1 lowercase letter, 1 uppercase letter, 1 digit, and 1 special character)Emails must be validAn email must be sent to the newly created userFunctional RequirementsUse Case 2 - User Management
  • 21. Details:As an administrator I should be able to view audit and health check reportsPrimary Actors: AdministratorAssumptions:The user is authenticated and has proper privileges to access the Reporting AreaAccess is granted through the web interfaceThe reports are periodically generated by the systemFunctional RequirementsUse Case 3 - Reporting
  • 22. RBAC (Role-based access control)AuthenticationForm-basedHttp BasicAuthorizationSecurity RolesRegular UserAccess to personal contact management areaAdministratorsAccess to personal contact management areaAccess to user administration areaAccess to reporting areaAccess ControlNo RulesTransport SecurityNot requiredNon-Functional Requirements Security
  • 24. The problem:Acquiring Resources viaInstantiation of a concrete classUsing a static method of a singleton factoryUsing a Directory Services API that allows for discovery and lookup (JNDI for example)Etc..Creates hard dependenciesCoupled code is hard to reuse (DRYness)Painful Unit TestingInversion of Control
  • 25. The Solution:Coding against InterfacesInversion of Control: Dependency InjectionReflectively supply external dependency at runtimeThe Hollywood principle: “Don’t call us, we’ll call you”Wait a minute this a lot of work!Spring to the rescueInversion of Control
  • 26. Container POJOConfiguration MetadataXML-BasedAnnotation-BasedJava-basedSpring CoreSource: Spring 3.0.x Framework Referencehttp://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/htmlsingle/spring-framework-reference.html
  • 27. JSR 330 – Dependency Injection for Java JSR 330@Inject@NamedSpring Annotations@Autowire@QualifierJSR 250 -  Common Annotationsjavax.annotationJSR 299 – Contexts and Dependency InjectionScopes and contexts: javax.contextDependency injection service: javax.injectFramework integration SPI: javax.inject.managerEvent notification service: javax.event
  • 28. Used to mark a class that fulfills a role or a stereotypeStereotyped classes can be automatically detectedSpring Stereotypes@Component@Repository@Service@ControllerStereotypical Spring
  • 31. A model of the “concepts” involved in the system and their relationshipsAnemic Domain ModelPOJOs (Plain Old Java Objects) or VOs (Value Objects)Clear separation between logic and dataParallel object hierarchies are evilMetadata is interpreted depending on the context as the object moves across the layers of the applicationObject-Relational mapping to persistent entitiesValidationMarshaling / Un-marshalingEtc…Domain Model
  • 32. Ensuring the correctness of data based on a set predefined rulesJSR 303 - Bean ValidationSource: Hibernate Validator Reference Guide 4.1.0.Finalhttp://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/
  • 33. javax.validationReference Implementation: Hibernate ValidatorJSR 303 - Bean ValidationSource: Hibernate Validator Reference Guide 4.1.0.Finalhttp://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/
  • 34. Instantiation (Items 1 & 2 of Josh Bloch’s Effective Java)Static FactoriesTelescopingProvide buildersOverride the default implementations of hashCode(), toString(), and equals(Object) methodsUse Pojomatic at http://pojomatic.sourceforge.net/Be aware of any circular dependency in your modelVersioning@Version of JSR 317 – JPA 2.0Domain Model
  • 36. A logical encapsulation of classes and interfaces whose responsibilities fall within the scope of:Create, Read, Update, and Delete (CRUD) operations on persistence storage mechanisms such as file systems and Database Management Systems (DBMS)Interacting with Message-Oriented Middleware (MOM) infrastructures or Message Transfer Agents (MTA) such as JMS or mail serversPersistence Layer
  • 37. javax.persistenceReference Implementation EclipseLinkPrimerA persistence entity is a POJO whose state is persisted to a table in a relational database according to predefined ORM metadataAn entity is managed by an Entity ManagerDo we still need a Persistence Layer?HighlightsSupport for JSR 303 validationJSR 317 – JPA 2.0
  • 38. Beans Stereotyped with @RepositoryEnables exception translation to a consistent exception hierarchyRun-time exceptions and do not have to be declared or caughtUse JPA annotations to inject EntityManager and EntityManagerFactory@PersistenceContext@PersistenceUnitFollow a convention (I suggest CRUD)Declaring transaction semantics@TransactionalSpring Data Access / Integration
  • 39. Java Mail APIjavax.mailSpring Helpers for various Templating EnginesVelocityFreeMarkerSpring Data Access / Integration
  • 40. TestingJUnitTake advantage of what JUnit 4.7 has to offer (Explore Theories, Rules, Etc…) LibrariesDbUnithttp://www.dbunit.org/Dumpster http://quintanasoft.com/dumbster/Consider HADES http://redmine.synyx.org/projects/show/hadesPersistence Layer
  • 42. A logical encapsulation of classes and interfaces that provide the system functionality consolidating Units of work. Service layer classes should be:Transactional StatelessBeans Stereotyped with @ServiceFollow a convention (I suggest VADER)Service Layer
  • 44. A logical encapsulation of classes and interfaces whose responsibilities fall within the scope of:Navigational logicRendering page views in the proper orderAs simple as mapping a single URL to a single pageAs complex as a full work flow engineWeb concerns (Request variables, session variables, HTTP methods, HTTP response codes, Etc…) should be separated from business logicWeb Layer
  • 45. Two types of Web FrameworksRequest / Response Web FrameworksWrap the Servlet APIAdopt push modelCompile resultPush it out to be rendered in a viewStruts, Spring MVC, Etc…Component Web FrameworksDot only hide the Servlet APIEvent-driven componentJSF, Tapestry, Etc…Web Layer
  • 47. Request / Response Web FrameworksA Front Controller PatternOne Dispatcher servletApplication ContextsApplication ContextWeb Application ContextSpring MVC
  • 48. The promise Non-invasivenessFully annotation-drivenNo extension of framework classes No overriding methodsControllersBeans (Spring Managed-POJOs) Stereotyped with @ControllerSpring MVC - Controllers
  • 49. Mapping Rules@RequestMappingByPathHTTP methodQuery ParametersRequest HeadersSpring MVC - Controllers
  • 50. Handler MethodsParameters are request inputsRequest data@RequestParam@PathVariable@RequestHeader@CookieValueCommand Objects (Domain Objects)Injection of standard objectsAutomatic Type ConversionCustom Type ConversionJSR 303 Support@ValidExposing reference data to the views@ModelAttributeSpring MVC - Controllers
  • 52. Representational State TransferArchitectural StyleIdentifiable ResourcesEverything is a resource accessible URIUniform Interface based on HTTP methodsGET /contacts reads all contactsGET /contacts/1 reads the contact whose id is 1POST /contacts creates a contact PUT /contacts/1 updates the contact whose id is 1DELETE /contacts/1 deletes the contact whose id is 1 RESTful Architecture
  • 53. Architectural StyleResource RepresentationsMultiple data representation (MIME types) can be specifiedRequestAccept HTTP header field or file extensionResponseContent-Type HTTP header fieldStateless ConversionNo sessionScalableLoosely coupledRESTful Architecture
  • 56. “Deciding to use Velocity or XSLT in place of an existing JSP is primarily a matter of configuration” Spring 3.0 DocumentationView technologiesJSP & JSTLTilesVelocityFreeMarkerXSLTJasperReportsEtc…Spring MVC - Views
  • 57. Views are rendered based on handler methods return@ResponseBody or ResponseEntity<T>Many HttpMessageConvertersStringHttpMessageConverterJaxb2RootElementHttpMessageConverterMappingJacksonHttpMessageConverterAtomFeed/RssChannelHttpMessageConverterEtc…Register your ownStringView Resolver and a ViewSpring MVC - Views
  • 59. JSP & JSTLSpring Tag LibrarySpring Form Tag LibraryRefer to spring-form.tldThemesOverall look-and-feel of your applicationA collection of style sheets and images<spring:theme />Theme resolversI18NSpring MVC - Views
  • 60. Spring Web FlowFor Web Application that areMore dynamicNon-linear without arbitrary end pointsSpring Portlet MVCA JSR 168 compliant Portlet environnentLarge web application composed with subcomponents on the same web pageSpring MVC Complements
  • 63. OOP creates a hierarchical object model by natureCross cutting concernsAre not necessarily a part of the application logicOccur across the object hierarchy in unrelated partsExamplesLoggingSecurityTransaction managementEtc…Aspect-Oriented Programming
  • 64. The ProblemCode TanglingNo CohesionCode ScatteringNot DRYThe SolutionAspect Oriented ProgrammingAspectJModulation of Aspects and weaving into the application codeAspect Oriented Programming
  • 65. Spring AOPJava based AOP FrameworkBuilt on top of AspectJInterception basedSpring APO
  • 66. Joint PointA point in the execution of the programPoint CutAn expression that selects one or more joint pointAspectJ Expression LanguageAdviceThe code to be weaved at a joint pointAspectPoint Cut + AdviceAOP Terminology
  • 69. Authenticationthe verification of the user identityAuthorizationPermissions granted to the identified userAccess ControlBy arbitrary conditions that may depend to Attributes of clientsTemporal and Local ConditionHuman User DetectionOtherChannel or Transport SecurityEncryptionSecurity Terminology
  • 70. RealmA Defined the authentication policyUserA defined individual in the Application ServerGroupA defined classification of users by common traits in the Application Server.RoleAn abstract name of the permissions to access a particular set of resources in an applicationSecurity Terminology
  • 71. Spring SecurityJAAS (Java Authentication and Authorization Service)jGuardApache ShiroAvailable Frameworks
  • 72. Security is your responsibilityFeatures:It is not the standardNo class loader authorization capabilitiesSimple configurationPortable across containersCustomizable and extendablePluggable authentication and web request URI securitySupport method interception, Single Sign-On, and Swing clientsSpring Security
  • 73. AuthenticationForm-BasedBasicDigestLDAPNTLM (NT LAN Manager)SSO (Single Sign-On)JA-SIG CASOpen IDAtlassian CrowdSiteMinderX.509Authentication
  • 74. MechanismsInteract with the userProvidersCheck credentialsBundles details in a Thread Local security context holderRepositoriesStore roles and profile infoIn MemoryJDBCLDAPEtc…Authentication
  • 75. Web AuthorizationURL-BasedWhich URL patterns and HTTP methods are allowed to be accessed by which roleMethod AuthorizationReusableProtocol AgnosticUses AOPAnnotations SupportJSR 250Spring @SecuredSpring Security ELAuthorization
  • 76. Other
  • 77. Job SchedulingBulk Processing IntegrationEtc…Other
  • 78. If you are interested inThe full-source code of the Address Book ApplicationA Step-By-Step tutorialPossibly a screen castGo tohttp://bit.ly/ad4VGhSupport Material
  • 79. The Silicon Valley Spring User Grouphttp://www.meetup.com/sv-sug
  • 80. Q & A

Editor's Notes

  • #7: Enterprise applications dealcomplex problems.This complexity manifests itself inThe ramification of their functional requirementsThe intricacy of their non-functional requirementsThe latter can be classified asThe ones that are related to the execution of the application (such as performance, reliability, and security)The ones that pertain to its evolution (such as testability, maintainability, extensibility, and scalability whether it is horizontal or vertical)
  • #8: Here I am using the termsseparation of concerns and abstraction interchangeably, which is not necessarily not true. Separation of concerns is a form abstraction.Abstraction manifested by modularization, encapsulation, etc… within the OOP paradigmReducing complexity is artificial because the complexity of the problem remains the same no matter what abstraction we apply to deal itIf you contemplate on Dijkstra’s quote
  • #9: Established the fact that EAS is far more complex to fit in a monolithic The terms tier and layer are used loosely (logical/physical)As you move up to the next level of abstraction, the lower level serves as a platform to the one on top of itMiddleware: RPC, WS, MOM, or as sophisticated as an ESB or a full blown SOA
  • #26: Tradeoff: Since it is done at runtime, no static type checking
  • #61: Spring Web FlowAllows web apps to act like state machinesEvents are raised to change to statesSpring Portlet MVCShared StateSSO and User authentication and authorization
  • #66: AspectJ vs. Spring AOPAspectJ uses Byte code modification for code weavingSpring AOP uses dynamic proxies for code weavingInterception removes the need for compilation or load-time weavingBut only allows for public or protected method execution at a join point
  • #70: Access control is like a gate that is either closed or open under certain conditions and designated to certain people only
  • #73: Compare to JAASSimple configuration compared with .policy whose authors still need to be trustedNot all the containers implement JAAS-based authorization
  • #74: BasicHTTP Standard (Pop-up)HTTPS is used for EncryptionDigest: S-HTTPSSL is designed to establish a secure connection, whereas S-HTTP is designed to send individual messages securely