Tuesday, 29 July 2008

Spring Recipes By Gary Mak

Just now i completed reading Spring Recipes By Gary Mak

Nice book written by Gary Mak.I skipped complete Part 3 as currently i was not interested in those topics as of now.

I wanted to share few important points i found from this book.

1) Understanding Different Types of Dependency Injection

Injecting a dependency via a settermethod is not the only way of implementing DI. You will need different types of DI in different scenarios.

There are threemain types of DI:

• Interface injection (Type 1 IoC)
• Setter injection (Type 2 IoC)
• Constructor injection (Type 3 IoC)


2) Checking Properties of the Simple Types

Suppose one property was not set for a bean class. Then the class may use the property which was null and it is a problem. This kind of issue is often very hard to debug, especially in a complicated bean. Fortunately, Spring is able to check if all properties of certain types have been set. To ask Spring to check properties of the simple types (i.e., the primitive and collection types), set the dependency-check attribute of <bean> to
simple.

<bean id="someId" class="SomeClass" dependency-check="simple">
................
</bean>

If any properties of such types have not been set, an UnsatisfiedDependencyException will be thrown, indicating the unset property.

3) Checking Properties of All Types

If you would like to check all bean properties whatever the type is, you can change the dependency-check attribute to all.

<bean id="someId" class="SomeClass" dependency-check="all">
...............
</bean>

4) Auto-Wiring Modes Supported by Spring

Below is the table that describes them clearly



no*
byName
byType
constructor
autodetect
ModeDescription
No auto-wiring will be performed. You must wire the dependencies explicitly.
For each bean property, wire a bean whose name is the same as the property’s.
For each bean property, wire a bean whose type is compatible with the property’s. If more than one bean is found, an UnsatisfiedDependencyException will be thrown.
For each argument of each constructor, first find a bean whose type is
compatible with the argument’s. Then pick the constructor with the most matching arguments. In case of any ambiguity, an UnsatisfiedDependencyException will be thrown.
If a default constructor with no argument is found, the dependencies will be
auto-wired by type. Otherwise, they will be auto-wired by constructor.


5) The main problem of auto-wiring by type is that sometimes there will be more than one bean in the IoC container compatible with the target type. In this case, Spring will not be able to decide which bean is most suitable for the property, and hence cannot perform autowiring.

6) Auto-Wiring by Name

Another mode of auto-wiring is byName, which can sometimes resolve the problems of autowiring by type. It works very similarly to byType, but in this case, Spring will attempt to wire a bean with the same name, rather than with the compatible type. As the bean name is unique within a container, auto-wiring by name will not cause ambiguity.

<beans ...>
<bean id="sequenceGenerator" class="SequenceGenerator"
autowire="byName">
<property name="initial" value="100000" />
<property name="suffix" value="A" />
</bean>
<bean id="prefixGenerator" class="DatePrefixGenerator">
<property name="pattern" value="yyyyMMdd" />
</bean>
</beans>

However, auto-wiring by name will not work in all cases. Sometimes it’s not possible for you to make the name of the target bean the same as your property. In practice, you often need to specify ambiguous dependencies explicitly, while keeping others auto-wired. That means you employ a mixture of explicit wiring and auto-wiring.

7) Auto-Wiring Beans with @Autowired and @Resource

Auto-wiring by setting the autowire attribute in the bean configuration file will wire all properties of a bean. It’s not flexible enough to wire particular properties only. Moreover, you can only auto-wire beans either by type or by name. If neither strategy satisfies your requirements,you must wire your beans explicitly.

Solution
Spring 2.5 makes extensive enhancements to the auto-wiring feature. You can auto-wire a particular property by annotating a setter method, a constructor, a field, or even an arbitrary method with the @Autowired annotation, or the @Resource annotation defined in JSR-250: Common Annotations for the Java Platform. That means you have one more option besides setting the autowire attribute to satisfy your requirements. However, this annotation-based option requires you to be using Java 1.5 or higher.

