Spring Framework

Omprakash Pandey http://www.synergetics-india.com omprakashpandey@synergetics-india.com


Need for Spring Framework


Application Layering
 A clear separation of application component responsibility.
 Presentation layer
    Concentrates on request/response actions Handles UI rendering from a model. Contains formatting logic and non-business related validation logic. Handles exceptions thrown from other layers

 Persistence layer

 Domain layer
    

 Used to communicate with a persistence store such as a relational database.  Provides a query language  Possible O/R mapping capabilities  JDBC, Hibernate, iBATIS, JDO, Entity Beans, etc. Contains business objects that are used across above layers. Contain complex relationships between other domain objects May be rich in business logic May have ORM mappings Domain objects should only have dependencies on other domain objects


What about a Service Layer? • Where do we position loosely-coupled business logic? • What is service logic? • How should container level services be implemented? • How do we support transactions in a POJO based application? • How do we communicate from our presentation layer to our persistence layer? • How do we get to services that contain business logic? • How should our business objects communicate with our persistence layer? • How do we get objects retrieved from our 4 persistence layer to our UI layer? .

5 . security.Application Layering (cont)  Service layer  Gateway to expose business logic to the outside world  Manages „container level services‟ such as transactions. and manipulates domain objects  Not well defined in many applications today or tightly coupled in an inappropriate layer. data access logic.

Java EE: History 6 .

Java EE Architecture 7 .

Proposed Web App Layering 8 .

Java EE vs Spring Java EE Spring 9 .

What is Spring Framework 10 .

What is Spring?  A Container  Creates objects and makes them available to your application  A Framework  Provides an infrastructure of classes that make it easier to accomplish tasks 11 .

Spring  A lightweight framework that addresses each tier in a Web application.  Reduces code and speeds up development  Current Version is 1.  Business layer – Lightweight IoC container and AOP support (including built in aspects)  Persistence layer – DAO template support for popular ORMs and JDBC  Simplifies persistence frameworks and JDBC  Complimentary: Not a replacement for a persistence framework  Helps organize your middle tier and handle typical J2EE plumbing problems.2 12 .0.  Presentation layer – An MVC framework that is most similar to Struts but is more powerful and easy to use.

What does Spring provide? ◦ Lightweight container and framework ◦ Manages dependencies between your objects ◦ Cleaner separation of responsibilities ◦ Simplifies database integration     Spring JDBC Hibernate iBATIS Java Persistence  Encourages use of interfaces  Lessens “coupling” between objects  Most of your code will be unaware of the Spring framework  Use only the parts you of Spring you want  Put logic that applies to many objects in one single place  Separate the class’s core responsibility from other duties 13 .

Spring Modules – Use What You Want See: http://static.org/spring/docs/2.html#introduction-overview 14 .x/reference/introduction.5.springframework.

15 .Spring Portfolio  Spring Web Flow  Spring Web Services  Spring Security  Spring Batch  Spring IDE  Spring Integration  Spring ..NET (!)  ..

 Removes common code issues like leaking connections and more.  Reduces or alleviates code littering. ad hoc singletons. 16 . service locators and multiple configuration files.  Built in aspects such as transaction management  Most business objects in Spring apps do not depend on the Spring framework.  Promotes decoupling and reusability  POJO Based  Allows developers to focus more on reused business logic and less on plumbing problems.Spring (continued)  Do I have to use all components of Spring?  Spring is a non-invasive and portable framework that allows you to introduce as much or as little as you want to your application. factories.

 Needed a solution to loosely couple business logic in a POJO fashion. business.Why choose Spring?  Introduced to Spring by way of Hibernate  Originally wanted Spring to provide a way to simplify DAO objects and provide declarative transaction support to our non-EJB applications.  Wanted to build portable applications that provided clearer separation of presentation. and persistence logic.  Easily integrated with our existing frameworks  Great documentation and community support 17 .

Simplify your code with Spring  Enables you to stop polluting code  No more custom singleton objects  Beans are defined in a centralized configuration file  No more custom factory object to build and/or locate other objects  DAO simplification  Consistent CRUD  Data access templates  No more copy-paste try/catch/finally blocks  No more passing Connection objects between methods  No more leaked connections  POJO Based  Refactoring experience with Spring  Caution Spring is addictive! 18 .

