Title: COMP 7100: Computers in the Information society
1COMP 7100 Computers in the Information society
- MVC and Spring Framework
- Hongjun SongComputer ScienceThe University of
Memphis
2MVC
3What it is All About
?
mental model
?
data
?
?
Computer
usecases
operations
4Scripting vs. Direct Manipulation
- Out of main door
- Turn right
- 5th left
- Right at 4th light
- ½ left at 1st light
- Youre there
5Users Mental ModelActivity Planning Network
actC
actA
Code Algorithms
DefineUseCases
actD
2 weeks
3 weeks
System Integration
actB
Define CodeDomainClass attributes
2 weeks
7 weeks
6User Machine Interaction
usermental model
data
DomainData
User
7Model View - Controller
usermental model
data
Model
User
Run Demo
8Use Case exampleA Functional Requirement
- Use Case N frontloading function
- An activity is characterized by its duration,
earlyStart time, earlyFinish time,its
predecessors and successors activities. - By default, earlyFinish earlyStart
durationspecial activities may have more complex
algorithms - An activity can start when all its predecessors
are finishedearlyStart MAX (earlyFinish all
predecessors)
Run Demo
9frontloading 1UML Diagrams
- Critical Questions
- What are the roles?
- How are they interconnected?
- How do they interact?
1. What are the roles?2. How are they
interconnected?
3. How do they interact?
10The Essence of Object OrientationObjects
interact to achieve a given goal
Critical questions
- What are the relevant objects?
- The relevant objects are seen as a structure of
Roles. - A role names the usage of one or more objects.
- The name is seen as an alias for those objects.
- How are they connected?
- A Collaboration describes the structure of roles.
- How do they interact?
- An Algorithm specifies the interaction in terms
of the roles.
11Class and Role 1Steven Pinker How The Mind
Works
Classification Group on common features
(inst.vars. methods)
- Role (Artifact) Group on common purpose
- People categorize objects in terms of the roles
they play within intuitive theories about how
the world operates. - Roles are defined by what they can do and by
what someone, somewhere, makes them to do at
some time.
12Class and Role 2The TrumpeterHändel Messiah,
Hallelujah choir
One Role - Two Classes
13Role Playing in the TheatreHenrik Ibsen Peer
Gynt
The Royal Hall of the King of the Dovre-Trolls.
THE OLD MAN OF THE DOVRE sits on the throne,
crowned, and with his sceptre in his hand. His
CHILDREN and NEAREST RELATIONS are ranged on both
sides. PEER GYNT stands before him. Violent
commotion in the hall. ---------------- (THE
GREEN-CLAD ONE)
http//norsk.kameraklubb.net/coppermine/displayima
ge/album167/pos6.html
14frontloading 1UML Diagrams
- Critical Questions
- What are the roles?
- How are they interconnected?
- How do they interact?
1. What are the roles?2. How are they
interconnected?
3. How do they interact?
15frontloading-2 Algorithm
public void frontload (Integer startWeek)
FrontIntf frontloader ?? SetltFrontpredIntfgt
frontpreds ?? Integer earlyStart
startWeek for (FrontpredIntf pred frontpreds)
earlyStart Math.max(earlyStart,
pred.earlyFinish() 1) frontloader.setEarl
yStart(earlyStart)
16Class and Role - 2
- A Class is static, it groups objects with similar
properties - class Activity specifies all activity objects.
- A Role is dynamic, it groups objects with a given
usage - the object playing the frontloader role is the
object currently in the focus of attention. - the objects playing the frontpreds role are
currently used as predecessors. - When we say that frontloader sends earlyFinish()
to frontpreds, we mean that the object currently
playing the frontloader role sends earlyFinish()
to all the objects currently playing the
frontpreds role. - a role is not an object, but an alias for one or
more objects.
17What it still is All About
mental model
data
GUI
Model
usecases
operations
18Data ModelConceptual Schema
19Data ModelJava Domain Classes
public class Model public SetltActivitygt
activities new HashSetltActivitygt() public
SetltDependencygt dependencies n
ew HashSetltDependencygt() public class
Activity implements FrontpredIntf, FrontIntf
private Integer earlyStart, earlyFinish,
duration private String name public class
Dependency private Activity predecessor,
successor
20Roles and ObjectsBridging the gap with queries
21frontloading-3 Algorithm
public void frontload (Integer startWeek)
FrontIntf frontloader ?? SetltFrontpredIntfgt
frontpreds ?? Integer earlyStart
startWeek for (FrontpredIntf pred frontpreds)
earlyStart Math.max(earlyStart,
pred.earlyFinish() 1) frontloader.setEarl
yStart(earlyStart)
FrontCollab frontCollab new FrontCollab()Front
Intf frontloader frontCollab.frontloader SetltFr
ontpredIntfgt frontpreds frontCollab.frontpreds
22FrontCollabExternal Data View
public class FrontCollab public FrontIntf
frontloader public FrontpredIntf frontpreds
public FrontCollab () frontloader
selectFrontloader() frontpreds
predecessorsOf(frontloader)
23Select domain object tofrontloader role by Java
Query
private FrontIntf selectFrontloader() for
(Activity act model.allActivities()) if
(act.earlyStart() null) SetltFrontpredIntfgt
predSet predecessorsOf(act) if
(areAllDone(predSet)) frontloader
act return (frontloader)
return null
24Select domain objects tofrontpreds role by Java
Query
public FrontpredIntf predecessorsOf(FrontIntf
act) SetltFrontpredIntfgt preds new
HashSetltFrontpredIntfgt() for (Dependency assoc
model.dependencies() ) if
(assoc.successor() act) preds.add(assoc.p
redecessor()) return preds
25Conclusion 1 of 2 User NeedsBalance Thinking
and Doing
User needs are in two dimensions they should be
supported in harmony thinking ? mental model
? data model ? objects doing ? use case ?
collaboration ? role ? query ? objects
26Conclusion 2 of 2 Architecture Balance State
and Behavior
Mental Model
Use Cases
Algorithm role interaction
Conceptualschema
reference roles
Collaboration roles and links
Classattributes
select objects
state
behavior
Data Objects
27Questions?
28More reading
- Reenskaug, T. Original MVC notes from Xerox
PARChttp//folk.uio.no/trygver/2007/MVC_Originals
.pdf - Reenskaug, T, The BabyUML discipline of
programming (where A Program Data
Communication Algorithms). SoSym 5,1 (April
2006). DOI 10.1007/s10270-006-0008-x.http//heim
.ifi.uio.no/trygver/2006/SoSyM/trygveDiscipline.p
df - Reenskaug, T. Programming with Roles and
Classes the BabyUML ApproachTo be published by
Nova publishers as a chapter in a book on
Computer Software Engineering Research WEB
PAGE http//folk.uio.no/trygver/2007/babyUML.pdf
(.PDF)) - Unified Modeling Language Superstructure.
Version 2.1. Object Management Group (OMG)
document ptc/06-04-02. http//www.omg.org - Arisholm, E. Sjøberg, D. A Controlled
Experiment with Professionals to Evaluate the
Effect of a Delegated versus Centralized Control
,Simula Research Laboratory Technical Report
2003-6http//www.simula.no/publication_one.php?pu
blication_id601 - Reenskaug, T Wold, P., Lehne, O. A. Working
With Objects. This book is out of print. An
early .pdf version kan be downloaded free from
http//folk.uio.no/trygver/1996/book/book11d.pdf
- Wirfs-Brock, R. McKean, A. Object Design.
Roles, Responsibilities, and Collaborations.
ISBN 0-201-37943-0 Addison-Wesley Boston, MA,
2003. - Andersen, E. P. Conceptual Modeling of Objects.
A Role Modeling Approach. D.Scient thesis,
November 1997, University of Oslo. web page
http//heim.ifi.uio.no/trygver/1997/
EgilAndersen/ConceptualModelingOO.pdf - Pinker, S. How the Mind Works ISBN
0-393-04535-8 Norton New York, NY, 1997.
29Spring Framework
30What is the Spring Framework?
- Spring is a Lightweight Application Framework
- Where Struts, WebWork and others can be
considered Web frameworks, Spring addresses all
tiers of an application - Spring provides the plumbing so that you dont
have to!
31Spring Framework History
- Started 2002/2003 by Rod Johnson and Juergen
Holler - Started as a framework developed around Rod
Johnsons book Expert One-on-One J2EE Design and
Development - Spring 1.0 Released March 2004
- 2004/2005 Spring is emerging as a leading
full-stack Java/J2EE application framework
32Spring J2EE Application Server?
- Spring is NOT a J2EE application server
- Spring can integrate nicely with J2EE application
servers (or any Java environment) - Spring can, in many cases, elegantly replace
services traditionally provided by J2EE
application servers
33Lessons Learned from Struts
- Before Struts, everyone wrote their own front
controllers (or YIKES! put their controller logic
in JSP) - After Struts, the custom front controllers could
be thrown out - Developers focus on solving business problems
- Productivity Gain!
- But with Struts (and most of the other web
frameworks) you still have to write your own
business delegates or service layers
34Spring Can Help!
- Spring brings a consistent structure to your
entire application - Spring provides a consistent way to glue your
whole application together - Spring provides elegant integration points with
standard and defacto-standard interfaces
Hibernate, JDO, TopLink, EJB, RMI, JNDI, JMS, Web
Services, Struts, etc. - Just as Struts did on the web tier, we can
realize huge productivity gains by not having to
write the common integration points across your
application
35The Spring Framework Mission Statement
- From springframework.org
- The authors of Spring believe that
- J2EE should be easier to use
- It's best to program to interfaces, rather than
classes. Spring reduces the complexity cost of
using interfaces to zero. - JavaBeans offer a great way of configuring
applications. - OO design is more important than any
implementation technology, such as J2EE. - Checked exceptions are overused in Java. A
framework shouldn't force you to catch exceptions
you're unlikely to be able to recover from. - Testability is essential, and a framework such as
Spring should help make your code easier to test.
36Spring Framework Mission Statement (continued)
- The authors of Spring aim that
- Spring should be a pleasure to use
- Your application code should not depend on Spring
APIs - Spring should not compete with good existing
solutions, but should foster integration. (For
example, JDO and Hibernate are great O/R mapping
solutions. We don't need to develop another one.)
37Spring Overview
Note Spring distribution comes as one big jar
file and alternatively as a series of smaller
jars broken out along the above lines (so you can
include only what you need)
38Spring is Non-Invasive
- What does that mean?
- You are not forced to import or extend any Spring
APIs - An invasive API takes over your code.
- Anti-patterns
- EJB forces you to use JNDI
- Struts forces you to extend Action
- Invasive frameworks are inherently difficult
to test. You have to stub the runtime that is
supplied by the application server
39But really, what IS Spring?
- At its core, Spring provides
- An Inversion of Control Container
- Also known as Dependency Injection (Fowlers
term) - An AOP Framework
- Spring provides a proxy-based AOP framework
- You can alternatively integrate with AspectJ or
AspectWerkz - A Service Abstraction Layer
- Consistent integration with various standard and
3rd party APIs - These together enable you to write powerful,
scalable applications using POJOs.
40Seriously though, what IS Spring?
- Spring at its core, is a framework for wiring up
your entire application - BeanFactories are the heart of Spring
41BeanFactories
- A BeanFactory is typically configured in an XML
file with the root element ltbeansgt - The XML contains one or more ltbeangt elements
- id (or name) attribute to identify the bean
- class attribute to specify the fully qualified
class
42BeanFactories
- By default, beans are treated as singletons
- Can also be prototypes
- Here is an example
The beans fully- qualified classname
The beans ID
ltbeansgt ltbean idwidgetService
classcom.zabada.base.WidgetServicegt
ltproperty namepoolSizegt lt!-property
value here--gt lt/propertygt lt/beangt lt/beansgt
Maps to a setPoolSize() call
43Property Values for BeanFactories
- Strings and Numbers
- Arrays and Collections
ltproperty namesizegtltvaluegt42lt/valuegtlt/propertygt
ltproperty namenamegtltvaluegtJimlt/valuegtlt/property
gt
ltproperty namehobbiesgt ltlistgt
ltvaluegtBasket Weavinglt/valuegt ltvaluegtBreak
Dancinglt/valuegt lt/listgt lt/propertygt
44Property Values for BeanFactories (continued)
- The real magic comes in when you can set
- a property on a bean that refers to another
- bean in the configuration
- This is the basic concept
- of Inversion of Control
ltbean namewidgetService classcom.zabada.base.
WidgetServiceImplgt ltproperty
namewidgetDAOgt ltref beanmyWidgetDAO/gt
lt/propertygt lt/beangt
calls setWidgetDAO(myWidgetDAO) where myWidgetDAO
is another bean defined in the configuration
45Dependency Injection(Inversion of Control)
- Complicated sounding terms for a fairly simple
concept - The Hollywood Principle Dont call me, Ill
call you - Dependencies used from within a bean arent asked
for outwardly, but are injected into the bean by
the container
46Dependency Injection(Inversion of Control)
- Eliminates lookup code from within your
application - Allows for pluggablity and hot swapping
- Promotes good OO design
- Enables reuse of existing code
- Makes your application extremely testable
47A Very Special BeanFactorythe ApplicationContext
- An ApplicationContext is a BeanFactory, but adds
framework features such as - i18n messages
- Event notifications
- This is what you will probably most often use in
your Spring applications
48AOP (Aspect-Oriented Programming)
- AOP decomposes a system into concerns, instead of
objects. - Deals with "aspects" that cross-cut across the
code and can be difficult or impossible to
modularize with OOP - The most common example given is logging
- Code for doing logging typically must be
scattered all over a system - With AOP, you can declare, for example, that a
system should write a log record at the beginning
and end of all method invocations.
49AOP (Aspect-Oriented Programming)
- AOP enables the delivery of services to POJOs
- Spring provides pre-packaged AOP services
- Declarative Transaction Management
- Security
- Logging
- You can write custom AOP services for
- Auditing
- Caching
- Custom security
50Service Abstraction Layers
- Spring provides abstraction for
- Transaction Management
- JTA, JDBC, others
- Data Access
- JDBC, Hibernate, JDO, TopLink, iBatis
- Email
- Remoting
- EJB, Web Services, RMI, Hessian/Burlap
51Service Abstraction Layers
- Benefits
- No implicit contracts with JNDI, etc.
- Insulates you from the underlying APIs
- Greater reusability
- Spring abstractions always consist of interfaces
- This makes testing simpler
- For data access, Spring uses a generic
transaction infrastructure and DAO exception
hierarchy that is common across all supported
platforms
52Spring on the Web Tier
- Spring integrates nicely with Struts, WebWork,
JSF, Tapestry, Velocity and other web frameworks - Spring also provides its own web framework,
Spring Web MVC
53Spring on the Web Tier Spring MVC
- The Spring MVC Framework offers a simple
interface based infrastructure for handing web
MVC architectures - Spring MVC components are treated as first-class
Spring beans - Other Spring beans can easily be injected into
Spring MVC components - Spring MVC components are easy to test
54Spring MVC Key Interfaces
- Controller (org.springframework.web.servlet.mvc.Co
ntroller) - Must implement ModelAndView handleRequest(request,
response) - This is the base controller interface, comparable
to the notion of a Struts Action. - View (org.springframework.web.servlet.mvc.View)
- Must implement void render( model, request,
response) - This is the MVC view for a web interaction.
Implementations are responsible for rendering
content, and exposing the model. - Model
- To complete the MVC trio, note that the model is
typically handled as a java.util.Map which is
returned with the view - the values of the model are available, for
example in a JSP, using a ltjspuseBean/gt where
the id corresponds to the key value in the Map
55Spring on the Web Tier Integration with Other
Frameworks
- Spring integrates nicely with other web
frameworks with two methodologies - Look up Spring beans within Controllers/Actions
via the convenience static method
WebApplicationContextUtils.getWebApplicationContex
t( servletContext).getBean(beanName) - Configure the Controllers/Actions for the web
framework in a Spring BeanFactory and then use
Spring provided proxies in the actual web
framework configuration - When available, this methodology is preferred
- This approach lets you design your
Controllers/Actions with dependency injection and
makes your Controller/Actions more testable
56Spring Related Tools and Add-Ons
- ACEGI Security - comprehensive security services
for the Spring Framework - Spring IDE - graphical user interface for the
configuration files used by the Spring Framework - Spring BeanDoc - tool that facilitates
documentation and graphing of Spring bean
factories and application context files - XDoclet Spring Tags - support for generating
Spring XML config files from annotations in Java
classes (you could also use JDK1.5 annotations to
achieve this) - Spring Web Flow - for web applications with
demanding page flow requirements - AppFuse Not really a tool or add-on, but AppFuse
is Matt Raible's project to jumpstart your Java
web projects. It uses Spring at it's core and
studying it is a great way to learn about Spring.
- Spring Framework .NET Spring Clone for the Dark
Side ?
57Spring Framework / Spring Related References
The Official Spring Reference Manual
http//www.springframework.org/docs/reference/ Int
roduction to Spring by Rod Johnson
http//www.theserverside.com/articles/article.tss
?lSpringFramework Spring in Action by Craig
Walls and Ryan Breidenbach Pro Spring by Rob
Harrop and Jan Machacek J2EE Without EJB by Rod
Johnson and Juergen Holler Expert One-on-One
J2EE Design and Development by Rod Johnson
Spring Developers Notebook by Bruce Tate and
Justin Gehtland Better, Faster, Lighter Java by
Bruce Tate and Justin Gehtland Spring Live by
Matt Raible Professional Java Development with
the Spring Framework