To ask Spring to auto-wire the bean properties with @Autowired or @Resource, you have to register an AutowiredAnnotationBeanPostProcessor instance in the IoC container. If you are using a bean factory, you have to register this bean post processor through the API. Otherwise, you can just declare an instance of it in your application context.

<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />

Or you can simply include the <context:annotation-config> element in your bean configuration file and an AutowiredAnnotationBeanPostProcessor instance will automatically get registered.

8) Auto-Wiring by Type with Qualifiers

By default, auto-wiring by type will not work when there is more than one bean with the compatible type in the IoC container. However, Spring allows you to specify a candidate bean by providing its name in the @Qualifier annotation.

9) Inheriting Bean Configuration

Problem:
When configuring beans in the Spring IoC container, you may have more than one bean
sharing some common configurations, such as bean properties and attributes in the <bean>element. You often have to repeat these configurations for multiple beans.

Solution:

Spring allows you to extract the common bean configurations to form a parent bean. The beans that inherit from this parent bean are called child beans. The child beans will inherit the bean configurations, including bean properties and attributes in the <bean> element, from the parent bean to avoid duplicate configurations. The child beans can also override the inherited configurations when necessary.

The parent bean can act as a configuration template and also as a bean instance at the same time. However, if you want the parent bean to act only as a template that cannot be retrieved, you must set the abstract attribute to true, asking Spring not to instantiate this bean.

10) Defining Collections Using Factory Beans and the Utility Schema

When using the basic collection tags to define collections, you can’t specify the concrete class of a collection, such as LinkedList, TreeSet, or TreeMap.Moreover, you cannot share a collection among different beans by defining it as a stand-alone bean for other beans to refer to.

Solution:

Spring provides a couple of options to overcome the shortcomings of the basic collection tags. One option is to use corresponding collection factory beans like ListFactoryBean, SetFactoryBean, and MapFactoryBean. A factory bean is a special kind of Spring bean that is used for creating another bean. The second option is to use collection tags such as , , and in the util schema introduced in Spring 2.x.

11) Creating Beans by Invoking a Static Factory Method

Problem

You would like to create a bean in the Spring IoC container by invoking a static factory method,whose purpose is to encapsulate the object-creation process in a static method. The client who requests an object can simply make a call to this method without knowing about the creation detail.

Solution
Spring supports creating a bean by invoking a static factory method, which should be specified in the factory-method attribute.

Example

<beans ...>
<bean id="aaa" class="roductCreator"
factory-method="createProduct">
<constructor-arg value="aaa" />
</bean>

12) Below table describes Valid Bean Scopes in Spring








ScopeDescription
singletonCreates a single bean instance per Spring IoC container
requestCreates a single bean instance per HTTP request; only valid in the context of a
web application
singletonCreates a single bean instance per Spring IoC container
sessionCreates a single bean instance per HTTP session; only valid in the context of a
web application
globalSessionCreates a single bean instance per global HTTP session; only valid in the
context of a portal application


In Spring 1.x, singleton and prototype are the only two valid bean scopes, and they are specified by the singleton attribute (i.e., singleton="true" or singleton="false"), not the scope attribute.

13) Customizing Bean Initialization and Destruction

Problem:

Many real-world components have to perform certain types of initialization tasks before they are ready to be used. Such tasks include opening a file, opening a network/database connection,allocating memory, and so on. Also, they have to perform the corresponding destruction tasks at the end of their life cycle. So, you have a need to customize bean initialization and destruction in the Spring IoC container.

Solution

In addition to bean registration, the Spring IoC container is also responsible for managing the life cycle of your beans, and it allows you to perform custom tasks at particular points of their life cycle. Your tasks should be encapsulated in callback methods for the Spring IoC container to call at a suitable time.

The following list shows the steps through which the Spring IoC container manages the life cycle of a bean. This list will be expanded as more features of the IoC container are introduced.

1. Create the bean instance either by a constructor or by a factory method.
2. Set the values and bean references to the bean properties.
3. Call the initialization callback methods.
4. The bean is ready to be used.
5. When the container is shut down, call the destruction callback methods.