Spring IoC + AOP  IoC container  Setter based and constructor based dependency injection  Portable across application servers  Promotes good use of OO practices such as programming to interfaces.1  AOP 19 .  Beans managed by an IoC container are reusable and decoupled from business logic  Spring uses Dynamic AOP Proxy objects to provide crosscutting services  Reusable components  Aopalliance support today  Integrates with the IoC container  AspectJ support in Spring 1.

Spring IoC 20 .

Inversion of Control  Dependency injection  Beans define their dependencies through constructor arguments or properties  The container provides the injection at runtime  “Don‟t talk to strangers”  Also known as the Hollywood principle – “don‟t call me I will call you”  Decouples object creators and locators from application logic  Easy to maintain and reuse  Testing is easier 21 .

Non-IoC / Dependency Injection 22 .

Lookup and invoke one of the methods in a // DAO and pass the Session/Connection object. //cleanup. // 4. // throw e }finally{ //Release resources and handle more exceptions } } 23 . rollback transaction. Create a Session/Connection object // 2. Commit transaction }catch(Exception e){ // handle e. Start a transaction // 3.Non-IoC Service Object public class OrderServiceImpl implements IOrderService { public Order saveOrder(Order order) throws OrderException{ try{ // 1.

IoC / Dependency Injection 24 .

