Spring Full
-
Upload
jadesh-chanda -
Category
Documents
-
view
221 -
download
0
Transcript of Spring Full
-
8/12/2019 Spring Full
1/103
INTRODUCTION TO THE SPRING
FRAMEWORK
Spring is a lightweight inversion of control
and
aspect oriented container framework
Spring makes develop ing J2EE
application easier
and more fun!! !
Introduced by Rod Johnson in J2EE Design
& Development
-
8/12/2019 Spring Full
2/103
Lightweight J2EE
Architecture
-
8/12/2019 Spring Full
3/103
Overview
Review current state of J2EE
Lightweight Frameworks and what they can do
Todays Frameworks Spring
Hibernate
Spring and Hibernate Integration
Demos along the way Review
-
8/12/2019 Spring Full
4/103
Current J2EE State
J2EE has done a great deal to standardize our industry These J2EE services are tremendously successful with wide adoption: JDBC
Servlet/JSP/WAR
JNDI
JMS
Useful EJB Services Declarative transactions support
Persistence
Security
Distributed component model
Instance pooling and caching
-
8/12/2019 Spring Full
5/103
Genesis of EJB
1998 Distributed Computing was the big
buzz-word
Sun made EJBs remote to compete with
technologies like CORBA
The specification was intrusive
And we have been *dealing* with these
decisions ever since
Lets take a look at the Sun Best practices.
-
8/12/2019 Spring Full
6/103
-
8/12/2019 Spring Full
7/103
EJB Issues
IntrusiveNoisy
Must be an EJBObject
Must run within the container
Rapid iterative code/debug/test cycles difficult
If the Sun Pet Store is the best, were in trouble
Too many different patterns
Performs poorlyReliance on Entity Beans
Too many different files needed to do simple
things
-
8/12/2019 Spring Full
8/103
Treating the Symptoms
Tools exist to make EJB development easier
XDoclet
IDE Wizards
Cactus
Work-a-rounds
Data Transfer Objects (DTOs)
Service Locator
-
8/12/2019 Spring Full
9/103
The Way Ahead
Development teams need a better
frameworks that supports these ideas:
Implementing business requirements first
Simplicity
Productivity
Testability
Object Orientation Lightweight Frameworks can get us there
-
8/12/2019 Spring Full
10/103
What are Lightweight Frameworks?
Non-intrusive
No container requirements
Simplify Application Development
Remove re-occurring pattern code
Productivity friendly
Unit test friendly
Very Pluggable
Usually Open Source
-
8/12/2019 Spring Full
11/103
Leading Lightweight Frameworks
Spring, Pico, Hivemind
Hibernate, IBatis, Castor
WebWork
Quartz
Sitemesh
JBoss is NOT a lightweight framework
-
8/12/2019 Spring Full
12/103
Spring
-
8/12/2019 Spring Full
13/103
Spring is in the Air
Spring is a glue framework that ties many frameworks togetherin a consistent way
Inversion of Control Framework (Dependency Injection)
Dont call us well call you
Service Injection rather than Service Lookup Encourages programming to Interfaces
Reduces coupling between components
Supports Testing
Configuration
Supports externalizing the configuration
And more
-
8/12/2019 Spring Full
14/103
The Bean Container finds the definition of the Spring Bean in theConfiguration file.
The Bean Container creates an instance of the Bean using JavaReflection API.
If any properties are mentioned, then they are also applied. If theproperty itself is a Bean, then it is resolved and set.
If the Bean class implements the BeanNameAware interface, then thesetBeanName() method will be called by passing the name of the Bean.
If the Bean class implements the BeanFactoryAware interface, then themethod setBeanFactory() will be called by passing an instance ofBeanFactory object.
If there are any BeanPostProcessors object associated with the
BeanFactory that loaded the Bean, then the methodpostProcessBeforeInitialization() will be called even before theproperties for the Bean are set.
Spring LifeCycle
-
8/12/2019 Spring Full
15/103
If the Bean class implements the InitializingBean interface, then themethod afterPropertiesSet() will be called once all the Beanproperties defined in the Configuration file are set.
If the Bean definition in the Configuration file contains a 'init-method'attribute, then the value for the attribute will be resolved to a methodname in the Bean class and that method will be called.
The postProcessAfterInitialization() method will be called if there areany Bean Post Processors attached for the Bean Factory object.
If the Bean class implements the DisposableBean interface, then themethod destroy() will be called when the Application no longerneeds the bean reference.
If the Bean definition in the Configuration file contains a 'destroy-method' attribute, then the corresponding method definition in theBean class will be called.
Spring LifeCycle
-
8/12/2019 Spring Full
16/103
Spring Modules
Core IoC container
Application context module
AOP module
JDBC abstraction and DAO module
Object/relational mapping integration module
Web module
MVC module Quartz, Email, WebServices Integration and
more.
-
8/12/2019 Spring Full
17/103
Why use IoC?
-
8/12/2019 Spring Full
18/103
IoC Types
Three basic types Type I
Interface Injection
Your service or component implement a specific interface
Much like EJBs
Type II Method Injection
Dependent objects are provided to the object by methods Based on JavaBeans constructs
Ordering of method calls may not be achievable
Type III Constructor Injection
Dependent objects are provided to the object by constructors
Large constructor argument lists
-
8/12/2019 Spring Full
19/103
AOP Introduction
AOPAspect Oriented Programming Separates concerns of an object into their own
aspects
Helps to remove infrastructure code from theapplication
AOP can remove replicated code that isscattered across an entire system
Used to apply cross-cutting concernsuniformly to objects. Logging
Security
Transaction Management
-
8/12/2019 Spring Full
20/103
AOP Crosscutting
Without AOP With AOP
-
8/12/2019 Spring Full
21/103
AOP Definitions
Aspect- An application wide concern that is often duplicated inmany classes, that could be implemented before, after, or uponfailure across a group of methods.
JoinPoint- A join of methods across which an aspect can beimplemented.
Spring allows method interception. This means when a method iscalled the framework can attach functionality.
Pointcut- Description of the collection of methods for which adviceis to be applied
Introduction- Adding methods or properties to a class with advice.
AOP Proxies- Surrogate object that invokes advice and advises the
invoked class
-
8/12/2019 Spring Full
22/103
AOP Example
Spring AOP Code Example
-
8/12/2019 Spring Full
23/103
Spring Tips and Tricks
Start with just the IoC and build from there
Be careful with the autowirechanges in Interfaces andrefactoring can change autowire rules
AOP supports proxying of classes via interface
and via CGLib Interfaces are recommended to reduce coupling
CGLib is available to support legacy code or 3rdparty code
Methods marked as final can not be advised
Dynamic Pointcuts (ControlFlowPointcuts) canbe slow so try to avoid them
Avoid applying Advise to fine grained objects
Use autoproxing when you want system wide
-
8/12/2019 Spring Full
24/103
Spring Hibernate Integration
-
8/12/2019 Spring Full
25/103
Spring Hibernate Integration
HibernateTemplate
Many convenience methods
Use is restricted to unchecked exceptions
Uses anonymous inner class callbacks
Hibernate AOP
Any exception types can be thrown within the data
access code
DAO must extend HibernateDAOSupport
Very clean DAO methods
-
8/12/2019 Spring Full
26/103
Spring Transactions
Clear application layering supporting most data access andtransaction technologies
Not bound to a container
Transactions can either be managed programmatically ordeclarative using AOP
TransactionTemplate Allows execution of transactional code without the need to re-implement
transaction workflows (Exception Handling)
Triggers a rollback if the callback throws a runtime exception or if it setsthe transaction to rollback-only
TransactionInterceptor
Business object does not need to be transaction aware (similar to EJB)
Check and unchecked exceptions supported
Default rollback behavior is to rollback on runtime exceptions but thiscan be configured
-
8/12/2019 Spring Full
27/103
Spring helps J2EE developers by:
Offering a lightweight JavaBean container that eliminates the
need to write repetitive plumbing code such as lookups
Providing an inversion of control framework that allows bean
dependencies to be automatically resolved upon object
instantiation Allowing cross cutting concerns such as transaction
management to be woven into beans as aspects rather than
becoming the concern of the business object
Offering layers of abstraction on top of popular existing
technologies such as JDBC and Hibernate that ease their use
and organize configuration management
-
8/12/2019 Spring Full
28/103
while adhering to certain principals:
Your application code should not depend on
Spring APIs
Spring should not compete with good existing
solutions, but should foster integration
Writing testable code is critical and the
container should help not interfere with this
objective Spring should be a pleasure to use
-
8/12/2019 Spring Full
29/103
Spring Architecture
-
8/12/2019 Spring Full
30/103
INVERSION OF CONTROL AND
AOP CONCEPTSWhat is it?A way of sorting out dependencies between objects and
automatically injecting references to collaborating objects on
demand
Who determines how the objects should be injected?
The IoC framework, usually via XML configuration files Benefits
Removes the responsibility of finding or creating dependent objects
and moves it into configuration
Reduces coupling between implementation objects and encourages
interface based design
Allows an application to be reconfiguredoutside of code
Can encourage writing testable components
-
8/12/2019 Spring Full
31/103
Traditional way of obtaining
references. private AccountService accountService = null; public void execute(HttpServletRequest req, .) throws Exception {
Account account = createAccount(req);
AccountService service = getAccountService();
service.updateAccount(account);
}
private AccountService getAccountService() throws {
if (accountService == null) { Context ctx = new InitialContext();
Context env = (Context) ctx.lookup(java:comp/env);
Object obj = env.lookup(ejb/AccountServiceHome);
AccountServiceHome home = (AccountServiceHome)
PortableRemoteObject.narrow(env, AccountService.class);
accountService = home.create();
} return accountService;
}
-
8/12/2019 Spring Full
32/103
With Spring IoC the container will
handle the injection of an appropriate
implementation private AccountService accountService = null;
public void setAccountService(AccountService
accountService) { this.accountService = accountService;
}
public void execute(HttpServletRequest req, .)throws Exception {
Account account = createAccount(req);
accountService.updateAccount(account);
}
-
8/12/2019 Spring Full
33/103
AOP Concepts
Applications must be concerned with things like:
Transaction management
Logging
Security
Do these responsibilities belong to the implementation classes?
Should our Service class be responsible for
transaction management, logging, or security?
These concerns are often referred to as crosscutting
concerns
-
8/12/2019 Spring Full
34/103
AOP Concepts
Separate these concerns and define them as
an advice
Before Advice
After Advice Around Advice
Throws Advice
Declaratively weave them into the application
based on certain criteria (pointcuts). Proxies then intercept relevant methods and
silently introduce the advice
-
8/12/2019 Spring Full
35/103
Types of AOP:
Static AOP
Aspects are typically introduced in the byte codeduring the build process or via a custom class loaderat runtime
AspectJ (byte code manipulation at compile time)
JBoss 4, AspectWerkz (Class loader approach)
Dynamic AOP
Create proxies for all advised objects Slightly poorer performance
Easier to configure
-
8/12/2019 Spring Full
36/103
AOP Improvements
Simplified AOP XML Configuration
AspectJ Pointcut Language
@AspectJ Aspects
Dependency Injection of Domain Object
-
8/12/2019 Spring Full
37/103
Spring and AOP
AOP is a enabling technology for proper design
Spring leverages AOP in many support classes
Transactions
Remoting Uses a proxy based setup that enables
method call interception
Spring 1.2.x has own pointcut system butcould support AspectJ if needed
-
8/12/2019 Spring Full
38/103
Spring and AOP
Raw AOP was used but not as widely as it
could have been
Springs proxy based system made AOP
more approachable than AspectJ
However, creating advice was very verbose
Pointcut language wasnt standard
Spring 2.0 makes AOP simpler and more
powerful
-
8/12/2019 Spring Full
39/103
Simplified AOP Configuration
Spring 1.2.x
setMessage1
setMessage2
-
8/12/2019 Spring Full
40/103
Simplified AOP Configuration Spring 2.0
-
8/12/2019 Spring Full
41/103
AspectJ Pointcut Language
Spring AOP now supports pointcuts based
on AspectJs pointcut language
Only supports a subset of the language
That which can be intercepted via proxy Typically anything with execution()
Uses AspectJs interpreter
No chance of Spring introduced bugs Preferred method of writing pointcuts
going forward
-
8/12/2019 Spring Full
42/103
AspectJ Pointcut Language
execution(public !void get*())
execution(public void set*(*))
execution(void Point.setX(int))
execution(public !static * *(..))
-
8/12/2019 Spring Full
43/103
@AspectJ Aspects
A method provided by AspectJ that allows the
use of annotations to describe aspects and
pointcuts
Enables the ability to compile an aspect
with a simple Java compiler and then be
woven by the AspectJ weaver at a later time
Subsequent build step
Class load-time
-
8/12/2019 Spring Full
44/103
@AspectJ Aspects
@Aspect public class AjLoggingAspect {
@Pointcut("execution(* *..Account.*(..))")
public void callsToAccount() {
}
@Before("callsToAccount()") public void before(JoinPoint jp) {
System.out.println("Before [" + jp.toShortString() +
"].");
}
@AfterReturning("callsToAccount()")
public void after() { System.out.println("After.");
}
}
-
8/12/2019 Spring Full
45/103
THE SPRING BEAN CONTAINER
Uses IoC to manage components that make up
an application
Components are expressed as regular Java
Beans
Container manages the relationships between
beans and is responsible for configuring them
Manages the lifecycle of the beans
-
8/12/2019 Spring Full
46/103
Types of Bean Containers:
Bean Factory
Provides basic support for dependency injection
Configuration and lifecycle management
Application ContextBuilds on Bean Factory and adds services for:
Resolving messages from properties files for
internationalization,
Loading generic resources
Publishing events
-
8/12/2019 Spring Full
47/103
Loading a Bean Factory:
public interface Greeting {
String getGreeting();
}
public class WelcomeGreeting implements Greeting {
private String message; public void setMessage(String message) {
this.message = message;
}
public String getGreeting() {
return message; }
}
-
8/12/2019 Spring Full
48/103
Loading a Bean Factory (cont):
Welcome
-
8/12/2019 Spring Full
49/103
Features of Managed Beans:
Default to Singletons
Properties can be set via dependency injection
References to other managed beans
StringsPrimitive types
Collections (lists, set, map, props)
Inner Beans
Autowiring
Parameters may be externalized to property files
-
8/12/2019 Spring Full
50/103
SPRING IN THE BUSINESS TIER
A layer of abstraction for persisting data via one or more of
the following technologies
JDBC
Hibernate, OJB
JDOiBatis
A robust infrastructure for declarative transaction
management that supports local transactions as well as
global transactions via JTA
A simplifying layer for remoting technologies includingEJB, RMI, Hession/Burlap, and Web Services
Useful support for JNDI, JMS, email, task scheduling
-
8/12/2019 Spring Full
51/103
Spring Persistence Support
A technology agnostic data access API that helps
isolate and streamline the way data is served by
the business tier
A consistent and rich exception hierarchy that is smart enough to map technology specific
exceptions to generalized exceptions
A series of template and wrapper classes for
working with JDBC, Hibernate, JDO, etc.
-
8/12/2019 Spring Full
52/103
Traditional JDBC coding techniques:
public void updateCustomer(Customer customer) {
Connection conn = null;
PreparedStatement ps = null; try {
conn = getConnection();
ps = conn.prepareStatement(update customer set +
firstName = ?, lastName = ?, );
ps.setString(1, customer.getFirstName());
ps.setString(2, customer.getLastName());
ps.executeUpdate();
} catch SQLException e) { log.error(e);
} finally {
try { if (ps != null) ps.close(); }
catch (SQLException e) {log.error(e);}
try {if (conn != null) conn.close();}
catch (SQLException e) {log.error(e);}
}
} private Connection getConnection() {
more plumbing code here
}
-
8/12/2019 Spring Full
53/103
Using Spring JDBC template:
public void updateCustomer(Customer customer) { String sql = update customer set +
firstName = ?, lastName = ?, );
Object[] params = new Object[] {
customer.getFirstName(),
customer.getLastName(), };
int[] types = new int[] {
Types.VARCHAR,
Types.VARCHAR,
}; jdbcTemplate.update(sql, params, types);
}
jdbcTemplate can be injected by container
-
8/12/2019 Spring Full
54/103
Operations can also be modeled as
objects: public class UpdateCustomer extends SqlUpdate { public UpdateCustomer(DataSource ds) {
setDataSource(ds);
setSql(update customer set values (?,?..));
declareParameter(new SqlParameter(Types.VARCHAR));
declareParameter(new SqlParameter(Types.VARCHAR));
compile(); }
public int update(Customer customer) {
Object[] params = new Object[] {
customer.getFirstName(),
customer.getLastName()
}; return update(params);
}
}
-
8/12/2019 Spring Full
55/103
Hibernate Support :
configuration and session management for business
objects
A HibernateTemplate class is provided to reduce
need for boilerplate code HibernateDaoSupport class that can be extended for
further abstraction
HibernateException management and mapping
Seamlessly plugs into Spring transaction framework
S i T i S
-
8/12/2019 Spring Full
56/103
Spring Transaction Support
Programmatic Transaction Management
Not as popular as declarative approach When finegrained control is required
Similar to manually controlling JTA UserTransactions
Available via the Spring TransactionTemplate class
Reference typically passed to the business object viaDI
Transaction template holds a property of type
PlatformTransactionManager
PlatformTransactionManager can be animplementation of
Hibernate, JDO, JDBC, or JTA transaction manager
S i T i S
-
8/12/2019 Spring Full
57/103
Spring Transaction Support
Declarative Transaction Management
Uses AOP to wrap calls to transactional objects with code to beginand commit transactions
Transaction propagation behavior
Mandatory, Never, Not Supported, Required, Requires New,
Support, Nested
Similar to EJB style behaviors
Also supports isolation levels
Default, Read Uncommitted, Read Committed, Repeatable
Read, Serializable
S i R i
-
8/12/2019 Spring Full
58/103
Spring Remoting
RMIProvides a RmiProxyFactoryBean that can be configured to
connect to an RMI service
Provides a RmiServiceExporter that can be configured to expose
any Spring managed bean as an RMI service
Caucho (Hessian/Burlap)
Provides a Hession(Burlap)ProxyFactoryBean and ServiceExporter
to connect to and expose Caucho remote services respectively
Also requires configuration of web application context and mapping
of appropriate servlet url
Spring Http Invoker
Similar to Caucho except using nonproprietaryobject serialization techniques
S i R i
-
8/12/2019 Spring Full
59/103
Spring Remoting
EJBSpring allows EJBs to be declared as beans within the
Spring configuration file making it possible to inject
references to them in other beans
Spring provides the ability to write EJBs that wrap Springconfigured Java Beans
Web Services via JAXRPC
Client side support via the JaxRpcPortProxyFactoryBean
ServletEndpointSupport class allows services that sit behind
a servlet to access the Spring Application Context
A i EJB i S i A
-
8/12/2019 Spring Full
60/103
Accessing EJBs in Spring Apps:
LocalStatelessSessionProxyFactoryBeanProxy for local SLSB
Finds and caches the EJB Home upon first access
Intercepts method calls and invokes corresponding
method on ejb SimpleRemoteStatelessSessionProxyFactoryBean
Proxy for remote SLSB
Will also catch Remote Exceptions and rethrow
as unchecked exceptions Stateful session beans are NOT proxied
Simplified lookup via Spring JndiObjectFactoryBean
S i J2EE
-
8/12/2019 Spring Full
61/103
Spring J2EE
JNDI Lookup
Moves verbose lookup code into theframework
Sending EmailTemplate classes that support COS mail Java
Mail
Event Scheduling
Support JDK Timer
OpenSymphony Quartz events
A d
-
8/12/2019 Spring Full
62/103
Agenda
Introduction to Spring MVC
Overview of architecture
Overview and examples of individual MVC
components
In depth examples of forms processing and
validation
Miscellaneous topics
Wh i S i MVC?
-
8/12/2019 Spring Full
63/103
What is Spring MVC?
Request-response based web application
framework, such as Struts and WebWork
Flexible and extensible via components interfaces
Simplifies testing through Dependency Injection Simplifies form handling through its parameter
binding, validation and error handling
Abstracts view technology (JSP, Velocity,
FreeMarker Excel , PDF)
S i MVC A hi
-
8/12/2019 Spring Full
64/103
Spring MVC Architecture
Di h S l
-
8/12/2019 Spring Full
65/103
DispatcherServlet
Di h S l
-
8/12/2019 Spring Full
66/103
DispatcherServlet
Example of Front Controllerpattern - entry
point for all Spring MVC requests
Loads WebApplicationContext and well are
parent contexts Controls workflow and mediates between
MVC components
Loads sensible default components if noneare configured
C fi i h Di h S l
-
8/12/2019 Spring Full
67/103
Configuring the DispatcherServlet
web.xml
dispatcher
org.springframework.web.servlet.DispatcherServlet
1
dispatcher
*.htm
C fi ri th Di p t h rS r l t ( td)
-
8/12/2019 Spring Full
68/103
Configuring the DispatcherServlet (contd)
web.xml
dispatcher
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
WEB-INF/mvc.xml
1
Config ring the Disp t herSer let ( ontd)
-
8/12/2019 Spring Full
69/103
Configuring the DispatcherServlet (contd)
web.xml
contextConfigLocation
/WEB-INF/services.xml
org.springframework.web.context.ContextLoaderListener
configures parent context
H dl M i
-
8/12/2019 Spring Full
70/103
HandlerMapping
H dl rM ppi
-
8/12/2019 Spring Full
71/103
HandlerMapping
Maps incoming requests to a corresponding
Handler, typically a Controller
Rarely needs to be implemented directly
many useful implementations are provided Also ties Interceptors to a mapped
Controllers
Can provided multiple HandlerMappings;priority is set using Orderedinterface
BeanNameUrlHandlerMapping
-
8/12/2019 Spring Full
72/103
BeanNameUrlHandlerMapping
Maps a URL to a bean registered with thesame namee.g. /simple.htm maps to abean named /simple.htm
Can give bean multiple names (aliases)separated by spaces
Mustuse name attribute/ is not allowed inXML id attribute
Can use wild card in bean names (/simple*) Default HandlerMapping, but not preferred
BeanNameUrlHandlerMapping
-
8/12/2019 Spring Full
73/103
BeanNameUrlHandlerMapping
dispatcher-servlet.xml
SimpleUrlHandlerMapping
-
8/12/2019 Spring Full
74/103
SimpleUrlHandlerMapping
Most common way to map request URLs tohandlers
Configured by a list of name/value pairs
consisting of URLs and bean names Can use wild card in bean names (/simple*)
SimpleUrlHandlerMapping
-
8/12/2019 Spring Full
75/103
SimpleUrlHandlerMapping
dispatcher-servlet.xml
simpleController
testController
ControllerClassNameHandlerMapping
-
8/12/2019 Spring Full
76/103
ControllerClassNameHandlerMapping
Part of Spring 2.0's Convention over Configuration Maps a URL to the shortened class nameof a
Controller bean
Removed "Controller" from class name
Converts to all lower case
Prepend and "/" and append a "*"
Example:
SimpleController -> /simple*
Greatly reduces amount of mapping configurations
ControllerClassNameHandlerMapping
-
8/12/2019 Spring Full
77/103
ControllerClassNameHandlerMapping
dispatcher-servlet.xml
Controllers
-
8/12/2019 Spring Full
78/103
Controllers
Controller interface
-
8/12/2019 Spring Full
79/103
Controllerinterface
Handles the processing of the request
Interface parameters mimics HttpServlet
handleRequest(HttpServletRequest,
HttpServletResponse) Returns aModelAndViewobject
Implementations are typically thread-safe
Rarely implemented directlySpringprovides many useful implementations
ModelAndView object
-
8/12/2019 Spring Full
80/103
ModelAndViewobject
Encapsulates both model and view that is tobe used to render model
Model is represented as a java.util.Map
Objects can be added to without name: addObject(String, Object) added with
explicit name
addObject(Object)added using name
generation (Convention over Configuration) View is represented by StringorViewobject
Analogous to StrutsAction
Controller implementations
-
8/12/2019 Spring Full
81/103
Controllerimplementations
Typical Controllers in your application will:
Be completely configured via wiring (no code)
Contain simple web processing
Handle web layer and defer to service layer foradditional processing
Parameter handling
View determination
Input validation
AbstractController
-
8/12/2019 Spring Full
82/103
AbstractController
Provides minimal behavior Used for handling simple requests
protected ModelAndView handleRequestInternal(HttpServletRequest request,
HttpServletResponse response) {
String text = service.getText();
return new ModelAndView(
"simple", "text", text);
}
AbstractController
-
8/12/2019 Spring Full
83/103
AbstractController
Provides minimal behavior Used for handling simple requests
protected ModelAndView handleRequestInternal(HttpServletRequest request,
HttpServletResponse response) {
String text = service.getText();
return new ModelAndView(
"simple", "text", text);
}
ThrowawayController
-
8/12/2019 Spring Full
84/103
ThrowawayController
Not part of the Controllerhierarchy
Parameters are mapped directlyonto
the controller
Useful when there is not model object
to map to
Must scope bean as prototype sincethese are inherently not thread-safe
ThrowawayController
-
8/12/2019 Spring Full
85/103
ThrowawayController
dispatcher-servlet.xml
configured as prototype bean
ThrowawayController
-
8/12/2019 Spring Full
86/103
ThrowawayControllerpublic class ExampleThrowawayController
implements ThrowawayController {
private String message;
public void setMessage(String message) {
this.message = message;
}
public ModelAndView execute() throws Exception {
String hashCodeMessage = "[" + hashCode()
+ "] - " + message;
return new ModelAndView("throwaway", "message",hashCodeMessage);
}
}
Command Controllers
-
8/12/2019 Spring Full
87/103
Command Controllers
Family of Controllers that bind requestparameters to command objects
Command object can be any POJOtypically a domain object
Provides functionality: Binding custom types
Automatic and custom validation
Automatically or programmatically creating
command object
We will cover in more detail later
Command Controllers
-
8/12/2019 Spring Full
88/103
Command Controllers
AbstractCommandController
Provides binding and validation
SimpleFormControllerIn addition to
binding and validation, provides rich work
flow for processing forms
Most useful for processing form
Detailed example to come later
AbstractWizardFormControllerForforms that span multiple pages
Additional Controllers
-
8/12/2019 Spring Full
89/103
Additional Controllers
ServletWrappingControllerandServletForwardingController
specialty Controllers to wrap Struts servlet in
Spring interceptors ParameterizableViewController
simply forwards to a configured view without
exposing view technology to client
UrlFilenameViewControllerconverts
a URL to a view name
Interceptors
-
8/12/2019 Spring Full
90/103
Interceptors
Interceptors
-
8/12/2019 Spring Full
91/103
Interceptors
Add additional functionality before and afterrequest
Contains to interception methods
preHandleandpostHandle Contains one callback methodafterCompletetion
Associated with a set of Controllersvia aHandlerMapping
Interceptor implementations
-
8/12/2019 Spring Full
92/103
Interceptor implementations
Implement either HandlerInterceptororWebRequestInterceptor
Spring provides a few implementations
OvenXxxInViewInteceptorUsed with
ORM frameworks JDO, JPA and Hibernate
UserRoleAuthorizationInterceptor
Provides authorization against a set of roles
Other useful customizations: custom security,caching,
ViewResolver
-
8/12/2019 Spring Full
93/103
ViewResolver
ViewResolver
-
8/12/2019 Spring Full
94/103
ViewResolver
Resolves a logical view name to a Viewobject
Orderable, so they be chained
For JSP user, typical implementation isInternalResourceViewResolver:
-
8/12/2019 Spring Full
95/103
p
VelocityViewResolverConvenience
class for Velocity templates
FreeMarkerViewResolverConvenience
class for FreeMarker templates
ResourceBundleViewResolver
Mappings are contained within a properties file
Supports internationalization
XmlViewResolver - Mappings are containedwith an XML file
View
-
8/12/2019 Spring Full
96/103
View
View
-
8/12/2019 Spring Full
97/103
Contains implementations for severaltemplate technologies:
InternalResourceView(JSP)
JstlView(JSP + JSTL)
VelocityView(Velocity)
FreeMarkerView(FreeMarker)
TilesView(Tiles)
TilesJstlView(Tiles + JSTL)
View
-
8/12/2019 Spring Full
98/103
Also contains views that support rendering Excel files
PDF files
XSLT results Jasper Reports
Processing forms with Spring MVC
-
8/12/2019 Spring Full
99/103
g p g
Leveraging workflow provided bySimpleFormController
Provides both form display and processing workflow with custom hooks
Be default, GETindicates form displaying andPOSTindicates form processing
Displaying and processing done by sameController
Complete workflow is quite involvedwe willonly hit the highlights
Registering the Command class
-
8/12/2019 Spring Full
100/103
g g
SimpleFormControllers are associated with aCommand class Since these are tightly coupled, configuring with the
Controller class is acceptable
public class PlayerFormControllerextends SimpleFormController {
public PlayerFormController() {
setCommandClass(Player.class);setCommandName("player");
}
Displaying a form
-
8/12/2019 Spring Full
101/103
p y g
We will discuss three methods in the workflow for displaying the form
formBackingObjectReturns the command
object used in the form. initBinder Registered custom
PropertyEditors for rendering command properties
referenceData Loads additional data to be
displayed on page
Processing a form
-
8/12/2019 Spring Full
102/103
g
Two main methods for form processing are: onBindAndValidate()Allows for custom
binding and validation
doSubmitAction() Callback to handlesuccessful form submission. Typical
implementation would be to persist command
object to database.
Spring MVC
-
8/12/2019 Spring Full
103/103
p g
Other Spring MVC functionality
Transparent handling of Multipart requests
Support for customized Look & Feels through
Themes Support for internalization
Convenience ServletContextListener for initializing
Log4J