There are three ways that Spring can recognize your initialization and destruction callback methods. First, your bean can implement the InitializingBean and DisposableBean life cycle interfaces and implement the afterPropertiesSet() and destroy() methods for initialization and destruction. Second, you can set the init-method and destroy-method attributes in the bean declaration and specify the callback method names. In Spring 2.5, you can also annotate the initialization and destruction callback methods with the life cycle annotations @PostConstruct and @PreDestroy, which are defined in JSR-250: Common Annotations for the
Java Platform. Then you can register a CommonAnnotationBeanPostProcessor instance in the IoC container to call these callback methods.

Annotating the @PostConstruct and @PreDestroy Annotations

In Spring 2.5, you can annotate the initialization and destruction callback methods with the JSR-250 life cycle annotations @PostConstruct and @PreDestroy.

14) A bean post processor allows additional bean processing before and after the initialization callback method. The main characteristic of a bean post processor is that it will process all the bean instances in the IoC container one by one, not just a single bean instance.

The basic requirement of a bean post processor is to implement the BeanPostProcessor interface. You can process every bean before and after the initialization callback method by implementing the postProcessBeforeInitialization() and postProcessAfterInitialization() methods

15) Externalizing Bean Configurations

Problem
When configuring beans in the configuration file, you must remember that it’s not a good practice to mix deployment details, such as the file path, server address, username, and password, with your bean configurations. Usually, the bean configurations are written by application developers while the deployment details are matters for the deployers or system administrators.

Solution
Spring comes with a bean factory post processor called PropertyPlaceholderConfigurer for you to externalize part of the bean configurations into a properties file. You can use variables of the form ${var} in your bean configuration file and PropertyPlaceholderConfigurer will load the properties from a properties file and use them to replace the variables.

A bean factory post processor differs from a bean post processor in that its target is the IoC container—either the bean factory or the application context—not the bean instances. It will take effect on the IoC container after it loads the bean configurations but before any of the bean instances are created. The typical usage of a bean factory post processor is to alter the bean configurations before the beans are instantiated. Spring comes with several bean factory post processors for you to use. In practice, you seldom need to write your own bean factory
post processors.

16) Loading External Resources

Problem Sometimes your application may need to read external resources (e.g., text files, XML files,properties file, or image files) from different locations (e.g., a file system, classpath, or URL).Usually, you have to deal with different APIs for loading resources from different locations.

Solution

Spring’s resource loader provides a unified getResource() method for you to retrieve an external resource by a resource path. You can specify different prefixes for this path to load resources from different locations. To load a resource from a file system, you use the file prefix.To load a resource from the classpath, you use the classpath prefix. You may also specify a URL in this resource path.

Resource is a general interface in Spring for representing an external resource. The resource loader’s getResource() method will decide which Resource implementation to instantiate according to the resource path.

17) Modularizing Crosscutting Concerns with Dynamic Proxy

Problem

As non-modularized crosscutting concerns will cause the code tangling and code scattering problems, you would like to seek a method to modularize them. However, they are often hard to modularize with the traditional object-oriented approach, as they span multiple modules of an application.

Solution

You can apply a design pattern called proxy to separate crosscutting concerns from core concerns.Proxy is one of the 23 GoF (Gang of Four) object-oriented design patterns, which belong to the “structural pattern” category.

The principle of the proxy design pattern is to wrap an object with a proxy and use this proxy to substitute for the original object. Any calls that were made to the original object will go through the proxy first.

The proxy object is responsible for deciding when and whether to forward method calls to the original object. In the meanwhile, the proxy can also perform additional tasks around each method call. So, the proxy would be a good place to implement the crosscutting concerns.

In Java, there are two ways to implement the proxy design pattern. The traditional one is write a static proxy in pure object-oriented style. Static proxy works by wrapping an object with a dedicated proxy to perform additional tasks around each method call. The dedication means you have to write a proxy class for each interface to be able to substitute for the original implementation, which is very inefficient in a large application with hundreds or thousands of components.

