SlideShare a Scribd company logo
An Introduction To the Spring
M.V.C. Framework
Outline
• Where we‟ve been

• M.V.C. Frameworks

• Why Use Spring

• IoC (Inversion of Control)

• Examples
• MVC Example
• Where do we go from here?

• Questions
Where we‟ve been
• Web based programming “The Servlet Way”

• JSP or HTML Form  Submit to servlet  Servlet
  Processes data & Outputs information

• Works well for small applications but can quickly grow out of
  control because HTML, scrip-lets, java script, tag-libraries,
  database access, and business logic makes it difficult to
  organize.

• Put simply, lack of structure can cause a “soup” of different
  technologies.

• JSP‟s compile to Servlet
“A Better Way?”

• Separate the Data Access, Business Logic
  and Presentation using a M.V.C.
  Framework.

Choose a M.V.C. framework:
• WebWork, Spring, Struts, Java-Server-
  Faces, Tapestry plus “many more”
Things change:
• Struts, by far is the most popular; same
  creator of Struts (Craig McClanahan) is the
  co-spec leader of Java Server Faces.

• Webwork evolved to Webwork2

• Tapestry - has been around for awhile.

• Spring – “newer” of the frameworks.
  Integrates well with any other framework
  or by itself.
Why use Spring?
• All frameworks integrate well with Spring.

• Spring offers an open yet structured framework, using
  dependency-injection, a type of inversion-of-control to
  integrate different technologies together.

• Consistent Configuration, open plug-in architecture

• Integrates well with different O/R Mapping frameworks
  like Hibernate

• Easier to test applications with.

• Less complicated then other frameworks.

• Active user community, many new books coming out.
Want to integrate your existing web-app with a
Spring middle tier?

   – Struts
      • http://struts.sourceforge.net/struts-spring/

   – Web Work
      • http://wiki.opensymphony.com/space/Spring+Frame
        work+Integration

   – Tapestry
      • http://www.springframework.org/docs/integration/tap
        estry.html
What if I like Microsoft .NET?



Then try Spring Framework .NET
http://sourceforge.net/projects/springnet/
Why I chose to learn the Spring framework

• Because of IoC/Dependency Injection you can easily
  change configurations.

• Addresses end-to-end requirements, not just one part.

• Spring is well organized and seems easier to learn then
  struts.

• Portable across deployment environments.

• Integrates well with Hibernate
Meant to wet your appetite and note be compressive.
Downsides:
• Not as mature as other frameworks (but very
  stable).

• Market share is small at this time, but rapidly
  growing.

• dependency-injection (Inversion-of-control) is a
  different way of thinking (This is actually a plus).

• Not a-lot of tool support for Spring yet. A plug-in
  for Eclipse is available.

• Depends on who you ask.
Spring is not just a Presentation M.V.C. Framework:

Persistence support:
• Spring also supports A JDBC Framework that makes it
  easier to create JDBC Apps.

• Supports O/R mapping Frameworks making it easier to use
  O/R tools like Hibernate & JDO

• Spring offers Connection Pooling for any POJO.

• Supports transaction framework

• Has good support for aspect-oriented-programming

• Plus much more.
What is dependency-injection & why use it?

• Dependency-injection (a type of IoC) is when you
  let your framework control your application.

• Spring links objects together instead of the
  objects linking themselves together.

• Spring object linking is defined in XML files,
  allowing easy changes for different application
  configurations thus working as a plug in
  architecture.

• Dependency injection is where the control of the
  application is inverted to the framework. This
  control is configured in the framework with an
  XML file.
Without Dependency-Injection/IoC

                            creates               Object B


          Object A



                            creates
                                                 Object C




An object creating its dependencies without IoC leads to tight object
coupling.
With Dependency-Injection/IoC
Allows objects to be created at higher levels and passed
into object so they can use the implementation directly



            Object B                  setB(IB)

                                                      Object A


                                       setC(IC)
            Object C



   Object A contains setter methods that accept interfaces to objects B
   and C. This could have also been achieved with constructors in
   object A that accepts objects B and C.
Spring supports two types of dependency injection
“setter-based” and “constructor based” injection
• Code Example of setter based injection:
<beans>
 <bean name="person" class="examples.spring.Person">
   <property name="email">
      <value>my@email.address</value>
   </property>
 </bean>
</beans>

*** beans are accessed by there “bean name”

Interpretation of the above code:
Person person = new Person();
person.setEmail(“my@email.address”);


This code creates a Person object and calls the setEmail() method,
passing in the string defined as a value.
Constructor based injection

<beans>
 <bean name="fileDataProcessor“ class="examples.spring.DataProcessor"
   singleton="true">
   <constructor-arg>
         <ref bean="fileDataReader"/>
   </constructor-arg>
 </bean>
 <bean name="fileDataReader" class="examples.spring.FileDataReader"
   singleton="true">
   <constructor-arg>
         <value>/data/file1.data</value>
   </constructor-arg>
 </bean>
</beans>