orderDAO = orderDAO.saveNewOrder(order). }  Program to interfaces for your bean dependencies! 25 . public Order saveOrder(Order order) throws OrderException{ // perform some business logic… return orderDAO. } public void setOrderDAO(IOrderDAO orderDAO) { this.IoC Service Object public class OrderSpringService implements IOrderService { IOrderDAO orderDAO.

 Bean behaviors include:  Singleton or prototype  Autowiring  Initialization and destruction methods  init-method  destroy-method  Beans can be configured to have property values set.  Can read simple values. etc  Spring config contains implementation classes while your code should program to interfaces. Service objects. DataSource. collections. 26 . Persistence Managers. maps. etc.Spring Bean Definition  The bean class is the actual implementation of the bean being described by the BeanFactory. Transaction Manager.  Bean examples – DAO. references to other beans.

Simple Spring Bean Example  <bean id=“orderBean” class=“example. } public void setOrderDAO(IOrderDAO odao){ this. minimumAmountToProcess = d.orderDAO = odao.OrderBean” init-method=“init”> <property name=“minimumAmountToProcess”>10</property> <property name=“orderDAO”> <ref bean=“orderDAOBean”/> </property> </bean>  public class OrderBean implements IOrderBean{ … public void setMinimumAmountToProcess(double d){ this. } } 27 .

 Knows how to serve and manage a singleton or prototype defined bean  Responsible for lifecycle methods.  Injects dependencies into defined beans when served  Avoids the use of singletons and factories 28 .Spring BeanFactory  BeanFactory is core to the Spring framework  Lightweight container that loads bean definitions and manages your beans. or files.  Configured declaratively using an XML file. that determine how beans can be referenced and wired together.

 Add the ability to load file resources in a generic fashion.  ClassPathXMLApplicationContext – standalone XML application context  FileSystemXmlApplicationContext  Allows you to avoid writing Service Locators 29 .  Several ways to configure a context:  XMLWebApplicationContext – Configuration for a web application.Spring ApplicationContext  A Spring ApplicationContext allows you to get access to the objects that are configured in a BeanFactory in a framework manner.  ApplicationContext extends BeanFactory  Adds services such as international messaging capabilities.

web.ContextLoaderL istener </listener-class> </listener> 30 .context.xml </param-value> </context-param> <listener> <listener-class> org.springframework.Configuring an XMLWebApplicationContext <context-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/applicationContext.

springframework.context.ContextLoaderS ervlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> 31 .xml </param-value> </context-param> <servlet> <servlet-name>context</servlet-name> <servlet-class> org.Configuring an XMLWebApplicationContext <context-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/applicationContext.web.

Locating a Bean with Struts public abstract class BaseAction extends ActionSupport { protected IOrderService getOrderService() { return (IOrderService) getWebApplicationContext() .OrderServiceImpl"> 32 .spring.meagle. } } <bean id=“orderService" class="com.service.getBean("orderService").

Spring AOP 33 .

 Aspects can be used as an alternative to existing technologies such as EJB. Inserts the advice (crosscutting concerns) into the code (core concerns).  Aspects can be added or removed as needed without changing your code. 34 .AOP  Complements OO programming  Core business concerns vs. declarative security. etc. Crosscutting enterprise concerns  Components of AOP      Aspect – unit of modularity for crosscutting concerns Join point – well-defined points in the program flow Pointcut – join point queries where advice executes Advice – the block of code that runs based on the pointcut definition Weaving – can be done at runtime or compile time. profiling. logging. Ex: declarative transaction management.

 Spring aspects can be configured using its own IoC container.  Objects obtained from the IoC container can be transparently advised based on configuration  Spring AOP has built in aspects such as providing transaction management. it does support common aspect uses to solve common problems in enterprise applications 35 .  Aspects are coded with pure Java code.Spring AOP  Framework that builds on the aopalliance interfaces.  However. You do not need to learn pointcut query languages that are available in other AOP implementations. performance monitoring and more for your beans  Spring AOP is not as robust as some other implementations such as AspectJ.

Spring AOP  Supports the following advices:     method before method after returning throws advice around advice (uses AOPAlliance MethodInterceptor directly)  Spring allows you to chain together interceptors and advice with precedence.  Spring AOP also includes advisors that contain advice and pointcut filtering. AspectJ uses compile time weaving.  Aspects are weaved together at runtime.  ProxyFactoryBean – sources AOP proxies from a Spring BeanFactory  IoC + AOP is a great combination that is non-invasive 36 .

AOP Weaving 37 .

Wiring Beans Together with Spring 38 .

HibernateTransactionManager"> <property name=“sessionFactory"> <ref local=“mySessionFactory"/> </property> </bean> 39 .springframework .Wiring your Transaction Management Four transaction managers available     DataSourceTransactionManager HibernateTransactionManager JdoTransactionManager JtaTransactionManager <bean id=“myTransactionManager" class="org .orm .hibernate .

40 .

Spring Database Components 41 .

 Requires a DataSource to be set. providing a JdoTemplate based on it to subclasses. providing a SqlMapTemplate 42 . providing a HibernateTemplate based on it to subclasses.  Requires a SessionFactory to be set.Consistent Abstract Classes for DAO Support  Extend your DAO classes with the proper xxxDAOSupport class that matches your persistence mechanism.  JdbcDaoSupport  Super class for JDBC data access objects.  Requires a PersistenceManagerFactory to be set.  Requires a DataSource to be set.  SqlMapDaoSupport  Supper class for iBATIS SqlMap data access object.  HibernateDaoSupport  Super class for Hibernate data access objects. providing a JdbcTemplate based on it to subclasses.  JdoDaoSupport  Super class for JDO data access objects.

 Code only needs to be implemented in callback methods. etc.  doInXXX(Object)  Optional separate JDBC framework 43 .  Transaction management is handled by a wired bean  You are dropped into the template with the resources you need for data access – Session.  Alleviates opening and closing connections in your DAO code.Spring DAO Templates  Built in code templates that support JDBC. PreparedStatement.  No more ThreadLocal or passing Connection/Session objects. JDO. Hibernate. and iBatis SQL Maps  Simplifies data access coding by reducing redundant code and helps avoid common errors.

and convert to OrderException } catch (SQLException sqle){ // log.close().save(order).beginTransaction(). // needs a try/catch block } return order. Transaction tx = null.. rollback. rollback.Ex: Code without a template public class OrderHibernateDAO implements IOrderDAO { public Order saveOrder(Order order) throws OrderException{ Session s = null. and convert to OrderException } finally { s. } 44 . s. try{ s = .commit(). // get a new Session object tx = s. tx.. } catch (HibernateException he){ // log.

..Ex: Spring DAO Template Example public class OrderHibernateDAO extends HibernateDaoSupport implements IOrderDAO { . SQLException { session. public Order saveOrder(final Order order) { return (Order) getHibernateTemplate()..save(order).execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException. return order. } . } 45 . } })..

.Ex 2: Spring DAO Template Example public class OrderHibernateDAO extends HibernateDaoSupport implements IOrderDAO { . new Integer(orderId)). } 46 .. public List findOrdersByCustomerId(int id) { return getHibernateTemplate() . } . } public Order findOrderById(int orderId ) { return (Order) getHibernateTemplate().load( Order.. new Integer(id)). class..findByNamedQuery(“OrdersByCustomerID”.

 These exceptions are treated as unchecked exceptions that you can handle in your business tier if needed.Consistent Exception Handling  Spring has it‟s own exception handling hierarchy for DAO logic.  No more copy and pasting redundant exception logic!  Exceptions from JDBC.  This allows you to decouple exceptions in your business logic. No need to try/catch in your DAO. and consistent.  Define your own exception translation by subclassing classes such as SQLErrorCodeSQLExceptionTranslator 47 . are wrapped up into an appropriate. DataAccessException and thrown. or a supported ORM.

48 .

Spring Transactions 49 .

Transaction Management With Spring  Choice of two transaction managers  DataSourceTransactionManager for Local Transactions  JtaTransactionManager for using container transactions manager  Choice of two transaction  Declarative (preferred).  Programmatic. Declarations are in Spring context. Custom Spring API 50 . only for scenarios when declarative doesn’t work.

No point in having both 51 . for both declarative and programmatic  Have to be enabled after disabling EJB CMT.Enabling Transactions on Services  Transactions are typically enabled at the business tier level and not in the DAO  Spring transactions are an alternative to EJB transactions.

setHibernateSessionFactory() beanId:hibernateSessionFactory MappingResources HibernateProperties 52 .Dependency Injection beanId:CampaignServiceTxn -TransactionProxyFactoryBean TransactionAttributes beanId:CampaignServiceTarget -CampaignServiceImpl + createCampaign(String): Long + setPromoDAO() beanId:TransactionManager .HibernatePromotionDAO .JTATransactionManager WebsphereTransactionManager beanId:promoDAO .

Spring Web MVC 53 .

About Spring MVC  Comes with the Spring distribution  Well integrated with the rest of Spring  Very extensible 54 .

stuff.platinumSolutions.text.SomeClass"> <property name=“dateFormat” ref=“dateFormat”/> </bean> 55 .SimpleDateFormat"> <constructor-arg value=“dd MMM yyyy”/> </bean> <bean id=“myBean" class=“com.Quick Spring Refresher  Write dependencies as setters  Link up dependencies in XML file  The Spring Framework will instantiate and call setters to hook it all together <bean id=“dateFormat" class=“java.

Controller 56 .web.springframework.xml by default  MVC: instances of the following:  M – Model: a Java Map  V – View: org.View  C – Controller: org.mvc.springframework.servlet.Spring MVC Basics  All calls go through the DispatcherServlet  Config file is *-servlet.web.servlet.

web.servlet.springframework.springframework.servlet.LocaleResolver  org. pages from .springframework.web.servlet.ViewResolver  org.HandlerAdapter  wrapper around the controller (or servlet) 57  what controller to call given a URL  how to determine what view to show  how to determine internationalization  how to handle uploaded files  what to do with an Exception  where to get css.servlet.MultipartResolver  org.servlet.springframework.web. images.HandlerExceptionResolver  org.HandlerMapping  org.servlet.springframework.springframework.springframework.web.ThemeResolver  org.multipart.web.Spring MVC Configuration The configurable pieces of Spring MVC:  org.web.web.

Spring MVC A (simplified) sequence diagram: 58 .

figures out what Controller to use:  SimpleUrlHandlerMapping  define mappings with Map or Properties  BeanNameUrlHandlerMapping  bean names have same names as URL  CommonsPathMapHandlerMapping  use Commons Attributes to determine mapping 59 .Handling the Request with a HandlerMapping  Given a URL.

figures out what View to use:  BeanNameViewResolver  UrlBasedViewResolver  Spring beans happen to have the same name  view name maps to a URL (like a filename)  ResourceBundleViewResolver  XmlViewResolver  look up the View in a resource file  uses XML file to determine mappings  UrlResourceViewResolver preset for FreeMarkerView  FreeMarkerViewResolver  InternalResourceViewResolver  VelocityViewResolver  UrlResourceViewResolver preset for InternalResourceView  UrlResourceViewResolver preset for VelocityView 60 .Selecting a View with ViewResolver  Given a view name.

VelocityToolboxView. VelocityView  FreeMarkerView  Integration with the Velocity templating tool  use the FreeMarker templating tool  JasperReportsView. JasperReportsPdfView. TilesJstlView  VelocityLayoutView.Different Views  Plenty of Views are packaged with Spring MVC:  JstlView  map to a JSP page  Perform an HTTP Redirect  integration with tiles  RedirectView  TilesView. JasperReportsMultiFormatView. JasperReportsXlsView  Support for Jasper Reports 61 . JasperReportsMultiFormatView.

or fixed  AcceptHeaderLocaleResolver .set messages within the object  ResourceMessageBundleMessageSource .properties files  ReloadableResourceMessageBundleMessageSource . but reloads!  (others) 62 .load messages from .use the HTTP accept-header to determine the locale  CookieLocalResolver .store the chosen locale in the session  The spring tag <spring:message> picks the resource  Define the bean messageSource with a MessageSource to set the resources:  StaticMessageSource .always use a fixed locale (set in the config file)  SessionLocaleResolver .same as above.Localization  The locale may be chosen manually.set the chosen locale in a cookie  FixedLocaleResolver . selected by the browser.

knows about caching. hooks for attaching commands.Other Provided Controllers  Spring MVC includes lots of Controllers to extend from:  AbstractController  ParameterizableViewController  basic controller. validator  AbstractWizardFormController  ServletWrappingController 63 . turning on/off get/set/post/head  always go to the same view  UrlFileNameViewController  SimpleFormController  easy wizard controller  delegates to a servlet  parses the URL to return a view (http://blah/foo.html -> foo)  for form handling.

springframework. uses GET/POST to determine whether it needs to load the form or process it 64 .Handling Forms  Set the Command (just a bean)  Set a Validator if needed (extend org.Validator)  Set destination views (form. error)  By default. failure.validation. success.

Wizards      Similar to Forms. but needs to validate along the way One Controller handles multiple pages Process at the end Cancel anywhere along the line Spring Webflow is the now preferred 65 .

adding things to the request/session  Kind of like AOP.Interceptor  Some HandlerMappings allow you to call an interceptor before the controller  Useful for checking for session timeout. but for Controllers 66 .

ExceptionHandler  Spring philosophy says that most Exceptions should not be caught  ExceptionHandler determines what to do if an Exception is thrown through the Controller 67 .

jsp.Themes  Totally change look and feel of your application in one step!  Lets you point to different css. images 68 .

 Spring MVC offers
 Lots of flexibility  Straightforward design  Leverages Spring injection


Spring Web MVC
 Popular web framework  Foundation for all other web modules  Significantly enhanced in Spring 2.5
 Annotated controller model  Convention-over-configuration


Spring Web Controllers
 In an MVC architecture your controllers handle all requests.  Spring uses a ‘DispatcherServlet” defined in the web.xml file to analyze a request URL pattern and then pass control to the correct Controller by using a URL mapping defined in a “ Spring bean” XML file.


web.Controller match. 72 .xml file with a “servlet.xml” file to look-up a URL-to. the Spring “bean” XML file exists in the same directory as your web.xml” appended to it. webapps /tradingapp /WEB-INF/tradingapp-servlet.xml) /classes /lib (all jar files) The dispatcher servlet is mapped to the name “tradingapp” so it knows to look in the “tradingappservlet.xml.Spring Web Container Setup In your Web Container.

Example of web.xml file
<web-app> <servlet> <servlet-name>tradingapp</servlet-name> <servlet-class>DispatcherServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>tradingapp</servlet-name> <url-pattern>*.htm</url-pattern> </servlet-mapping> </web-app> *** Any URL ending with an “.htm” pattern is routed to the DispatcherServlet, the DispatcherServlet loads the tradingappservlet.xml file and routes the user to the correct controller.

Our Demo Logon Form at URL http://localhost/tradingapp/logon.htm


The tradingapp-servlet.xml file a.k.a. Spring beans XML file is where the majority of your configuration is done.
For example: If working with the URL: /logon.htm Because the URL ends with .htm the DispatcherServlet loads the tradingapp-servlet.xml file to determine which controller to use. The tradingapp-servlet.xml file uses Springs SimpleUrlHandlerMapping class to map the URL to a controller, in this case the LogonFormController Next…what the tradingapp-servlet.xml looks like.

tradingapp.tradingapp-servlet.htm</value></property> </bean> 76 If it passes “validator” then successView.htm page . passes to portfolio.SimpleUrlHandlerMapping"> <property name="urlMap"> <map> <entry key="/logon.springframework.tradingapp.Credentials</value> </property> <property name="validator"><ref bean="logonValidator"/></property> <property name="formView"><value>logon</value></property> <property name="successView"><value>portfolio.LogonFormController"> <property name="sessionForm"><value>true</value></property> <property name="commandName"><value>credentials</value></property <property name="commandClass"> <value>com.htm"> <ref bean="logonForm"/> </entry> </map> </property> This class extends Springs SimpleFormController </bean> Which defines a setSuccessView() method <bean id="logonForm" class="com.xml <bean id="urlMapping" class="org.

validation.g. e.htm  Since the URL ends with “.xml file is loaded to determine what controller to use. 77 . the tradingappservlet.  The <bean name urlMapping …/> says to refer to the <bean id="logonForm" class="com.htm”.LogonFormController">  Since the LogonFormController extends SimpleFormController we can use the methods defined in the SimpleFormController class to do all kinds of form checking.tradingapp.Review of the process so far  User goes to this URL: http://tradingapp/logon.

xml file? <bean id="logonForm" class="com. } } Remember our tradingapp-servler.LogonFormController"> <property name="sessionForm"><value>true</value></property> <property name="commandName"><value>credentials</value></property <property name="commandClass"> <value>com.Credentials</value> </property> <property name="validator"><ref bean="logonValidator"/></property> <property name="formView"><value>logon</value></property> <property name="successView"><value>portfolio.htm</value></property> </bean> If no validation errors.tradingapp.tradingapp. public class LogonFormController extends SimpleFormController { public ModelAndView onSubmit(Object command) throws ServletException { return new ModelAndView(new RedirectView(getSuccessView())). go here 78 .What our LogonFormController Looks Like.

successView /portfolio.htm 79 .

tradingapp. 80 On error go back to formView.xml <bean id="logonForm" class="com.Where do I go if there is a validation error in my logon page? tradingapp-servler.devx.LogonValidator"/> *** Your LogonFormController will check the validation “first” without writing any additional code because your LogonFormController extends Springs SimpleFormController.htm</value></property> </bean> <bean id="logonValidator" class="com. . that is where you started.tradingapp.web. Next: The LogonValidator implements Springs Validator interface.Credentials</value> </property> <property name="validator"><ref bean="logonValidator"/></property> <property name="formView"><value>logon</value></property> <property name="successView"><value>portfolio.tradingapp.LogonFormController"> <property name="sessionForm"><value>true</value></property> <property name="commandName"><value>credentials</value></property <property name="commandClass"> <value>com.

Logon page with error message Next: code for LogonValidator implements Springs Validator 81 .

invalid-pass". Command / form backing bean if (credentials.LogonFormController"> <property name="commandName"><value>credentials</value></property <property name="commandClass"> <value>com.tradingapp.tradingapp.equals("guest") == false) { errors. } } 82 Next: Command/Form Backing Bean .htm</value></property> </bean> <bean id="logonValidator" class="com.").devx. Errors errors) { Credentials credentials = (Credentials) obj.LogonValidator"/> public class LogonValidator implements Validator { public void validate(Object obj.getPassword().tradingapp. null. "error.Credentials</value> </property> <property name="validator"><ref bean="logonValidator"/></property> <property name="formView"><value>logon</value></property> <property name="successView"><value>portfolio.xml <bean id="logonForm" class="com.web.rejectValue("password".Example code of validator tradingapp-servler. "Incorrect Password.login.

public String getPassword() { return password. } public void setUsername(String username) { this.username = username. private String password. } Next: Why its called a “command” or “form backing bean” } 83 .Command/Form Backing Bean is a POJO public class Credentials { private String username.password = password. } public void setPassword(String password) { this. } public String getUsername() { return username.

} Password: The logon form is “backed” by the Credentials bean and given a commandName of “credentials” defined in out springapp-servlet. private String password. public String getPassword() { return password.Command/Form Backing Bean is a POJO logon.xml file } 84 public void setPassword(String password) { this. } public void setUsername(String username) { this. } public String getUsername() { return username.htm form Username: public class Credentials { private String username.username = username.xml file.password = password. } . Next: another look at springappservlet. “credentials” will be our “command object” we will use to bind the form to the bean.

Credentials</value> </property> <property name="validator"><ref bean="logonValidator"/></property> <property name="formView"><value>logon</value></property> <property name="successView"><value>portfolio.springapp-servlet.LogonFormController"> <property name="commandName"><value>credentials</value></property <property name="commandClass"> <value>com.tradingapp.tradingapp.xml file <bean id="logonForm" class="com.htm</value></property> </bean> We use the commandName “credentials” with Spring’s tag library. 85 Next: Code that shows logon form binding to commandName . to bind the Credentials bean to the logon form.

username"> <input type="text" name="username" <spring:bind path="credentials.logon form binding to commandName using Springs Tag Library <%@ taglib prefix="spring" uri="/spring" %> <html> <head><title>DevX.password"> <input type="password" name="password" /> </body> </html> Spring’s taglib has bound the bean to the form 86 .com Stock-Trading System Logon</title></head> <body> <spring:bind path="credentials.

Annotated Controller Model  Annotate a plain Java™ class as a Controller  Map HTTP requests to methods  Bind request parameters to method arguments  Populate Model to export data to the view  Return a String to select a view 87 .

Example  @Controller to manage hotels  GET /hotels/list  List hotels available for booking 88 .

hotelService. method=GET) public String list(Model model) { model.findAll()).Example @Controller @Controller public class HotelsController { @RequestMapping(“/hotels/list”. return “/hotels/list”. } } 89 .add(“hotels”.

jsp 90 .list(Model) /hotels/list render Model {hotels} /hotels/list.Example Request Lifecycle invoke /hotels/list Dispatcher Servlet HotelsController .

mv.Before Spring Web MVC 2.add(“hotels”. } } + External XML URL Mapping Configuration 91 .5 public class HotelsController extends MultiActionController { public ModelAndView list( HttpServletRequest request. mv. hotelService.setViewName(“/hotels/list”). return mv.findAll()). HttpServletResponse response) { ModelAndView mv = new ModelAndView().

get consistency  Conventions available for  Request mapping  View name selection  Model population  Can always override when needed 92 .Convention over configuration  Write less code.

With Conventions GET /hotels/list @Controller public class HotelsController { View @RequestMapping selected public void list(Model model) { from model. request path } Model entry name generated from object type Mapping to class + method name } 93 .findAll()).add(hotelService.

findAll(). for you } } 94 .Simplest Signature Possible @Controller public class HotelsController { @RequestMapping public List<Hotel> list() { Added to the Model return hotelService.

Multi-Action Convention Example @Controller public class HotelsController { /hotels/index @RequestMapping public void index(…) {…} /hotels/show @RequestMapping public void show(…) {…} /hotels/update @RequestMapping public void update(…) {…} } 95 .

add(hotelService. Model m) { model. } } 96 .Data Binding @Controller public class HotelsController { /hotels/list?searchString=Westin&pageSize=5 @RequestMapping public void list(Criteria c.find(c)).add(hotelService. Model m) { model. } /hotels/show?id=1 @RequestMapping public void show(@RequestParam Long id.get(id)).

Scan for components to deploy as beans --> <context:component-scan base-package=”example.hotels”/> 97 .@Controller Deployment  Found in classpath  Auto-wired as Spring beans <!-.

Autowiring Hints @Controller public class HotelsController { @Autowired @Service public class HibernateHotelService public HotelsController(HotelService service) { implements HotelService { } } @Autowired public HibernateHotelService(DataSource ds) { } @Transactional public List<Hotels> find(Criteria c) {} } 98 .

Mixing Annotations and XML Configure your application beans <beans> <context:component-scan Link with environment-specific infrastructure base-package=”example.hotels”/> <jee:jndi-lookup id=”dataSource” jndi-name=”eis/jdbc/travelDataSource”/> </beans> 99 .

Demo Essential Spring MVC Features 100 .

g.Web MVC Summary  Favor @Controller model over old styles  Favor convention-over-configuration  Favor strongly typed handler methods  Consider grouping control logic by Resource  e. “HotelsController” for acting on Hotel resources 101 .

Jboss SEAM 102 .

What is JBoss SEAM? JBoss Seam is web application framework that acts as the glue between existing (presumably JavaEE) components. If JavaEE standards are seen as a set of cloth patches. 103 . then SEAM is what brings them together to form a quilt.

What is JBoss SEAM? SEAM provides the plumbing between the various components of the web development stack by providing Context Management to all of them. 104 .

Sign up to vote on this title
UsefulNot useful