Another method is through the dynamic proxy support offered by JDK version 1.3 or higher. It supports creating a proxy dynamically for any object. The only restriction is that the object must implement at least one interface, and only the calls to the methods declared in the interfaces will go through the proxy. However, there’s another kind of proxy, CGLIB proxy,that doesn’t have this restriction. It can handle all the methods declared in a class even if it doesn’t implement any interface.

Dynamic proxies are implemented with the Java Reflection API, so they can be used in a more general way than static proxies. For this reason, dynamic proxy is one of the core technologies used by Spring for its AOP implementation.

18) Modularizing Crosscutting Concerns with Classic Spring Advices

Problem

As crosscutting concerns are often hard to modularize with the traditional object-oriented approach, you would like to seek another approach to modularize them. Dynamic proxy is helpful in modularizing crosscutting concerns, but it’s too demanding for an application developer to write such low-level proxy code.

Solution

AOP defines a group of high-level concepts for application developers to express their crosscutting concerns. First, the crosscutting action to take at a particular execution point is encapsulated in an advice. For example, you can encapsulate the logging and validation actions in one or more advices.

Classic Spring AOP supports four types of advices, each of which takes effect at different times of an execution point. In the formal AOP definition, there are many types of execution points, including method executions, constructor executions, and field accesses. However,Spring AOP only supports method executions. So, the definition of the four classic advice types can be narrowed down to the following:

• Before advice: Before the method execution

• After returning advice: After the method returns a result

• After throwing advice: After the method throws an exception

• Around advice: Around the method execution When using the classic Spring AOP approach, advices are written by implementing one of the proprietary advice interfaces.

19) Before Advices

A before advice takes effect before the method execution. It is created by implementing the MethodBeforeAdvice interface. In the before() method, you can get access to the method detail as well as the arguments.

public class LoggingBeforeAdvice implements MethodBeforeAdvice {

private Log log = LogFactory.getLog(this.getClass());

public void before(Method method, Object[] args, Object target)
throws Throwable {
log.info("The method " + method.getName() + "() begins with " + Arrays.toString(args));
}
}


20) Matching Methods with Classic Spring Pointcuts

Problem
When you specify an advice for an AOP proxy, all of the methods declared in the target class/proxy interfaces will be advised. But in most situations, you only want some of them to be advised.

Solution

Pointcut is another core AOP concept, usually appearing as an expression, and allowing you to match certain program execution points to apply an advice. In classic Spring AOP, pointcuts are also declared as Spring beans by using pointcut classes.

Spring provides a family of pointcut classes for you to match program execution points.You can simply declare beans of these types in your bean configuration file to define pointcuts.However, if you find that the built-in pointcut classes cannot satisfy your needs, you can write your own by extending StaticMethodMatcherPointcut or DynamicMethodMatcherPointcut.The former matches execution points by the static class and method information only, while the latter matches them by the dynamic argument values as well.

21) Regular Expression Pointcuts

In addition to matching methods by name, you can also match them using a regular expression.You can make use of RegexpMethodPointcutAdvisor to specify one or more regular expressions. For example, the following regular expressions match the methods with the keyword mul or div in the method name:

<beans ...>
...
<bean id="regexpAdvisor" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
<property name="patterns">
<list>
<value>.*mul.*</value>
<value>.*div.*</value>
</list>
</property>
<property name="advice" ref="loggingAroundAdvice" />
</bean>
<bean id="arithmeticCalculatorProxy"
class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target" ref="arithmeticCalculator" />
<property name="interceptorNames">
<list>
<value>methodNameAdvisor</value>
<value>regexpAdvisor</value>
</list>
</property>
</bean>
</beans>

22) AspectJ Expression Pointcuts

The AspectJ framework defines a powerful pointcut expression language. You can make use of AspectJExpressionPointcutAdvisor to match your methods using an AspectJ pointcut expression.For example, the following AspectJ pointcut expression matches all the methods with the keyword To in the method name.

