Web Application Development with the Spring Framework - PowerPoint PPT Presentation

1 / 22
About This Presentation
Title:

Web Application Development with the Spring Framework

Description:

Interceptor chaining. Aspect Oriented Programming (AOP) examples. Spring and Hibernate ... with Spring, including method interceptors/AOP and a persistence layer ... – PowerPoint PPT presentation

Number of Views:396
Avg rating:3.0/5.0
Slides: 23
Provided by: ander47
Category:

less

Transcript and Presenter's Notes

Title: Web Application Development with the Spring Framework


1
Web Application Development with the Spring
Framework
2
whoami
  • Kristoffer Moum
  • Systems Developer and consultant at Objectware
  • Five years of experience with Java/J2EE

3
Agenda
  • Presentation goals
  • Development environment setup
  • Configuration
  • Spring and MVC
  • Basics of testing
  • Interceptor chaining
  • Aspect Oriented Programming (AOP) examples
  • Spring and Hibernate
  • Spring and JDBC
  • Summary

4
Presentation goals
  • A better understanding of the Spring framework
    targetted on web applications
  • Knowledge to setup a development environment with
    Spring, including method interceptors/AOP and a
    persistence layer

5
Development environment setup
  • Required components
  • JDK 1.5
  • A Servlet / JSP container, i.e. Tomcat
  • Exploded war-file for fast test and deploy cycles
  • All tiers cannot be tested automatically in a
    sensible way

6
Web application configuration
  • Web application configuration
  • web.xml
  • Spring container configuration
  • Various xml configuration files

7
Example web.xml
ltweb-appgt ltdisplay-namegtspringwebexamplelt/disp
lay-namegt ltcontext-paramgt
ltparam-namegtcontextConfigLocationlt/param-namegt
ltparam-valuegt/WEB-INF/classes/spring.xmllt/par
am-valuegt lt/context-paramgt ltfiltergt
ltfilter-namegtOpenSessionInViewFilterlt/filter-nam
egt ltfilter-classgtorg.springframework.orm.h
ibernate.support.OpenSessionInViewFilterlt/filter-c
lassgt lt/filtergt ltfilter-mappinggt
ltfilter-namegtOpenSessionInViewFilterlt/filter-namegt
lturl-patterngt/lt/url-patterngt
lt/filter-mappinggt ltlistenergt
ltlistener-classgtorg.springframework.web.context.Co
ntextLoaderListenerlt/listener-classgt
lt/listenergt ltservletgt
ltservlet-namegtspringapplt/servlet-namegt
ltservlet-classgtorg.springframework.web.servlet.Dis
patcherServletlt/servlet-classgt
ltload-on-startupgt1lt/load-on-startupgt
lt/servletgt ltservlet-mappinggt
ltservlet-namegtspringapplt/servlet-namegt
lturl-patterngt.htmllt/url-patterngt
lt/servlet-mappinggt lt/web-appgt
8
Example spring.xml
ltbean id"customerDao" class"no.objectware.jz2005
.springwebapp.dao.impl.HibernateCustomerDao"gt
ltproperty name"sessionFactory"gtltref
local"sessionFactory" /gtlt/propertygt lt/beangt ltbean
id"customerTarget" class"no.objectware.jz2005.s
pringwebapp.service.impl.DefaultCustomerService"gt
ltproperty name"customerDao"gtltref
bean"customerDao" /gtlt/propertygt lt/beangt ltbean
id"timingInterceptor" class"no.objectware.jz2005
.springwebapp.aop.TimingInterceptor"/gt ltbean
id"timeoutInterceptor" class"no.objectware.jz200
5.springwebapp.aop.TimeoutInterceptor"/gt ltbean
id"transactionManager" class"org.springframework
.orm.hibernate.HibernateTransactionManager"gt
ltproperty name"sessionFactory"gtltref
local"sessionFactory" /gtlt/propertygt lt/beangt ltbean
id"transactionInterceptor" class"org.springfram
ework.transaction.interceptor.TransactionIntercept
or"gt ltproperty name"transactionManager"gt
ltref bean"transactionManager" /gt
lt/propertygt ltproperty name"transactionAttribu
teSource"gt ltvaluegtno.objectware.jz2005.spr
ingwebapp.service.CustomerService.savePROPAGATIO
N_REQUIRED,-Exceptionlt/valuegt
lt/propertygt lt/beangt ltbean id"customerService"
class"org.springframework.aop.framework.ProxyFact
oryBean"gt ltproperty name"proxyInterfaces"gt
ltvaluegtno.objectware.jz2005.springwebapp.ser
vice.CustomerServicelt/valuegt lt/propertygt
ltproperty name"interceptorNames"gt
ltlistgt ltvaluegttimingInterceptorlt/value
gt ltvaluegttimeoutInterceptorlt/valuegt
ltvaluegttransactionInterceptorlt/valuegt
ltvaluegtcustomerTargetlt/valuegt
lt/listgt lt/propertygt lt/beangt
9
Spring and MVC example Controller
public class ProductsController extends
SimpleFormController private
ProductService productService public
void setProductService(ProductService
productService) this.productService
productService public
ProductsController() protected
ModelAndView onSubmit(Object command,
BindException errors) throws Exception
ListltProductgt products productService.findAllPro
ducts() return new ModelAndView(getSucces
sView(),"products", products)
10
Spring and MVC example configuration
ltbean id"productsForm" class"no.objectware.jz200
5.springwebapp.web.controller.ProductsController"gt
ltproperty name"productService"gt
ltref bean"productService"/gt lt/propertygt
ltproperty name"formView"gt
ltvaluegtdisplayProductslt/valuegt lt/propertygt
ltproperty name"successView"gt
ltvaluegtdisplayProductDetailslt/valuegt
lt/propertygt ltproperty name"validator"gt
ltbean class"no.objectware.jz2005.springwebapp.w
eb.validator.ProductValidator"/gt
lt/propertygt lt/beangt ltbean id"urlMapping"
class"org.springframework.web.servlet.handler.Sim
pleUrlHandlerMapping"gt ltproperty
name"mappings"gt ltpropsgt
ltprop key"/products.html"gtproductsFormlt/propgt
lt/propsgt lt/propertygt lt/beangt ltbean
id"viewResolver" class"org.springframework.web.s
ervlet.view.InternalResourceViewResolver"gt
ltproperty name"prefix"gt
ltvaluegt/WEB-INF/jsp/lt/valuegt lt/propertygt
ltproperty name"suffix"gt
ltvaluegt.jsplt/valuegt lt/propertygt lt/beangt
11
Spring and MVC
  • Several abstract Controller implementations
  • Validation through Validator interface
  • Binding to form fields through ltspringbindgt