Interpretation of the above code:
FileDataReader fileDataReader = new FileDataReader(“/data/file1.data”);
DataProcessor fileDataProcessor = new DataProcessor(fileDataReader);
Spring provides a JDBC Template that manages your connections for you.
  *** Simple example of connecting to a datasource. ***
  ProductManagerDaoJdbc implements ProductManagerDao {
      public void setDataSource(DataSource ds) {
            this.ds = ds;
      }
  }
  *** No need to change java code when changing datasource; change in
      „Spring bean‟ XML file below.
  <beans>
      <bean name="dataSource"
      class="com.mysql.jdbc.jdbc2.optional.MysqlDataSource" destroy-
      method="close">
      <property name="url">
            <value>jdbc:mysql://localhost/test</value>
      </property>
  <beans>
  <bean id="prodManDao" class="db.ProductManagerDaoJdbc">
      <property name="dataSource">
            <ref bean="dataSource"/>
      </property>
  </bean>
Spring Web
Key Concepts
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.
Spring Web Container Setup
In your Web Container, the Spring “bean” XML file
  exists in the same directory as your web.xml file
  with a “-servlet.xml” appended to it.

webapps
 /tradingapp
     /WEB-INF/tradingapp-servlet.xml, web.xml)
           /classes
           /lib (all jar files)

The dispatcher servlet is mapped to the name
  “tradingapp” so it knows to look in the “tradingapp-
  servlet.xml” file to look-up a URL-to- Controller
  match.
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 tradingapp-
    servlet.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-servlet.xml
<bean id="urlMapping"
   class="org.springframework.SimpleUrlHandlerMapping">
 <property name="urlMap">
   <map>
        <entry key="/logon.htm">
                  <ref bean="logonForm"/>
        </entry>
   </map>
                                This class extends Springs SimpleFormController
 </property>
                                Which defines a setSuccessView() method
</bean>

<bean id="logonForm" class="com.tradingapp.LogonFormController">
   <property name="sessionForm"><value>true</value></property>
   <property name="commandName"><value>credentials</value></property
   <property name="commandClass">
        <value>com.tradingapp.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 it passes “validator” then successView, passes to portfolio.htm page
Review of the process so far
• User goes to this URL:
  http://tradingapp/logon.htm
• Since the URL ends with “.htm”, the
  tradingapp-servlet.xml file is loaded to
  determine what controller to use.
• The <bean name urlMapping …/> says to refer
  to the <bean id="logonForm"
  class="com.tradingapp.LogonFormController">
• Since the LogonFormController extends
  SimpleFormController we can use the methods
  defined in the SimpleFormController class to do
  all kinds of form checking, e.g. validation.
What our LogonFormController Looks Like.
public class LogonFormController extends SimpleFormController {
  public ModelAndView onSubmit(Object command) throws ServletException {
     return new ModelAndView(new RedirectView(getSuccessView()));
  }
}

Remember our tradingapp-servler.xml file?

<bean id="logonForm" class="com.tradingapp.LogonFormController">
   <property name="sessionForm"><value>true</value></property>
   <property name="commandName"><value>credentials</value></property
   <property name="commandClass">
        <value>com.tradingapp.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, go here
successView /portfolio.htm
Where do I go if there is a validation error in my logon page?
tradingapp-servler.xml
<bean id="logonForm" class="com.tradingapp.LogonFormController">
    <property name="sessionForm"><value>true</value></property>
    <property name="commandName"><value>credentials</value></property
    <property name="commandClass">
         <value>com.tradingapp.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>

 <bean id="logonValidator" class="com.devx.tradingapp.web.LogonValidator"/>

 *** Your LogonFormController will check the validation “first” without writing
  any additional code because your LogonFormController extends Springs
    SimpleFormController.
   Next: The LogonValidator implements Springs Validator interface.

   On error go back to formView, that is where you started.
Logon page with error message




    Next: code for LogonValidator implements Springs Validator
Example code of validator
tradingapp-servler.xml
<bean id="logonForm" class="com.tradingapp.LogonFormController">
   <property name="commandName"><value>credentials</value></property
   <property name="commandClass">
        <value>com.tradingapp.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>

<bean id="logonValidator" class="com.devx.tradingapp.web.LogonValidator"/>

public class LogonValidator implements Validator {
  public void validate(Object obj, Errors errors) {
  Credentials credentials = (Credentials) obj;         Command / form backing bean
  if (credentials.getPassword().equals("guest") == false) {
         errors.rejectValue("password", "error.login.invalid-pass",
                 null, "Incorrect Password.");
          }
}               Next: Command/Form Backing Bean
Command/Form Backing Bean is a POJO
public class Credentials {
   private String username;

    private String password;

    public String getPassword() {
          return password;
    }

    public void setPassword(String password) {
          this.password = password;
    }

    public String getUsername() {
          return username;
    }

    public void setUsername(String username) {
    this.username = username;
    }
}              Next: Why its called a “command” or “form backing bean”
Command/Form Backing Bean is a POJO
                                       public class Credentials {
logon.htm form                           private String username;

                                           private String password;
  Username:
                                           public String getPassword() {
                                             return password;
                                           }