23) AOP is a complement to OOP that specializes in modularizing crosscutting concerns. It defines a set of high-level concepts such as advice and pointcut for application developers to express their crosscutting concerns.

An advice encapsulates the action to take at a particular program execution point. Classic Spring AOP supports four types of advice: before, after returning, after throwing, and around.To apply your advices to a bean in the Spring IoC container, you have to create a proxy by using ProxyFactoryBean.

24) Enabling AspectJ Annotation Support in Spring

Problem

Spring version 2.x supports the use of POJO aspects written with AspectJ annotations in its AOP framework. But first you have to enable AspectJ annotation support in the Spring IoC container.

Solution

To enable AspectJ annotation support in the Spring IoC container, you only have to define an empty XML element in your bean configuration file. Then Spring will automatically create proxies for any of your beans that are matched by your AspectJ aspects.

TO enable AspectJ annotation support for this application, you just define an empty XML element, , in your bean configuration file. Moreover, you must add the aop schema definition to your root element. When the Spring IoC container notices the element in your bean configuration file, it will automatically create proxies for your beans that are matched by your AspectJ aspects.

25) Declaring Aspects with AspectJ Annotations

Problem
Since merging with AspectWerkz in version 5, AspectJ supports its aspects to be written as POJOs annotated with a set of AspectJ annotations. Aspects of this kind are also supported by the Spring 2.x AOP framework. But they must be registered in the Spring IoC container to take effect.

Solution
You register AspectJ aspects in Spring simply by declaring them as bean instances in the IoC container.With AspectJ enabled in the Spring IoC container, it will create proxies for your beans that are matched by your AspectJ aspects.

Written with AspectJ annotations, an aspect is simply a Java class with the @Aspect annotation.An advice is a simple Java method with one of the advice annotations. AspectJ supports five types of advice annotations: @Before, @After, @AfterReturning, @AfterThrowing, and @Around.

26) Before Advices

To create a before advice to handle crosscutting concerns before particular program execution points, you use the @Before annotation and include the pointcut expression as the annotation value

27) After Advices

An after advice is executed after a join point finishes, whenever it returns a result or throws an exception abnormally. The following after advice logs the calculator method ending. An aspect may include one or more advices.

28) After Returning Advices

An after advice is executed regardless of whether a join point returns normally or throws an exception. If you would like to perform logging only when a join point returns, you should replace the after advice with an after returning advice.

In an after returning advice, you can get access to the return value of a join point by adding a returning attribute to the @AfterReturning annotation. The value of this attribute should be the argument name of this advice method for the return value to pass in. Then you have to add an argument to the advice method signature with this name. At runtime, Spring AOP will pass in the return value through this argument. Also note that the original pointcut expression needs to be presented in the pointcut attribute instead.

Example:

@AfterReturning(
pointcut = "execution(* *.*(..))",returning = "result")
public void logAfterReturning(JoinPoint joinPoint, Object result) {
System.out.println("The method " + joinPoint.getSignature().getName()
+ "() ends with " + result);
}

29) After Throwing Advices

An after throwing advice is executed only when an exception is thrown by a join point.

Similarly, the exception thrown by the join point can be accessed by adding a throwing attribute to the @AfterThrowing annotation. The type Throwable is the superclass of all errors and exceptions in the Java language.

30) Around Advices

The last type of advice is an around advice. It is the most powerful of all the advice types. It gains full control of a join point, so you can combine all the actions of the preceding advices into one single advice. You can even control when, and whether, to proceed with the original join point execution.

The following around advice is the combination of the before, after returning, and after throwing advices you created before. Note that for an around advice, the argument type of the join point must be ProceedingJoinPoint. It’s a subinterface of JoinPoint that allows you to control when to proceed with the original join point.

31) A common rule for choosing an advice type is to use the least powerful one that can satisfy your requirements.

32) Introducing Behaviors to Your Beans

Problem
Sometimes you may have a group of classes that share a common behavior. In OOP, they must extend the same base class or implement the same interface. This issue is actually a crosscutting concern that can be modularized with AOP.