12
Basics of testing
  • Unit testing
  • Integration testing
  • Rolling back transactions
  • AbstractDependencyInjectionSpringContextTests
  • Hibernate laziness
  • Mock classes within the framework

13
Interceptor chaining and AOP
  • Interceptor chaining by declarative configuration
  • How to make it useful
  • The good old invocation timing example
  • Implement time-out handling
  • Where to apply it
  • Write Once Read Many
  • Infrastructure

14
AOP examples
  • Caching time-consuming look-ups
  • Caching by declarative configuration
  • Business interface remains unchanged
  • Application security
  • Declarative security handling
  • The Acegi framework
  • Method invocation time-out handling

15
Business method invocation timeout
public final class ReadOnlyTimeoutInterceptor
implements MethodInterceptor private
static ExecutorService runner
Executors.newCachedThreadPool() private
MapltString,Stringgt timeouts new
HashMapltString,Stringgt() public void
setTimeouts(MapltString, Stringgt timeouts)
this.timeouts timeouts public
Object invoke(MethodInvocation invocation) throws
Throwable String serviceMethod
invocation.getMethod().getDeclaringClass().getName
() "." invocation.getMethod().getName()
String maxInvocation timeouts.get(serviceMeth
od) if(maxInvocation null)
maxInvocation timeouts.get("default")
Future asyncCaller
runner.submit(new CallableHandler(invocation,
serviceMethod)) try return
asyncCaller.get(Long.parseLong(maxInvocation),
TimeUnit.MILLISECONDS) catch
(InterruptedException e) throw new
RuntimeException(e) catch
(ExecutionException e) throw
e.getCause() catch (TimeoutException
e) throw new RuntimeException("Servi
ce " serviceMethod " timed out after
approximately " maxInvocation " ms")
(..)
16
Business method invocation timeout (cont.)
public class CallableHandler implements Callable
private MethodInvocation invocation
private String service public
QualityOfServiceHandler(MethodInvocation
invocation, String service)
this.invocation invocation
this.service service public
Object call() throws Exception try
return invocation.proceed()
catch (Throwable throwable)
throw new RuntimeException("Exception when
invoking service " service "")

17
Spring and Hibernate
  • Small amount of code
  • Extend HibernateDaoSupport
  • No handling of checked exceptions
  • Avoiding the dreaded LazyInitializationException

18
Spring and Hibernate by example
public interface CustomerService void
save(Customer customer) public final class
DefaultCustomerService implements CustomerService
private CustomerDao customerDao public
void setCustomerDao(CustomerDao customerDao)
this.customerDao customerDao
public void save(Customer customer)
customerDao.save(customer) public
interface CustomerDao void save(Customer
customer) public final class
HibernateCustomerDao extends HibernateDaoSupport
implements CustomerDao public void
save(Customer customer)
getHibernateTemplate().save(customer)
19
Spring and Jdbc
  • Still a small amount of code
  • Extend JdbcDaoSupport
  • When to apply this wrapper
  • Joining many tables with lazy collections isnt
    exactly fast
  • Databases could be out of our control, i.e.
    Legacy and may have lots of constraints

20
Spring and Jdbc by example
public final class JdbcProductCategoryDao extends
JdbcDaoSupport implements ProductCategoryDao
private static final String findAllProductCatego
ries "select from product_category"
public ListltProductCategorygt findAll()
return getJdbcTemplate().query(findAllProductCateg
ories, new ProductCategoryRowMapper())
public static class ProductCategoryRowMapper
implements RowMapper public Object
mapRow(ResultSet rs, int i) throws SQLException
long categoryId
rs.getLong("product_category_id")
String description rs.getString("product_categor
y_desc") return new
ProductCategory(categoryId, description)

21
Summary
  • Development environment setup
  • Configuration
  • Spring and MVC
  • Basics of testing
  • Interceptor chaining
  • Aspect Oriented Programming (AOP) examples
  • Spring and Hibernate
  • Spring and JDBC

22
Further reading
  • Introduction to Dependency Injection
  • http//www.martinfowler.com/articles/injection.htm
    l
  • Introduction to Spring
  • http//www.theserverside.com/articles/article.tss?
    lSpringFramework
  • Spring Forum
  • http//forum.springframework.org
  • Blog on Hibernate and laziness in different
    application tiers
  • http//jroller.com/comments/kbaum/Weblog/orm_lazy_
    initialization_with_dao
  • The Serverside discussion thread on testing
  • http//theserverside.com/news/thread.tss?thread_id
    33215
  • Matt Raibles appfuse project
Write a Comment
User Comments (0)
About PowerShow.com