Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Spring MVC Training

16,019 views

Published on

http://www.intertech.com/Courses/CourseCategory.aspx?CategoryID=62

This is a slide deck from an Intertech Oxygen Blast technical presentation on Spring MVC.

Published in: Technology, Education

Spring MVC Training

  1. 1. Intertech Oxygen Blast 2008 CJWD Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 1
  2. 2. Intertech Oxygen Blast 2008 • Introduce Spring, Spring modules and the Spring philosophy • Understand of Inversion of Control/dependency injection • Explore the Spring MVC Module • Learn about Spring MVC Components (Dispatcher, Handler Mapping, Controller, View Resolver, View) • Examine how Spring MVC compares to other MVC frameworks (Struts, JSF, Tapestry) • Explore Spring MVC’s alternate types of views(PDF, Excel, Portlets, etc.) and integration to other MVC frameworks. • Provide additional resources for additional information. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 2
  3. 3. Intertech Oxygen Blast 2008 • Jim White – jwhite@intertech.com • Author J2ME, Java in Small Things – 2002, Manning • International Speaker • Including JavaOne • Contributor to many journals including: • JDJ • DevX.com • JavaPro • Consultant, engineer and architect with several companies • Most recently - Senior Technical Architect at Target Corp. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 3
  4. 4. Intertech Oxygen Blast 2008 Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 4
  5. 5. Intertech Oxygen Blast 2008 • Spring is an open source framework. • It was created by Rod Johnson; first described in his 2002 book: Expert One- on-One J2EE Design and Development (Wrox). • Spring 1.0 was released in 2004. • The latest edition of Spring is version 2.5 (November 2007). Spring 2.0 (the last major release) was released in October 2006. • Therefore, Spring, in its current form, is a relative newcomer to the framework landscape. • Spring is available from www.springframework.org. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 5
  6. 6. Intertech Oxygen Blast 2008 • Spring was created to reduce the complexity observed in Java enterprise application development – most notably in EJB development. • It was meant to be a lightweight framework that could also be used in non- enterprise Java applications. • In general, Spring leverages plain-vanilla Java objects (POJOs) or more precisely JavaBeans to achieve enterprise tasks. • While based on simple JavaBean technology, today Spring is a large and all encompassing framework. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 6
  7. 7. Intertech Oxygen Blast 2008 • Spring is based on several core development philosophies. • Java Enterprise applications should be easy to create. • The framework should be lightweight. Allowing it to be distributed in a single JAR file. • The framework should be non-intrusive. “Lock-in” to Spring should be minimized. • For example, the application code should not be required to extend a lot of classes or implement a lot of interfaces. • The framework should facilitate good object-oriented design – the application is more important than the enterprise technology. • Application and application components should be easy to test. Allowing the use of unit testing frameworks (JUnit) even with enterprise components. • All too often, testing enterprise components requires the enterprise server environment be available to test even the smallest pieces of the application. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 7
  8. 8. Intertech Oxygen Blast 2008 • Coding by interfaces is better. Interfaces allow for loose coupling/pluggability. • Spring should not compete with good existing solutions. • Requiring applications to check for exceptions serves no purpose unless some recovery can occur from the exception detected. • In essence, Spring provides a framework that many say promotes applications, specifically enterprise applications, that are: • Easier and less complex to develop. • Easier to test. • More flexible. • Easier to maintain. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 8
  9. 9. Intertech Oxygen Blast 2008 • How are the Spring philosophies carried out in the framework? • Applications are composed of simple Java objects. • The objects are configured via XML and the framework provides much of the infrastructure functionality: lifecycle management, transactions, etc. • Spring is a container in that it contains and manages the lifecycle and configuration of application objects. • This makes Spring a container running within a container like an application or Web container. • Loose coupling is promoted through dependency injection and aspect oriented programming (AOP). Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 9
  10. 10. Intertech Oxygen Blast 2008 • Dependency injection is a technique demonstrated in a bit. • AOP is a framework within the framework that allows developers to put cross cutting system services (logging, auditing, security, etc.) in separate code. • These services are then declaratively linked in and applied to the rest of the application. Security Transactions Logging Order Entry Service Process Order Service Billing Service Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 10
  11. 11. Intertech Oxygen Blast 2008 • Spring is organized into many modules that offer various types of assistance to the developer in a host of application areas. • This include persistence, monitoring and configuration, remoting, messaging and of course Web application development. • And every day, Spring is getting bigger and richer – while still maintaining its JavaBean simplicity and “lightweight” foundations. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 11
  12. 12. Intertech Oxygen Blast 2008 • Some of the major modules are pictured in the diagram and listed below. • Core is the most fundamental part and base of the Spring framework, providing Dependency Injection and the container. • The Context module builds on the Core. It provides a way to access objects/services in a registry style (not unlike a JNDI lookup). • Context also adds support for internationalization, resource-loading, etc. • The DAO module provides a JDBC abstraction layer. On top of that, the ORM module provides integration for popular object-relational mapping APIs (Hibernate, Java Persistent API, etc.). • The Inc. 2007 • www.Intertech.com 800-866-9884 • Slide 12 Copyright © Intertech, AOP module provides•the aspect-oriented programming implementation.
  13. 13. Intertech Oxygen Blast 2008 • Spring's Web module provides web-oriented support to Web developers and the MVC module. • The Web module also provides integration support to Struts and JSF frameworks. • The MVC module provides a Model-View-Controller (MVC) implementation for Web applications. • This talk is an introduction to the Spring MVC module. • Again, this is not a complete list of the Spring functionality or modules. Spring, in all of its capabilities, is quite large today. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 13
  14. 14. Intertech Oxygen Blast 2008 • Model View Controller or MVC is an architectural pattern used in the development of applications. • It is not a new pattern. • It is also not a pattern specific to Java or Web development. • In fact, the pattern was first described in 1979. • It was a concept that originated at Xerox Palo Alto Research Center. • PARC also served as the incubator for • the mouse • laser printer • OO programming (to include Smalltalk) • GUI • and many more modern computing technologies. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 14
  15. 15. Intertech Oxygen Blast 2008 • Most software engineers soon learn that it is important to divide an application into separate layers. • Specifically, most significant applications are divided into presentation (or user interface), business or domain logic and data access layers. • When implemented correctly, applications divided in this manner allow each layer to be significantly modified or even replaced without affecting the others. • For example, the data access layer can be changed to get data from a different source without causing the domain logic or UI to change. • Loose coupling between the layers provides for flexibility and ease of maintenance. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 15
  16. 16. Intertech Oxygen Blast 2008 • In MVC applications, this pattern is carried further. • In MVC applications, the presentation layer is further divided into view and controller layers. • In an MVC application, the business or domain logic and data access layers are seen collectively as the model. • The model encapsulates the raw data and business logic that operate on that data. The model should also notify observes when it has changed. • The controller responds to events, typically user actions, and instructs the model and the view to perform actions based on the events. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 16
  17. 17. Intertech Oxygen Blast 2008 • The controller may invoke changes on the model. • The view renders information supplied by the model in a form suitable for user interaction. Multiple views may exist for different displays of the same model. • The view may also serve to capture events to send to the controller. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 17
  18. 18. Intertech Oxygen Blast 2008 • In the Java EE, Web application world, MVC is also known as Model 2 architecture. • Servlets are often used in the role of controller. • JSPs and tags are used to generate the user interface that presents the view. • JavaBeans and/or Enterprise JavaBeans are used to provide the Model layer. • JavaBeans are also used to carry information between the various layers. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 18
  19. 19. Intertech Oxygen Blast 2008 • The Spring framework can be downloaded in a single, all inclusive zip file from www.springframework.org. • The important JAR file in this download is the spring.jar file. This contains all the necessary code to run Spring. • It weighs in at more than 2.5 MB. • Considering the capabilities available in Spring, this is not too terribly bad and is very convenient. • This JAR file was used for demonstrations used throughout this talk. • For those that are concerned about the size, smaller JAR files for each of the Spring modules are available from the open source project. • As with many open source projects, Spring relies on other open source projects for many ancillary needs and integration. • Therefore the distribution zip (that includes spring.jar) file comes with a number of additional JAR files. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 19
  20. 20. Intertech Oxygen Blast 2008 • As of Spring 2.5, Spring MVC is no longer part of the 'spring.jar' file. • Spring MVC can be found in 'spring-webmvc.jar„ • Spring 2.5 was just released in November of 2007 so it is still very young. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 20
  21. 21. Intertech Oxygen Blast 2008 • Inversion of Control is a design pattern that is at the heart of Spring. • In order to understand Spring MVC, or any part of Spring, one must have a good grasp on IoC. • More precisely, Spring uses Dependency Injection (DI). • DI is a type of IoC. • For more information on the exact differences between DI and IoC and the different types of DI, see Martin Fowlers article (listed in resources). • Using Dependency Injection, objects are given their dependencies instead of creating them or looking them up for themselves. • “Dependencies” include collaborating objects, property data, configuration information, etc. • Who “injects” or provides the objects/data to the objects? In Spring, it is the container. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 21
  22. 22. Intertech Oxygen Blast 2008 • Perhaps one of the easiest ways to understand DI/IoC is via example. • If you where to create some business service (say one to process accounts), it might look generically like the code below. public class AccountServiceImpl implements AccountService { AccountDao dao; private Account[] getAccounts(String[] names) { dao = new AccountDaoImpl( /*config params go here*/ ); return dao.getAccounts(names); } public void processAccounts() { ... Account[] accts = getAccounts(nm[]); ... } } Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 22
  23. 23. Intertech Oxygen Blast 2008 • Using DI, the same service would look like the following implementation. public class AccountServiceImpl implements AccountService { AccountDao dao; public void processAccounts() { ... Account[] accts = dao.getAccounts(nm[]); ... } } • The DAO represents the Dependency Injection here. • The DAO is “injected” into the Account Service object. • Who does the injecting? In the Spring world, the Spring container does with some help of configuration that you provide. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 23
  24. 24. Intertech Oxygen Blast 2008 • Why is this important? • What if you change the implementation of the AccountDao? If you do, you must also change the AccountServiceImpl. The two are tightly coupled. • How do you test the AccountServiceImpl class in the first example without testing the AccountDao? Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 24
  25. 25. Intertech Oxygen Blast 2008 • Now, with an understanding of DI, how does Spring implement DI? • Again, an example serves to demonstrate the core of the Spring framework, container and DI. • To allow the Spring container to own and create the dependency between, in the example, the AccountDao and AccountService, it must be configured. <beans> <bean id=“accountDao” class=“AccountDaoImpl” /> <bean id=“accountService” class=“AccountServiceImpl”> <property name=“dao”> <ref bean=“accountDao” /> </property> </bean> </beans> • This task of creating associations between beans is called wiring in Spring. • Wiring can be accomplished by database, properties files, etc. but is most commonly accomplished by XML configuration file as shown above. • This file is often referred to as the Spring configuration metadata or sometimes “bean” configuration file. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 25
  26. 26. Intertech Oxygen Blast 2008 • To use Spring and the Account Service (with its injected DAO), call on a Spring Container. public static void main(String[] args) throws Exception { BeanFactory factory=new XmlBeanFactory(new FileInputStream(“spring-beans.xml”)); AccountService service =(AccountService)factory.getBean(“accountService”); service.processAccounts(); } • In this example, the XmlBeanFactory is the Spring Container. • As its name suggests, it is an implementation of the Factory design pattern. • Using the XML configuration, the container creates the AccountService and AccountDAO beans, associates them and manages their lifecycle. Live Spring IoC Demo Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 26
  27. 27. Intertech Oxygen Blast 2008 • The Spring MVC module provides an MVC Web application framework • Like other Java MVC frameworks, it provides state management, workflow, validation, etc. • And like other frameworks, it is also based primarily on existing servlet/JSP technology. • Unlike other frameworks, Spring uses JavaBeans and DI to create and assemble the MVC environment. • The Spring MVC framework is modular, so various components within the framework can be easily replaced. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 27
  28. 28. Intertech Oxygen Blast 2008 • The diagram below depicts the Spring MVC architecture at a high level. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 28
  29. 29. Intertech Oxygen Blast 2008 • As is the case in most Java based MVC frameworks, a servlet acts in the role of controller in the Spring MVC environment. • In Spring, the controller is the DispatcherServlet. All requests must be directed to this servlet. • After receiving a request, the DispatcherServlet consults a handler mapping object to figure out which controller should receive the request. • Once determined, the DispatcherServlet calls on the controller and waits for its reply. • The controller object in Spring MVC acts as the conduit to the model, calling on various business logic code/components. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 29
  30. 30. Intertech Oxygen Blast 2008 • On finishing the model business, the controller packages up model data needed for the display and the logical name of the next view in a ModelAndView object. • The ModelAndView object is a special Spring MVC framework object (org.springframework.web.servlet.ModelAndView). • The DispatcherServlet receives the ModelAndView from the controller and calls on a view resolver to help determine the next actual display view. • The ModelAndView contains the logical name in order not to tightly couple the model to the view. • The view resolver maps the logical name to some view. • Typically the view is a JSP or HML page. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 30
  31. 31. Intertech Oxygen Blast 2008 Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 31
  32. 32. Intertech Oxygen Blast 2008 Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 32
  33. 33. Intertech Oxygen Blast 2008 Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 33
  34. 34. Intertech Oxygen Blast 2008 • What makes Spring MVC so powerful? • The Spring MVC Architecture is straightforward at first glance. • Spring MVC does have more components than most MVC frameworks. • Each component serves a specific purpose. • And there are many choices for many of the components. • For example, there are over a dozen choices for the controller component!!! • Spring provides many implementation options for each component, and custom components can also be developed. • Spring MVC provides simple components for simple applications and more complex components for complex application needs. • In fact, the task for most developers is in picking and configuring the right components with the desired features versus coding the component. • Some would say the “tough” task. • In the end, however, Spring MVC relies on the fact that the components, while Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide simple to understand. many, are still just POJOs/JavaBeans and 34
  35. 35. Intertech Oxygen Blast 2008 • Because of its numerous and interchangeable parts, perhaps the best way to learn Spring MVC is through a simple application. • The example used throughout most of this talk is a take-off from the ubiquitous Hello World application. • In the example application, the user is allowed to specify the origin of their greeting. The origin selection page is a simple JSP containing an HTML form. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 35
  36. 36. Intertech Oxygen Blast 2008 <html> <head> <title>Main Page - Multi State Hello World</title> </head> <body> <b>Specify your greeting</b> <form action=quot;greeting.requestquot; method=quot;POSTquot;> <input type=quot;radioquot; name=quot;statequot; value=quot;Minnesotanquot; checked>Minnesotan<br> <input type=quot;radioquot; name=quot;statequot; value=quot;Texanquot;>Texan<br> <input type=quot;radioquot; name=quot;statequot; value=quot;Canadianquot;>Canadian<br> <input type=quot;radioquot; name=quot;statequot; value=quot;Philadephianquot;>Philadephian<br> <input type=quot;radioquot; name=quot;statequot; value=quot;Italianquot;> Italian<br> <input type=quot;submitquot; value=quot;OKquot;> </form> </body> </html> Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 36
  37. 37. Intertech Oxygen Blast 2008 • After specifying their greeting and pressing the OK button, “Hello World” in the appropriate vernacular is shown to the user via another JSP page. • The personalization (in this case “Jim”) will come from Spring configuration. Live Spring MVC Demo Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 37
  38. 38. Intertech Oxygen Blast 2008 • The DispatcherServlet is provided with the Spring MVC framework. So you do not have to provide this portion of the controller. • However, you must configure the Web application to direct all requests into this servlet. • As is the typical case in Java Web development, this is accomplished via the servlet/servlet mapping elements in the standard web.xml file. <servlet> <servlet-name>dispatcher</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>*.request</url-pattern> </servlet-mapping> Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 38
  39. 39. Intertech Oxygen Blast 2008 • In this example, all requests that end in “.request” are mapped to the Spring DispatcherServlet. Note the Greeting form‟s action attribute. <form action=quot;greeting.requestquot; method=quot;POSTquot;> • Aside note: it is not uncommon to see the url-pattern of *.htm to be used. This can help obfuscate the technology used in the Web application. • Making it look like a web site of simple HTML. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 39
  40. 40. Intertech Oxygen Blast 2008 • As the DispatcherServlet is loaded, a Spring container is also constructed. • The name given the DispatcherServlet in the web.xml file (dispatcher in this case) is important. • By default, the Spring container looks for and uses a Spring bean configuration file called dispatcher-servlet.xml in this example. • All bean definitions (DAO, services, etc.) could be defined in this file and automatically loaded/injected via this configuration file. • This is considered messy as all the layers of the application would then be defined in a single file. • This doesn‟t lend itself to loose-coupling of the layers (M-V-C). • While beyond the scope of this talk, it should be noted that the config file can be separated across multiple Spring configuration files. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 40
  41. 41. Intertech Oxygen Blast 2008 • The controller, however, is the conduit to your application’s true business functionality. This class you must provide. • For those familiar with Struts, the Controller is very similar to the Struts Action. • For those familiar with JSF, the Controller is very similar to a managed bean. • While controllers can actually perform all the business logic, more appropriately designed controllers call on the model to get the job done. • Having the controller call on the business model provides the appropriate loose coupling between the M (model) and C (controller) layers. • The controller, in Spring, is just another JavaBean. This means you can take full advantage of DI, AOP, and every other aspect of Spring in building it. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 41
  42. 42. Intertech Oxygen Blast 2008 • Below is the code for the Greeting controller. • In this “greeting” controller example, the controller simply determines the value of a request parameter (state) and determines how to greet the user. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 42
  43. 43. //imports here public class GreetingController extends AbstractController{ private String name; Intertech Oxygen Blast 2008 public void setName(String n){ name=n; } public ModelAndView handleRequestInternal(HttpServletRequest request,HttpServletResponse resp) throws Exception { String stateChoice = request.getParameter(quot;statequot;); if (stateChoice!=null) { if (quot;Minnesotanquot;.equals(stateChoice)){ System.out.println(quot;This guy talks Minnesotan don't you knowquot;); return new ModelAndView(quot;mnViewquot;, quot;usernamequot;, name); } else if (quot;Texanquot;.equals(stateChoice)){ System.out.println(quot;Well all be - a big Texanquot;); return new ModelAndView(quot;txViewquot;, quot;usernamequot;, name); } else if (quot;Canadianquot;.equals(stateChoice)){ System.out.println(quot;A north of the border cannuckquot;); return new ModelAndView(quot;caViewquot;, quot;usernamequot;, name); } else if (quot;Philadephianquot;.equals(stateChoice)){ System.out.println(quot;Yo Adrianquot;); return new ModelAndView(quot;phillyViewquot;, quot;usernamequot;, name); } else { System.out.println(quot;Grazie - Italianoquot;); return new ModelAndView(quot;italyViewquot;,quot;usernamequot;, name); } } else { System.out.println(quot;We're not sure what they speak??quot;); return new ModelAndView(quot;mnViewquot;,quot;usernamequot;, name); } } } Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 43
  44. 44. Intertech Oxygen Blast 2008 • In this case, the controller extends Spring’s AbstractController. Spring provides a rich controller hierarchy which gets examined later. • The handleRequestInternal method is called by the framework when a handler mapping helps determine a request is for this GreetingController. • The name property in the GreetingController, like any Spring bean, can be dependency injected by the framework (more in a bit). • At the conclusion of its work in handleRequestInternal, the controller must return a ModelAndView object. • Again, this object must be set with the logical name of the next view and any model data that must be returned for the next view. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 44
  45. 45. Intertech Oxygen Blast 2008 • Spring provides the ModelAndView class. The class has many constructors, all to provide the logical view name and various types of model data. • In this example, the ModelAndView(String, String, Object) constructor is used to create a ModelAndView object. • The first parameter in construct call provides the logical name of the next view (mnView, txView, caView, etc. are the logical view names). • The second and third parameters provide a key value pair to a model object. • The key (second parameter) provides a means to reference the model object (third parameter). • In the example, the model always consists of the property name set to the key of “username”. This data can be used in the succeeding view. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 45
  46. 46. Intertech Oxygen Blast 2008 • All of the pieces of the Spring MVC environment, to include the controller above, must be wired together in the Spring configuration file. • Below is a minimum dispatcher-servlet.xml to wire together the application. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 46
  47. 47. Intertech Oxygen Blast 2008 <?xml version=quot;1.0quot; encoding=quot;UTF-8quot;?> <beans xmlns=quot;http://www.springframework.org/schema/beansquot; xmlns:xsi=quot;http://www.w3.org/2001/XMLSchema-instancequot; xsi:schemaLocation=quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdquot;> <bean id=quot;urlMapquot; class=quot;org.springframework.web.servlet.handler.SimpleUrlHandlerMappingquot;> <property name=quot;mappingsquot;> <props> <prop key=quot;greeting.requestquot;>greetingController</prop> </props> </property> </bean> <bean id=quot;greetingControllerquot; class= quot;com.intertech.GreetingControllerquot;> <property name=quot;namequot;> <value>Jim</value> </property> </bean> <bean id=quot;vresquot; class=quot;org.springframework.web.servlet.view.InternalResourceViewResolverquot;> <property name=quot;suffixquot;> <value>.jsp</value> </property> </bean> © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 47 Copyright </beans>
  48. 48. Intertech Oxygen Blast 2008 • In the center of the file, the GreetingController is configured. As with everything in Spring MVC it is just another JavaBean that the container must manage. • Notice that Dependency Injection is used to provide the “name” property a value. In this case, it is provide the value of “Jim”. • Recall from above, this DI provided property is passed as the model data to the next view in the controller and is used in the resulting greeting view. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 48
  49. 49. Intertech Oxygen Blast 2008 • What about the other parts of the controller? The other two beans: the SimpleURLHandlerMapping and the InternalResourceViewResolver? • Along with the DispatcherServlet and Controller, two additional objects are needed to assist the control layer. • A handler mapping object provides the DispatcherServlet assistance in reading the request and determining what controller to pass the request onto. • And a view resolver object assists the DispatcherServlet determine, based on the ModelAndView object returned, what view is displayed next. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 49
  50. 50. Intertech Oxygen Blast 2008 • Both the SimpleUrlHandlerMapping and InternalResourceViewResolver classes are provided with the Spring MVC framework. • So no work is required on your part to create them. • In fact, as you will learn, Spring MVC offers many handler mapping and view resolver objects to choose from. • You can implement your own handler mapping and/or view resolver. • However, your task as a developer is generally to pick the right handler mapping and view resolver object for the job and configure it. • The handler mapping and view resolver objects are just additional JavaBeans in the Spring environment. • So again, they are configured just as any JavaBean, in the Spring configuration file. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 50
  51. 51. Intertech Oxygen Blast 2008 • The SimpleUrlHandlerMapping, as its name implies, is a simple handler mapping object that uses the incoming request URL and maps that to a controller. • In this example, based on the form action, the URL of the request coming from the index.jsp page would be greeting.request. <form action=quot;greeting.requestquot; method=quot;POSTquot;> • As can be seen in the Spring configuration file, the handler mapping‟s property indicates that this URL is mapped to the Greeting controller bean. <prop key=quot;greeting.requestquot;>greetingController</prop> Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 51
  52. 52. Intertech Oxygen Blast 2008 • The InternalResourceViewResolver also uses a pretty simple strategy for helping the DispatcherServlet determine the next view to display. • The InternalResourceViewResolver takes the logical view name provided by the controller and simply adds text to develop the view name. • Recall that the controller must return a ModelAndView object. This object contains the next logical view name. • In the GreetingController, values such as “mnView”, “caView”, and “phillyView” are returned as logical names in the ModelAndView object. • The properties provided on the view resolver in the config indicate what strings to prefix and append to the logical view name to get the physical view name. • In this example, the InternalResourceViewResolver only appends a “.jsp” to the logical name. • However, if all the JSPs where stored in a /jsp folder, the property configuration could provide a prefix and suffix to get the right physical name. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 52
  53. 53. Intertech Oxygen Blast 2008 <property name=quot;prefixquot;> <value>/jsp/</value> </property> <property name=quot;suffixquot;> <value>.jsp</value> </property> • So if the user requests a Minnesotan greeting, “mnView” is returned by the controller as the next logical name. • It is then prefixed and suffixed with “/jsp/” and “.jsp” to provide the next physical view of “/jsp/mnView.jsp” which the DispatcherServlet displays. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 53
  54. 54. Intertech Oxygen Blast 2008 • Unlike many Web frameworks, Spring offers a rich set of controller classes that provide the interface between the control layer and the business model. • In the Greeting example above, you extended the AbstractController. This is a simple abstract class that does not offer many services/capabilities. • The controllers Spring provides are more advanced; providing better access to parameter and form data, validation, and even multi-page wizard control. • You can also write your own custom controller. It must implement the Spring Controller interface. • As can be seen by the diagram below, the list of controllers is extensive. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 54
  55. 55. Intertech Oxygen Blast 2008 Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 55
  56. 56. Intertech Oxygen Blast 2008 • Handler mapping objects map incoming requests to a controller. • Spring 2.0 or better comes with several handler mapping beans out of the box. • The table below lists the additional handler mapping classes. Additional Spring Handler Mapping Beans BeanNameUrlHandlerMapping CommonsPathMapHandlerMapping ControllerClassNameHandlerMapping • These other handler mappings allow for more complex means to map requests to controllers. • Of course, you can also implement your own custom handler mapping. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 56
  57. 57. Intertech Oxygen Blast 2008 • In the Greeting application, the InternalResourceViewResolver was used. • This view resolver simply attaches a prefix and suffix to the logical name to create a path to the view file (JSP, HTML page, etc.). • However, it is only one of many view resolvers. Some of the others are listed in the table below. Additional View Resolvers BeanNameViewResolver ResourceBundleViewResolver XmlViewResolver • Again, these resolvers allow for more complex view determination. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 57
  58. 58. Intertech Oxygen Blast 2008 • In most cases, the view resolvers resolve to what are termed “templated” views in Spring. • Templated views include JSPs and HTML • Some types of view resolvers, like the BeanNameViewResolver, can be configured to resolve to plain JavaBeans to produce the view. • This mechanism allows Spring to output non-traditional output such as Microsoft Excel spreadsheets, PDF documents, or other “views.” • In fact, Spring already comes with several built-in view classes that allow output of Excel, Word or PDF documents. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 58
  59. 59. Intertech Oxygen Blast 2008 • In the example below, an implementation of Spring‟s AbstractExcelView allows an Microsoft Excel Spreadsheet to be created and displayed. public class MyExcelView extends AbstractExcelView { protected void buildExcelDocument(Map model, HSSFWorkbook wb, HttpServletRequest req, HttpServletResponse resp) throws Exception { … //utilizes Jakarta POI, an API for creating MS Office documents, // to create/display an Excel document } } • Likewise, an AbstractPdfView class can create and display a PDF document. public class OrderPdfView extends AbstractPdfView { protected void buildPdfDocument(Map model, Document pdfDoc, PdfWriter pw, HttpServletRequest req, HttpServletResponse resp) throws Exception { … //utilize the iText PDF API to create and display a PDF document. } } Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 59
  60. 60. Intertech Oxygen Blast 2008 • As with other MVC frameworks, Spring provides a set of custom tags to be used in place of standard HTML form tags. • Just as Struts UI form tags do, these Spring form tags allow form fields to be bound to JavaBeans called command objects. • Binding goes both ways – the command bean is populated by field entries and fields are populated by command data • These tags help reduce the verbosity associated with manually setting HTML tag name and values. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 60
  61. 61. Intertech Oxygen Blast 2008 • To use the Spring Form Tags, the following taglib directive must be added to the page. <%@ taglib prefix=quot;formquot; uri=quot;http://www.springframework.org/tags/formquot; %> • An example login input form would look like the code below using the Spring form tags. <form:form commandName=“login” action=“login.request”> Username: <form:input path=quot;usernamequot;/><br/> Password: <form:password path=quot;passwordquot;/><br/> <input type=quot;submitquot; value=quot;Loginquot;/> </form:form> • In this example, the command bean is called login with username and password properties. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 61
  62. 62. Intertech Oxygen Blast 2008 • Additional form tags and their HTML equivalent are listed in the table below. Spring Form Tag HTML Tag <form:checkbox> <input type=quot;checkboxquot;> <form:errors> Renders an HTML <span> tag containing field errors <form:form> <form> <form:hidden> <input type=”hidden”> <form:input> <input type=”text”> <form:lable> <label> <form:password> <input type=”password”> <form:radiobutton> <input type=”radio”> <form:select> <select> <form:textarea> <textarea> <form:option> <option> <form:options> Many <option> Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 62
  63. 63. Intertech Oxygen Blast 2008 • In addition to the form tags, Spring also provides a set of tags for resolving message properties to provide for internationalization/localization. <spring:message code=”username”/> <form:input path=quot;usernamequot;/><br/> • All the Spring custom tag classes and tlds are in spring.jar. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 63
  64. 64. Intertech Oxygen Blast 2008 • Portlets are web components that run in a portlet container that are aggregated in a web page (view) in a portal. • Spring 2.0 provides a Portlet MVC framework. • This framework attempts to mimic the Spring Web MVC framework where ever possible. • DispatcherPortlet (vs. DispatcherServlet) • Handler mappings • View Resolvers • A rich controller hierarchy • The controllers in Portlet MVC are very similar to the Web MVC Controllers. • Handler mappings map incoming Portlet requests to controllers. • View resolution is handled by a special ViewRendererServlet. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 64
  65. 65. Intertech Oxygen Blast 2008 • A complete compare and contrast of all the major Java MVC Web frameworks is beyond the span of this talk. • To some extent, personal taste is a factor. • Below is a list of some of the more generally agreed upon pros/cons associated with each MVC frameworks. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 65
  66. 66. Intertech Oxygen Blast 2008 Struts 1 Struts 2/ Tapestry JSF Spring MVC WebWork •Lots of •Simple •HTML over JSPs •Java EE standard •IoC/DI, AOP ,… documentation, •Tag library and Tags •Swing for the •Unit testing examples, help •Interceptors •Powerful/ Web (rich UI) •Integration with •Validation and (validation) productive •Rich navigation other web tech. Pluses Layout modules •Navigation •Powerful event •Simple alternatives mechanism components for simple apps/Complex for complex apps •Tight coupling of •Small community •Steep learning •Lots of tags •Lots of classes to Struts •Documentation curve •No single Configuration Minuses (ActionForms, •Documentation implementor •JSP tags Action) •Lots of •Too many choices •Unit testing configuration •Difficult with security Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 66
  67. 67. Intertech Oxygen Blast 2008 • It should be noted that Spring allows most of the other MVC frameworks to be integrated with it. • Perhaps you already have a large investment in another MVC framework. • Perhaps you like the specific features of one of the frameworks. • Perhaps finding Spring resources is more difficult. • However, you also want to take advantage of DI, AOP and the other modules and features Spring has to offer. • That‟s ok! • Struts, JSF, Tapestry, and others can all be used in conjunction with Spring. • In some cases, Spring offers multiple integration options. • The ease of integration and leverage of Spring features (and vice versa) depends on each framework. • The Spring documentation, and most good text on Spring provide you starter kits on how to integrate your MVC with Spring. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 67
  68. 68. Intertech Oxygen Blast 2008 • Spring in Action, 2nd Edition by Craig Walls from Manning. • Java Development with the Spring Framework by Rod Johnson et. al from Wrox. • Pro Spring by Harrop & Machacek from Apress. • Spring: A Developer's Notebook by Tate & Gehtland from O’Reilly. • POJOs in Action: Developing Enterprise Applications with Lightweight Frameworks by Chris Richardson from Manning. • Spring’s Web site: www.springframework.org. • Collection of Spring info and links: www.springhub.com. • An open source Spring IDE: www.springide.org. • Spring tutorial: www.visualbuilder.com/java/spring/tutorial. • Another Spring tutorial: www.theserverside.com/tt/articles/article.tss?l=SpringFramework • Article on the difference between IoC and DI: martinfowler.com/articles/injection.html. • Matt Raible’s Comparison of MVC frameworks: Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 68 equinox.dev.java.net/framework-comparison/WebFrameworks.pdf
  69. 69. Intertech Oxygen Blast 2008 • Spring is an open source framework. • Spring was created to reduce the complexity observed in Java enterprise application development. • In general, Spring leverages plain-vanilla Java objects (POJOs) or more precisely JavaBeans to achieve enterprise tasks. • Spring is organized into many modules that offer various types of assistance to the developer in a host of application areas. • The MVC module provides a Model-View-Controller (MVC) implementation for Web applications. • Like other Java MVC frameworks, it provides state management, workflow, validation, etc. and it based primarily on servlet/JSP technology. • Unlike other frameworks, Spring uses JavaBeans and DI to create and assemble the MVC environment. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 69
  70. 70. Intertech Oxygen Blast 2008 • The Spring MVC framework is comprised of cooperating beans, often provided by the framework, which can be easily replaced. • In Spring, the controller is the DispatcherServlet. All requests must be directed to this servlet. • On a request, the DispatcherServlet consults a handler mapping object to figure out which controller should receive the request. • The controller object in Spring MVC acts as the conduit to the model, calling on various business logic code/components. • The controller packages up model data needed for the display and the logical name of the next view in a ModelAndView object. • The DispatcherServlet calls on a view resolver to help determine the next view. • The view resolver maps the logical name to some view, which is typically a JSP or HML page. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 70
  71. 71. Intertech Oxygen Blast 2008 • As with other MVC frameworks, Spring provides a set of custom tags to be used in place of standard HTML form tags. • Just as Struts UI form tags do, these Spring form tags allow form fields to be bound to command objects. Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 71
  72. 72. Intertech Oxygen Blast 2008 • Thanks for coming. • We hope you learned something and • Enjoyed the talk. • Come back and see us again. • Plenty of classes on Spring, Struts and other Java/.Net technologies this winter/spring. • Feel free to chat with one of our account reps for more info. • A PDF on this material will be emailed to you. • The demonstration code can be downloaded from Intertech at: http://www.intertech.com/downloads/SpringDemos.exe Copyright © Intertech, Inc. 2007 • www.Intertech.com • 800-866-9884 • Slide 72

×