In addition, the single inheritance mechanism of Java only allows a class to extend one base class at most. So, you cannot inherit behaviors from multiple implementation classes at the same time.

Solution

Introduction is a special type of advice in AOP. It allows your objects to implement an interface dynamically by providing an implementation class for that interface. It seems as if your objects had extended the implementation class at runtime.

Moreover, you are able to introduce multiple interfaces with multiple implementation classes to your objects at the same time. This can achieve the same effect as multiple inheritance.

33) Configuring a Data Source in Spring

The javax.sql.DataSource interface is a standard interface defined by the JDBC specification.There are many data source implementations provided by different vendors and projects. It is very easy to switch between different data source implementations because they implement the common DataSource interface. As a Java application framework, Spring also provides several convenient but less powerful data source implementations. The simplest one is DriverManagerDataSource, which opens a new connection every time it’s requested.

DriverManagerDataSource is not an efficient data source implementation, as it opens a new connection for the client every time it’s requested. Another data source implementation provided by Spring is SingleConnectionDataSource. As its name indicates, this maintains only a single connection that’s reused all the time and never closed. Obviously, it is not suitable in a multithreaded environment.

34) The concept of transactions can be described with four key properties: atomicity, consistency,isolation, and durability (ACID). These are described following:

Atomicity: A transaction is an atomic operation that consists of a series of actions. The atomicity of a transaction ensures that the actions either complete entirely or take no effect at all.

Consistency: Once all actions of a transaction have completed, the transaction is committed.
Then your data and resources will be in a consistent state that conforms to business rules.

Isolation: As theremay bemany transactions processing with the same data set at the same time, each transaction should be isolated fromothers to prevent data corruption.

Durability: Once a transaction has completed, its result should be durable to survive any systemfailure. Usually, the result of a transaction is written to persistent storage.

35) Below are Propagation Behaviors Supported by Spring









REQUIREDIf there’s an existing transaction in progress, the currentmethod should run
within this transaction. Otherwise, it should start a new transaction and run
within its own transaction.
REQUIRES_NEWThe currentmethodmust start a new transaction and run within its own
transaction. If there’s an existing transaction in progress, it should be
suspended.
SUPPORTSIf there’s an existing transaction in progress, the currentmethod can run within
this transaction. Otherwise, it is not necessary to run within a transaction.
NOT_SUPPORTEDThe currentmethod should not run within a transaction. If there’s an existing
transaction in progress, it should be suspended.
MANDATORYThe currentmethodmust run within a transaction. If there’s no existing
transaction in progress, an exception will be thrown.
NEVERThe currentmethod should not run within a transaction. If there’s an existing
transaction in progress, an exception will be thrown.
NESTEDIf there’s an existing transaction in progress, the currentmethod should run
within the nested transaction (supported by the JDBC 3.0 save point feature) of
this transaction. Otherwise, it should start a new transaction and run within its
own transaction.


36) Below are Isolation Levels Supported by Spring.








IsolationDescription
DEFAULTUses the default isolation level of the underlying database. Formost
databases, the default isolation level is READ_COMMITTED.
READ_UNCOMMITTEDAllows a transaction to read uncommitted changes by other transactions.
The dirty read, non-repeatable read, and phantomread problemsmay
occur.
READ_COMMITTEDAllows a transaction to read only those changes that have been committed
by other transactions. The dirty read problemcan be avoided, but the nonrepeatable
read and phantomread problemsmay still occur.
REPEATABLE_READEnsures that a transaction can read identical values froma fieldmultiple
times. For the duration of this transaction, updatesmade by other transactions to this field are prohibited. The dirty read and non-repeatable read problems can be avoided, but the phantomread problemmay still
occur.
SERIALIZABLEEnsures that a transaction can read identical rows froma tablemultiple
times. For the duration of this transaction, inserts, updates, and deletes made by other transactions to this table are prohibited. All the concurrency problems can be avoided, but the performance will be low.