  Password:                              public void setPassword(String
                                       password) {
                                           this.password = password;
The logon form is “backed” by the        }
Credentials bean and given a
commandName of “credentials”               public String getUsername() {
defined in out springapp-servlet.xml         return username;
                                           }
file. “credentials” will be our
“command object” we will use to          public void setUsername(String
bind the form to the bean.             username) {
                                           this.username = username;
Next: another look at springapp-
                                           }
servlet.xml file
                                       }
springapp-servlet.xml file
<bean id="logonForm" class="com.tradingapp.LogonFormController">
   <property name="commandName"><value>credentials</value></property
   <property name="commandClass">
        <value>com.tradingapp.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>



    We use the commandName “credentials”
    with Spring‟s tag library, to bind the
    Credentials bean to the logon form.

Next: Code that shows logon form binding to commandName
logon form binding to commandName using
Springs Tag Library
<%@ taglib prefix="spring" uri="/spring" %>
<html>
<head><title>DevX.com Stock-Trading System
   Logon</title></head>
<body>
<spring:bind path="credentials.username">
<input type="text" name="username"
<spring:bind path="credentials.password">
<input type="password" name="password" />
</body>
           Spring‟s taglib has bound the bean to the form
</html>
Where do we go from here.
Presentation based on tutorials from:
Javid Jamae
http://www.devx.com/Java/Article/21665/0/page/1

- Other Spring Presentations & Tutorials
http://ckny.eatj.com/wiki/jsp/Wiki?Spring#presentations

- Categories from AOP to Security (Acegi) check out
   Springs: Forum
http://forum.springframework.org/index.php
Ad

More Related Content

What's hot (20)

Data Access Options in SharePoint 2010
Data Access Options in SharePoint 2010Data Access Options in SharePoint 2010
Data Access Options in SharePoint 2010
Rob Windsor
 
MVC Training Part 1
MVC Training Part 1MVC Training Part 1
MVC Training Part 1
Lee Englestone
 
Jinal desai .net
Jinal desai .netJinal desai .net
Jinal desai .net
rohitkumar1987in
 
Introduction to the SharePoint Client Object Model and REST API
Introduction to the SharePoint Client Object Model and REST APIIntroduction to the SharePoint Client Object Model and REST API
Introduction to the SharePoint Client Object Model and REST API
Rob Windsor
 
SharePoint 2010 Client Object Model
SharePoint 2010 Client Object ModelSharePoint 2010 Client Object Model
SharePoint 2010 Client Object Model
G. Scott Singleton
 
Spring mvc 2.0
Spring mvc 2.0Spring mvc 2.0
Spring mvc 2.0
Rudra Garnaik, PMI-ACP®
 
Jsf
JsfJsf
Jsf
Shaharyar khan
 
Spring MVC 3.0 Framework (sesson_2)
Spring MVC 3.0 Framework (sesson_2)Spring MVC 3.0 Framework (sesson_2)
Spring MVC 3.0 Framework (sesson_2)
Ravi Kant Soni ([email protected])
 
Introduction to the Client OM in SharePoint 2010
Introduction to the Client OM in SharePoint 2010Introduction to the Client OM in SharePoint 2010
Introduction to the Client OM in SharePoint 2010
Ben Robb
 
Web API with ASP.NET MVC by Software development company in india
Web API with ASP.NET  MVC  by Software development company in indiaWeb API with ASP.NET  MVC  by Software development company in india
Web API with ASP.NET MVC by Software development company in india
iFour Institute - Sustainable Learning
 
Jsf intro
Jsf introJsf intro
Jsf intro
vantinhkhuc
 
Asp.Net Mvc
Asp.Net MvcAsp.Net Mvc
Asp.Net Mvc
micham
 
Microsoft Azure
Microsoft AzureMicrosoft Azure
Microsoft Azure
Dima Maleev
 
Ch 04 asp.net application
Ch 04 asp.net application Ch 04 asp.net application
Ch 04 asp.net application
Madhuri Kavade
 
New Features Of ASP.Net 4 0
New Features Of ASP.Net 4 0New Features Of ASP.Net 4 0
New Features Of ASP.Net 4 0
Dima Maleev
 
dbadapters
dbadaptersdbadapters
dbadapters
XAVIERCONSULTANTS
 
Asp.net
Asp.netAsp.net
Asp.net
Naveen Sihag
 
Oracle ADF 11g Tutorial
Oracle ADF 11g TutorialOracle ADF 11g Tutorial
Oracle ADF 11g Tutorial
Rakesh Gujjarlapudi
 
Angular - Chapter 3 - Components
Angular - Chapter 3 - ComponentsAngular - Chapter 3 - Components
Angular - Chapter 3 - Components
WebStackAcademy
 
Introduction to apex code
Introduction to apex codeIntroduction to apex code
Introduction to apex code
EdwinOstos
 
Data Access Options in SharePoint 2010
Data Access Options in SharePoint 2010Data Access Options in SharePoint 2010
Data Access Options in SharePoint 2010
Rob Windsor
 
Introduction to the SharePoint Client Object Model and REST API
Introduction to the SharePoint Client Object Model and REST APIIntroduction to the SharePoint Client Object Model and REST API
Introduction to the SharePoint Client Object Model and REST API
Rob Windsor
 
SharePoint 2010 Client Object Model
SharePoint 2010 Client Object ModelSharePoint 2010 Client Object Model
SharePoint 2010 Client Object Model
G. Scott Singleton
 
Introduction to the Client OM in SharePoint 2010
Introduction to the Client OM in SharePoint 2010Introduction to the Client OM in SharePoint 2010
Introduction to the Client OM in SharePoint 2010
Ben Robb
 
Asp.Net Mvc
Asp.Net MvcAsp.Net Mvc
Asp.Net Mvc
micham
 
Ch 04 asp.net application
Ch 04 asp.net application Ch 04 asp.net application
Ch 04 asp.net application
Madhuri Kavade
 
New Features Of ASP.Net 4 0
New Features Of ASP.Net 4 0New Features Of ASP.Net 4 0
New Features Of ASP.Net 4 0
Dima Maleev
 
Angular - Chapter 3 - Components
Angular - Chapter 3 - ComponentsAngular - Chapter 3 - Components
Angular - Chapter 3 - Components
WebStackAcademy
 
Introduction to apex code
Introduction to apex codeIntroduction to apex code
Introduction to apex code
EdwinOstos
 

Viewers also liked (8)

Minicollge Webtypografie
Minicollge WebtypografieMinicollge Webtypografie
Minicollge Webtypografie
remohollaar
 
Access Net Web Services From Java
Access  Net Web Services From JavaAccess  Net Web Services From Java
Access Net Web Services From Java
Guo Albert
 
Nig project setup quickly tutorial
Nig project setup quickly tutorialNig project setup quickly tutorial
Nig project setup quickly tutorial
Guo Albert
 
This Presentation will Revolutionize News Feed E-commerce
This Presentation will Revolutionize News Feed E-commerceThis Presentation will Revolutionize News Feed E-commerce
This Presentation will Revolutionize News Feed E-commerce
Tommyismyname
 
Spring 2.x 中文
Spring 2.x 中文Spring 2.x 中文
Spring 2.x 中文
Guo Albert
 
Overview chap1
Overview chap1Overview chap1
Overview chap1
Guo Albert
 
JPA lifecycle events practice
JPA lifecycle events practiceJPA lifecycle events practice
JPA lifecycle events practice
Guo Albert
 
eCommerce Cloud
eCommerce CloudeCommerce Cloud
eCommerce Cloud
ecommercecloud
 
Minicollge Webtypografie
Minicollge WebtypografieMinicollge Webtypografie
Minicollge Webtypografie
remohollaar
 
Access Net Web Services From Java
Access  Net Web Services From JavaAccess  Net Web Services From Java
Access Net Web Services From Java
Guo Albert
 
Nig project setup quickly tutorial
Nig project setup quickly tutorialNig project setup quickly tutorial
Nig project setup quickly tutorial
Guo Albert
 
This Presentation will Revolutionize News Feed E-commerce
This Presentation will Revolutionize News Feed E-commerceThis Presentation will Revolutionize News Feed E-commerce
This Presentation will Revolutionize News Feed E-commerce
Tommyismyname
 
Spring 2.x 中文
Spring 2.x 中文Spring 2.x 中文
Spring 2.x 中文
Guo Albert
 
Overview chap1
Overview chap1Overview chap1
Overview chap1
Guo Albert
 
JPA lifecycle events practice
JPA lifecycle events practiceJPA lifecycle events practice
JPA lifecycle events practice
Guo Albert
 
Ad

Similar to Toms introtospring mvc (20)

springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892
Tuna Tore
 
Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5
Tuna Tore
 
Skillwise-Spring framework 1
Skillwise-Spring framework 1Skillwise-Spring framework 1
Skillwise-Spring framework 1
Skillwise Group
 
MVC
MVCMVC
MVC
akshin
 
Spring framework in depth
Spring framework in depthSpring framework in depth
Spring framework in depth
Vinay Kumar
 
Spring Basics
Spring BasicsSpring Basics
Spring Basics
Emprovise
 
Spring User Guide
Spring User GuideSpring User Guide
Spring User Guide
Muthuselvam RS
 
Spring and DWR
Spring and DWRSpring and DWR
Spring and DWR
wiradikusuma
 
SpringBootCompleteBootcamp.pptx
SpringBootCompleteBootcamp.pptxSpringBootCompleteBootcamp.pptx
SpringBootCompleteBootcamp.pptx
SUFYAN SATTAR
 
Spring Framework
Spring FrameworkSpring Framework
Spring Framework
nomykk
 
ASP.net MVC CodeCamp Presentation
ASP.net MVC CodeCamp PresentationASP.net MVC CodeCamp Presentation
ASP.net MVC CodeCamp Presentation
buildmaster
 
Spring (1)
Spring (1)Spring (1)
Spring (1)
Aneega
 
Spring Boot
Spring BootSpring Boot
Spring Boot
HongSeong Jeon
 
Sel study notes
Sel study notesSel study notes
Sel study notes
Lalit Singh
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
Raveendra R
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
Collaboration Technologies
 
Spring 3.1: a Walking Tour
Spring 3.1: a Walking TourSpring 3.1: a Walking Tour
Spring 3.1: a Walking Tour
Joshua Long
 
Web Components v1
Web Components v1Web Components v1
Web Components v1
Mike Wilcox
 
Spring mvc
Spring mvcSpring mvc
Spring mvc
Hamid Ghorbani
 
Spring data jpa are used to develop spring applications
Spring data jpa are used to develop spring applicationsSpring data jpa are used to develop spring applications
Spring data jpa are used to develop spring applications
michaelaaron25322
 
springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892
Tuna Tore
 
Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5
Tuna Tore
 
Skillwise-Spring framework 1
Skillwise-Spring framework 1Skillwise-Spring framework 1
Skillwise-Spring framework 1
Skillwise Group
 
Spring framework in depth
Spring framework in depthSpring framework in depth
Spring framework in depth
Vinay Kumar
 
Spring Basics
Spring BasicsSpring Basics
Spring Basics
Emprovise
 
SpringBootCompleteBootcamp.pptx
SpringBootCompleteBootcamp.pptxSpringBootCompleteBootcamp.pptx
SpringBootCompleteBootcamp.pptx
SUFYAN SATTAR
 
Spring Framework
Spring FrameworkSpring Framework
Spring Framework
nomykk
 
ASP.net MVC CodeCamp Presentation
ASP.net MVC CodeCamp PresentationASP.net MVC CodeCamp Presentation
ASP.net MVC CodeCamp Presentation
buildmaster
 
Spring (1)
Spring (1)Spring (1)
Spring (1)
Aneega
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
Raveendra R
 
Spring 3.1: a Walking Tour
Spring 3.1: a Walking TourSpring 3.1: a Walking Tour
Spring 3.1: a Walking Tour
Joshua Long
 
Web Components v1
Web Components v1Web Components v1
Web Components v1
Mike Wilcox
 
Spring data jpa are used to develop spring applications
Spring data jpa are used to develop spring applicationsSpring data jpa are used to develop spring applications
Spring data jpa are used to develop spring applications
michaelaaron25322
 
Ad

More from Guo Albert (20)

AWS IAM (Identity and Access Management) Policy Simulator
AWS IAM (Identity and Access Management) Policy SimulatorAWS IAM (Identity and Access Management) Policy Simulator
AWS IAM (Identity and Access Management) Policy Simulator
Guo Albert
 
TOEIC 準備心得
TOEIC 準備心得TOEIC 準備心得
TOEIC 準備心得
Guo Albert
 
DBM專案環境建置
DBM專案環境建置DBM專案環境建置
DBM專案環境建置
Guo Albert
 
JPA Optimistic Locking With @Version
JPA Optimistic Locking With @VersionJPA Optimistic Locking With @Version
JPA Optimistic Locking With @Version
Guo Albert
 
OCEJPA Study Notes
OCEJPA Study NotesOCEJPA Study Notes
OCEJPA Study Notes
Guo Albert
 
OCEJPA(1Z0-898) Preparation Tips
OCEJPA(1Z0-898) Preparation TipsOCEJPA(1Z0-898) Preparation Tips
OCEJPA(1Z0-898) Preparation Tips
Guo Albert
 
XDate - a modern java-script date library
XDate -  a modern java-script date libraryXDate -  a modern java-script date library
XDate - a modern java-script date library
Guo Albert
 
How to avoid check style errors
How to avoid check style errorsHow to avoid check style errors
How to avoid check style errors
Guo Albert
 
NIG系統報表開發指南
NIG系統報表開發指南NIG系統報表開發指南
NIG系統報表開發指南
Guo Albert
 
Ease Your Effort of Putting Data into History Table
Ease Your Effort of Putting Data into History TableEase Your Effort of Putting Data into History Table
Ease Your Effort of Putting Data into History Table
Guo Albert
 
NIG 系統開發指引
NIG 系統開發指引NIG 系統開發指引
NIG 系統開發指引
Guo Albert
 
NIG系統開發文件閱讀步驟
NIG系統開發文件閱讀步驟NIG系統開發文件閱讀步驟
NIG系統開發文件閱讀步驟
Guo Albert
 
Form Bean Creation Process for NIG System
Form Bean Creation Process for NIG SystemForm Bean Creation Process for NIG System
Form Bean Creation Process for NIG System
Guo Albert
 
A Short Intorduction to JasperReports
A Short Intorduction to JasperReportsA Short Intorduction to JasperReports
A Short Intorduction to JasperReports
Guo Albert
 
Apply Template Method Pattern in Report Implementation
Apply Template Method Pattern in Report ImplementationApply Template Method Pattern in Report Implementation
Apply Template Method Pattern in Report Implementation
Guo Albert
 
Utilize Commons BeansUtils to do copy object
Utilize Commons BeansUtils to do copy objectUtilize Commons BeansUtils to do copy object
Utilize Commons BeansUtils to do copy object
Guo Albert
 
Apply my eclipse to do entity class generation
Apply my eclipse to do entity class generationApply my eclipse to do entity class generation
Apply my eclipse to do entity class generation
Guo Albert
 
Spring JDBCTemplate
Spring JDBCTemplateSpring JDBCTemplate
Spring JDBCTemplate
Guo Albert
 
Java Server Faces + Spring MVC Framework
Java Server Faces + Spring MVC FrameworkJava Server Faces + Spring MVC Framework
Java Server Faces + Spring MVC Framework
Guo Albert
 
Spring db-access mod03
Spring db-access mod03Spring db-access mod03
Spring db-access mod03
Guo Albert
 
AWS IAM (Identity and Access Management) Policy Simulator
AWS IAM (Identity and Access Management) Policy SimulatorAWS IAM (Identity and Access Management) Policy Simulator
AWS IAM (Identity and Access Management) Policy Simulator
Guo Albert
 
TOEIC 準備心得
TOEIC 準備心得TOEIC 準備心得
TOEIC 準備心得
Guo Albert
 
DBM專案環境建置
DBM專案環境建置DBM專案環境建置
DBM專案環境建置
Guo Albert
 
JPA Optimistic Locking With @Version
JPA Optimistic Locking With @VersionJPA Optimistic Locking With @Version
JPA Optimistic Locking With @Version
Guo Albert
 
OCEJPA Study Notes
OCEJPA Study NotesOCEJPA Study Notes
OCEJPA Study Notes
Guo Albert
 
OCEJPA(1Z0-898) Preparation Tips
OCEJPA(1Z0-898) Preparation TipsOCEJPA(1Z0-898) Preparation Tips
OCEJPA(1Z0-898) Preparation Tips
Guo Albert
 
XDate - a modern java-script date library
XDate -  a modern java-script date libraryXDate -  a modern java-script date library
XDate - a modern java-script date library
Guo Albert
 
How to avoid check style errors
How to avoid check style errorsHow to avoid check style errors
How to avoid check style errors
Guo Albert
 
NIG系統報表開發指南
NIG系統報表開發指南NIG系統報表開發指南
NIG系統報表開發指南
Guo Albert
 
Ease Your Effort of Putting Data into History Table
Ease Your Effort of Putting Data into History TableEase Your Effort of Putting Data into History Table
Ease Your Effort of Putting Data into History Table
Guo Albert
 
NIG 系統開發指引
NIG 系統開發指引NIG 系統開發指引
NIG 系統開發指引
Guo Albert
 
NIG系統開發文件閱讀步驟
NIG系統開發文件閱讀步驟NIG系統開發文件閱讀步驟
NIG系統開發文件閱讀步驟
Guo Albert
 
Form Bean Creation Process for NIG System
Form Bean Creation Process for NIG SystemForm Bean Creation Process for NIG System
Form Bean Creation Process for NIG System
Guo Albert
 
A Short Intorduction to JasperReports
A Short Intorduction to JasperReportsA Short Intorduction to JasperReports
A Short Intorduction to JasperReports
Guo Albert
 
Apply Template Method Pattern in Report Implementation
Apply Template Method Pattern in Report ImplementationApply Template Method Pattern in Report Implementation
Apply Template Method Pattern in Report Implementation
Guo Albert
 
Utilize Commons BeansUtils to do copy object
Utilize Commons BeansUtils to do copy objectUtilize Commons BeansUtils to do copy object
Utilize Commons BeansUtils to do copy object
Guo Albert
 
Apply my eclipse to do entity class generation
Apply my eclipse to do entity class generationApply my eclipse to do entity class generation
Apply my eclipse to do entity class generation
Guo Albert
 
Spring JDBCTemplate
Spring JDBCTemplateSpring JDBCTemplate
Spring JDBCTemplate
Guo Albert
 
Java Server Faces + Spring MVC Framework
Java Server Faces + Spring MVC FrameworkJava Server Faces + Spring MVC Framework
Java Server Faces + Spring MVC Framework
Guo Albert
 
Spring db-access mod03
Spring db-access mod03Spring db-access mod03
Spring db-access mod03
Guo Albert
 

Recently uploaded (20)

UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Library Association of Ireland
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Library Association of Ireland
 
New Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptxNew Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptx
milanasargsyan5
 
Quality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdfQuality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdf
Dr. Bindiya Chauhan
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptxSCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
Ronisha Das
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
Handling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptxHandling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptx
AuthorAIDNationalRes
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Celine George
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
Social Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy StudentsSocial Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy Students
DrNidhiAgarwal
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Library Association of Ireland
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Library Association of Ireland
 
New Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptxNew Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptx
milanasargsyan5
 
Quality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdfQuality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdf
Dr. Bindiya Chauhan
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptxSCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
Ronisha Das
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
Handling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptxHandling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptx
AuthorAIDNationalRes
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Celine George
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
Social Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy StudentsSocial Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy Students
DrNidhiAgarwal
 

Toms introtospring mvc