37) The central component of Spring MVC is DispatcherServlet. As its name indicates, it mainly dispatches requests to appropriate handlers for them to handle the requests. It is the only servlet you need to configure in the web deployment descriptor. DispatcherServlet implements one of Sun’s core Java EE design patterns called front controller. It acts as the front controller of the Spring MVC framework, and every web request must go through it so that it can manage the entire request-handling process.

38) Mapping Requests to Handlers

Problem

When DispatcherServlet receives a web request, it will simply dispatch the request to an appropriate handler for handling the request. You would like to define a strategy for DispatcherServlet to map requests to handlers.

Solution

In a Spring MVC application, web requests are mapped to handlers by one or more handler mapping beans declared in the web application context. These beans have to implement the HandlerMapping interface for DispatcherServlet to auto-detect them. Spring MVC comes with several HandlerMapping implementations for you to map requests using different strategies. By default, if you don’t have a handler mapping configured explicitly, DispatcherServlet will use BeanNameUrlHandlerMapping as its default handler mapping, which maps requests to handlers according to the URL patterns specified in the bean names. So, if you are satisfied with this strategy, you don’t need to define your own handler mappings.

Handler mappings match URLs according to their paths relative to the context path (i.e.,the web application context’s deployed path) and the servlet path (i.e., the path mapped to DispatcherServlet). So, for the URL http://localhost:8080/court/welcome.htm, the path to match is /welcome.htm, as the context path is /court and there’s no servlet path.

39) Creating a Controller with a Parameterized View

Problem When creating a controller, you don’t want to hard-code the view name in the controller class.Instead, you would like the view name to be parameterized so that you can specify it in the bean configuration file.

Solution
ParameterizableViewController is a subclass of AbstractController that defines a viewName property with both getter and setter methods. You can use this controller class directly for a controller that only renders a view to users without any processing logic, or you can extend this controller class to inherit the viewName property.

40) Handling Forms with Form Controllers

Problem
In a web application, you often have to deal with forms. A form controller has to show a form to a user and also handle the form submission. Form handling can be a very complex and variable task. You will get involved in too many form-handling details if you build your form controller from scratch.

Solution
The SimpleFormController class provided by Spring MVC defines the basic form-handling
flow. It supports the concept of a command object and can bind form field values to a command object’s properties of the same name. By extending the SimpleFormController class,your controller will inherit the ability to handle forms.

When SimpleFormController is asked to show a form by an HTTP GET request, it will render the form view to the user. Then when the form is submitted by an HTTP POST request,SimpleFormController will handle the form submission by binding the form field values to a command object and invoking the onSubmit() method. If the form is handled successfully, it will render the success view to the user. Otherwise, it will render the form view again with the errors.

To adapt to different form requirements, SimpleFormController allows you to customize
the form-handling flow by overriding several life cycle methods.

Hope you enjoy reading this book

About the Author

Gary Mak

Gary Mak has been a technical architect and application developer on the enterprise Java platform for six years. In his career, Gary has developed a number of Java–based software projects, most of which are core application frameworks and software tools. He enjoys designing and implementing the complex parts of software projects.

Gary is a Sun certified Java programmer and has a master’s degree in computer science. His research interests include object–oriented technology, aspect–oriented technology, design patterns, and software reuse. Gary specializes in building enterprise applications on frameworks including Spring, Hibernate, JPA, Struts, JSF, and Tapestry. He has been using the Spring framework in his projects for four years, since Spring version 1.0. Gary is also an instructor of courses on enterprise Java, Spring, Hibernate, Web Services, and agile development. He has written a series of Spring and Hibernate tutorials as course materials, parts of which are open to the public, and they’re gaining popularity in the Java community. In his spare time, he enjoys playing tennis and watching tennis competitions

2 comments:

Rockhopper said...

You post huge chunks of copyrighted material. Your own contribution is a few lines stating that you skimmed the book. On what planet would this be acceptable behavior?

Unknown said...

can anyone please help me with "postprocessing beans" topic with example code.