  • 1. An Introduction To the Spring M.V.C. Framework
  • 2. Outline • Where we‟ve been • M.V.C. Frameworks • Why Use Spring • IoC (Inversion of Control) • Examples • MVC Example • Where do we go from here? • Questions
  • 3. Where we‟ve been • Web based programming “The Servlet Way” • JSP or HTML Form  Submit to servlet  Servlet Processes data & Outputs information • Works well for small applications but can quickly grow out of control because HTML, scrip-lets, java script, tag-libraries, database access, and business logic makes it difficult to organize. • Put simply, lack of structure can cause a “soup” of different technologies. • JSP‟s compile to Servlet
  • 4. “A Better Way?” • Separate the Data Access, Business Logic and Presentation using a M.V.C. Framework. Choose a M.V.C. framework: • WebWork, Spring, Struts, Java-Server- Faces, Tapestry plus “many more”
  • 5. Things change: • Struts, by far is the most popular; same creator of Struts (Craig McClanahan) is the co-spec leader of Java Server Faces. • Webwork evolved to Webwork2 • Tapestry - has been around for awhile. • Spring – “newer” of the frameworks. Integrates well with any other framework or by itself.
  • 6. Why use Spring? • All frameworks integrate well with Spring. • Spring offers an open yet structured framework, using dependency-injection, a type of inversion-of-control to integrate different technologies together. • Consistent Configuration, open plug-in architecture • Integrates well with different O/R Mapping frameworks like Hibernate • Easier to test applications with. • Less complicated then other frameworks. • Active user community, many new books coming out.
  • 7. Want to integrate your existing web-app with a Spring middle tier? – Struts • http://struts.sourceforge.net/struts-spring/ – Web Work • http://wiki.opensymphony.com/space/Spring+Frame work+Integration – Tapestry • http://www.springframework.org/docs/integration/tap estry.html
  • 8. What if I like Microsoft .NET? Then try Spring Framework .NET http://sourceforge.net/projects/springnet/
  • 9. Why I chose to learn the Spring framework • Because of IoC/Dependency Injection you can easily change configurations. • Addresses end-to-end requirements, not just one part. • Spring is well organized and seems easier to learn then struts. • Portable across deployment environments. • Integrates well with Hibernate Meant to wet your appetite and note be compressive.
  • 10. Downsides: • Not as mature as other frameworks (but very stable). • Market share is small at this time, but rapidly growing. • dependency-injection (Inversion-of-control) is a different way of thinking (This is actually a plus). • Not a-lot of tool support for Spring yet. A plug-in for Eclipse is available. • Depends on who you ask.
  • 11. Spring is not just a Presentation M.V.C. Framework: Persistence support: • Spring also supports A JDBC Framework that makes it easier to create JDBC Apps. • Supports O/R mapping Frameworks making it easier to use O/R tools like Hibernate & JDO • Spring offers Connection Pooling for any POJO. • Supports transaction framework • Has good support for aspect-oriented-programming • Plus much more.
  • 12. What is dependency-injection & why use it? • Dependency-injection (a type of IoC) is when you let your framework control your application. • Spring links objects together instead of the objects linking themselves together. • Spring object linking is defined in XML files, allowing easy changes for different application configurations thus working as a plug in architecture. • Dependency injection is where the control of the application is inverted to the framework. This control is configured in the framework with an XML file.
  • 13. Without Dependency-Injection/IoC creates Object B Object A creates Object C An object creating its dependencies without IoC leads to tight object coupling.
  • 14. With Dependency-Injection/IoC Allows objects to be created at higher levels and passed into object so they can use the implementation directly Object B setB(IB) Object A setC(IC) Object C Object A contains setter methods that accept interfaces to objects B and C. This could have also been achieved with constructors in object A that accepts objects B and C.
  • 15. Spring supports two types of dependency injection “setter-based” and “constructor based” injection • Code Example of setter based injection: <beans> <bean name="person" class="examples.spring.Person"> <property name="email"> <value>[email protected]</value> </property> </bean> </beans> *** beans are accessed by there “bean name” Interpretation of the above code: Person person = new Person(); person.setEmail(“[email protected]”); This code creates a Person object and calls the setEmail() method, passing in the string defined as a value.
  • 16. Constructor based injection <beans> <bean name="fileDataProcessor“ class="examples.spring.DataProcessor" singleton="true"> <constructor-arg> <ref bean="fileDataReader"/> </constructor-arg> </bean> <bean name="fileDataReader" class="examples.spring.FileDataReader" singleton="true"> <constructor-arg> <value>/data/file1.data</value> </constructor-arg> </bean> </beans> Interpretation of the above code: FileDataReader fileDataReader = new FileDataReader(“/data/file1.data”); DataProcessor fileDataProcessor = new DataProcessor(fileDataReader);
  • 17. Spring provides a JDBC Template that manages your connections for you. *** Simple example of connecting to a datasource. *** ProductManagerDaoJdbc implements ProductManagerDao { public void setDataSource(DataSource ds) { this.ds = ds; } } *** No need to change java code when changing datasource; change in „Spring bean‟ XML file below. <beans> <bean name="dataSource" class="com.mysql.jdbc.jdbc2.optional.MysqlDataSource" destroy- method="close"> <property name="url"> <value>jdbc:mysql://localhost/test</value> </property> <beans> <bean id="prodManDao" class="db.ProductManagerDaoJdbc"> <property name="dataSource"> <ref bean="dataSource"/> </property> </bean>
  • 19. 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.
  • 20. Spring Web Container Setup In your Web Container, the Spring “bean” XML file exists in the same directory as your web.xml file with a “-servlet.xml” appended to it. webapps /tradingapp /WEB-INF/tradingapp-servlet.xml, web.xml) /classes /lib (all jar files) The dispatcher servlet is mapped to the name “tradingapp” so it knows to look in the “tradingapp- servlet.xml” file to look-up a URL-to- Controller match.
  • 21. 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 tradingapp- servlet.xml file and routes the user to the correct controller.
  • 22. Our Demo Logon Form at URL http://localhost/tradingapp/logon.htm
  • 23. 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.
  • 24. tradingapp-servlet.xml <bean id="urlMapping" class="org.springframework.SimpleUrlHandlerMapping"> <property name="urlMap"> <map> <entry key="/logon.htm"> <ref bean="logonForm"/> </entry> </map> This class extends Springs SimpleFormController </property> Which defines a setSuccessView() method </bean> <bean id="logonForm" class="com.tradingapp.LogonFormController"> <property name="sessionForm"><value>true</value></property> <property name="commandName"><value>credentials</value></property <property name="commandClass"> <value>com.tradingapp.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 it passes “validator” then successView, passes to portfolio.htm page
  • 25. Review of the process so far • User goes to this URL: http://tradingapp/logon.htm • Since the URL ends with “.htm”, the tradingapp-servlet.xml file is loaded to determine what controller to use. • The <bean name urlMapping …/> says to refer to the <bean id="logonForm" class="com.tradingapp.LogonFormController"> • Since the LogonFormController extends SimpleFormController we can use the methods defined in the SimpleFormController class to do all kinds of form checking, e.g. validation.
  • 26. What our LogonFormController Looks Like. public class LogonFormController extends SimpleFormController { public ModelAndView onSubmit(Object command) throws ServletException { return new ModelAndView(new RedirectView(getSuccessView())); } } Remember our tradingapp-servler.xml file? <bean id="logonForm" class="com.tradingapp.LogonFormController"> <property name="sessionForm"><value>true</value></property> <property name="commandName"><value>credentials</value></property <property name="commandClass"> <value>com.tradingapp.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, go here
  • 28. Where do I go if there is a validation error in my logon page? tradingapp-servler.xml <bean id="logonForm" class="com.tradingapp.LogonFormController"> <property name="sessionForm"><value>true</value></property> <property name="commandName"><value>credentials</value></property <property name="commandClass"> <value>com.tradingapp.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> <bean id="logonValidator" class="com.devx.tradingapp.web.LogonValidator"/> *** Your LogonFormController will check the validation “first” without writing any additional code because your LogonFormController extends Springs SimpleFormController. Next: The LogonValidator implements Springs Validator interface. On error go back to formView, that is where you started.
  • 29. Logon page with error message Next: code for LogonValidator implements Springs Validator
  • 30. Example code of validator tradingapp-servler.xml <bean id="logonForm" class="com.tradingapp.LogonFormController"> <property name="commandName"><value>credentials</value></property <property name="commandClass"> <value>com.tradingapp.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> <bean id="logonValidator" class="com.devx.tradingapp.web.LogonValidator"/> public class LogonValidator implements Validator { public void validate(Object obj, Errors errors) { Credentials credentials = (Credentials) obj; Command / form backing bean if (credentials.getPassword().equals("guest") == false) { errors.rejectValue("password", "error.login.invalid-pass", null, "Incorrect Password."); } } Next: Command/Form Backing Bean
  • 31. Command/Form Backing Bean is a POJO public class Credentials { private String username; private String password; public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } } Next: Why its called a “command” or “form backing bean”
  • 32. Command/Form Backing Bean is a POJO public class Credentials { logon.htm form private String username; private String password; Username: public String getPassword() { return password; } Password: public void setPassword(String password) { this.password = password; The logon form is “backed” by the } Credentials bean and given a commandName of “credentials” public String getUsername() { defined in out springapp-servlet.xml return username; } file. “credentials” will be our “command object” we will use to public void setUsername(String bind the form to the bean. username) { this.username = username; Next: another look at springapp- } servlet.xml file }
  • 33. springapp-servlet.xml file <bean id="logonForm" class="com.tradingapp.LogonFormController"> <property name="commandName"><value>credentials</value></property <property name="commandClass"> <value>com.tradingapp.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> We use the commandName “credentials” with Spring‟s tag library, to bind the Credentials bean to the logon form. Next: Code that shows logon form binding to commandName
  • 34. logon form binding to commandName using Springs Tag Library <%@ taglib prefix="spring" uri="/spring" %> <html> <head><title>DevX.com Stock-Trading System Logon</title></head> <body> <spring:bind path="credentials.username"> <input type="text" name="username" <spring:bind path="credentials.password"> <input type="password" name="password" /> </body> Spring‟s taglib has bound the bean to the form </html>
  • 35. Where do we go from here. Presentation based on tutorials from: Javid Jamae http://www.devx.com/Java/Article/21665/0/page/1 - Other Spring Presentations & Tutorials http://ckny.eatj.com/wiki/jsp/Wiki?Spring#presentations - Categories from AOP to Security (Acegi) check out Springs: Forum http://forum.springframework.org/index.php