Sie sind auf Seite 1von 13

Developing a Spring 3 Framework MVC application step by step tutorial

Written by admin on July 15, 2012. Posted in Spring 70 Flares Twitter 7 Facebook 46 Google+ 17 Email -- Email to a friend In this article we will learn how to develop a MVC(CRUD Operation) web application from scratch using the Spring 3 Framework. Parts of Spring 3 Framework that will be covered in this article.

Inversion of Control (IoC) Spring MVC via Annoation Data Access with JDBCTemplate

Prerequisite:

Java SDK 1.6 (Used during this tutorial) Eclipse Indigo (Can also be used Later versions) Spring Framework 3.1 HSQLDB v2.2.8 (Any other DB can also be used)

Application to be Developed :
Here in this tutorial we are developing an application where we will Insert(Create) User Details in System. Other CRUD operation look here.

Application Setup :
First create directory for Spring 3 MVC application. Open Eclipse and go to File >> New >> Other. Then select Dynamic Web Project from Select a Wizard screen.

Now click Next. In next(New Dynamic Web Project) screen provide the name of the application as JBTSpringMVC and click Finish.

Note*: We have selected Dynamic Web Module version as 2.5. Now project has been created and structure of the project would be like.

Add all required Jar in WebContent > WEB-INF > lib . Download all Spring Framework JAR from here . Required Jars :

commons-logging-1.1.1.jar hsqldb.jar (Used for HSQLDB) org.springframework.aop-3.1.1.RELEASE.jar org.springframework.asm-3.1.1.RELEASE.jar org.springframework.beans-3.1.1.RELEASE.jar org.springframework.context-3.1.1.RELEASE.jar org.springframework.core-3.1.1.RELEASE.jar org.springframework.expression-3.1.1.RELEASE.jar org.springframework.jdbc-3.1.1.RELEASE.jar org.springframework.transaction-3.1.1.RELEASE.jar org.springframework.web-3.1.1.RELEASE.jar org.springframework.web.servlet-3.1.1.RELEASE.jar

Configure Web.xml in WEB-INF directory:


Now we will modify the web.xml in JBTSpringMVC>>WebContent>>WEB-INF. In web.xml we will define dispatcher servlet(Front End Controller) which will control all request going to web application based on information provided in url-pattern. As we want all request url ending with .do to pass through dispatcher we will provide <url-pattern> as *.do. Changed web.xml will look like below.
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>SpringMVC</display-name> <welcome-file-list>

<welcome-file>welcome.do</welcome-file> </welcome-file-list> <servlet> <servlet-name>dispatcher</servlet-name> <servletclass>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <listener> <listenerclass>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> </web-app>

Now we will create a file named dispatcher-servlet.xml JBTSpringMVC>>WebContent>>WEB-INF. This file contains the view resolver details.

in

Note*: Name of the file (dispatcher-servlet.xml) is not fixed but it depend on the value of <servlet-name> element in web.xml. What ever servlet-name is defined in web.xml you need to add -servlet in it and corresponding .xml will needs to be created in given location(WebContent>>WEB-INF).

Define Dispatcher Servlet XML


In dispatcher servlet we will define viewResolve which help Spring to resolve the exact location of views.
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/springbeans-3.0.xsd"> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean> </beans>

Create Application Context XML


This XML file we will be used for bean definition and AOP related things. This file has already been configured in Spring via contextConfigLocation property in web.xml.
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:jd="http://www.springframework.org/schema/jdbc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/jdbc <!-http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd"> How to include more then one base package -->

<context:annotation-config /> <context:component-scan base-package="com.controller,com.beans" /> <mvc:annotation-driven /> <!-- Below configuration has been added to enable in memory DB HSQLDB <jd:embedded-database id="dataSource1" type="HSQL"> <jd:script location="classpath:schema.sql"/> <jd:script location="classpath:test-data.sql"/> </jd:embedded-database> -->

<bean id="SpringJdbcDao" class="com.dao.SpringJdbcDaoImpl"> <property name="dataSource" ref="dataSource1"/> </bean> <bean id="SpringJdbcService" class="com.service.SpringJdbcServiceImpl"> <property name="springJdbcDao" ref="SpringJdbcDao"/> </bean> </beans>

Look carefully @ the below code in configuration file


<context:annotation-config /> <context:component-scan base-package="com.controller,com.beans" /> <mvc:annotation-driven />

These lines will enable annotation config and let spring know which package to scan for Controller.

Create Bean Class:


Create a package named com.beans and create a bean class VngMem.java. This class will have properties of user and getter ,setter for the same.
package com.beans; public class VngMem { private private private private private private private String name; String dob; String email; String phone; String address; Long pincode; String country;

public VngMem(String name, String dob, String email, String phone, String address, Long pincode, String country) { super(); this.name = name; this.dob = dob; this.email = email; this.phone = phone; this.address = address; this.pincode = pincode; this.country = country; } public VngMem() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDob() { return dob;

} public void setDob(String dob) { this.dob = dob; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public Long getPincode() { return pincode; } public void setPincode(Long pincode) { this.pincode = pincode; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } }

Create Controller Class:


Create a package named com.controller. Then create controller class JBTJdbcController.java in given package. Controller class will look like. To let spring know that this is Controller class we have used @Controller annotation.

To map a URL to method we have used @RequestMapping annotation. Now all the request URL as insertJdbcContact.do will pass throgh insertMemDtls method. Given URL can be fired via two methods GET & POST. To differentiate between two types of request method property @RequestMapping annotation can be used. As use can in below code.
package com.controller; import import import import import import org.springframework.beans.factory.annotation.Autowired; org.springframework.stereotype.Controller; org.springframework.web.bind.annotation.ModelAttribute; org.springframework.web.bind.annotation.RequestMapping; org.springframework.web.bind.annotation.RequestMethod; org.springframework.web.servlet.ModelAndView;

import com.beans.VngMem; @Controller public class JBTJdbcController { @Autowired com.service.SpringJdbcService mfssService; @RequestMapping(value = "/insertJdbcContact", method = RequestMethod.GET) public ModelAndView insertMemDtls() { ModelAndView mav = new ModelAndView("JdbcInsert"); VngMem mfssbean = new VngMem(); mav.addObject("insertUser", mfssbean); mav.addObject("status", "success"); return mav; } @RequestMapping(value = "/insertJdbcContact", method = RequestMethod.POST) public ModelAndView insertContact( @ModelAttribute("insertUser") VngMem vngmem) { ModelAndView mav = new ModelAndView("JdbcInsert"); try { mfssService.insertMfssMemDts(vngmem); } catch (Exception e) { e.printStackTrace(); } mav.addObject("searchResultPost", vngmem); return mav; } }

In Above code we have used ModelAndView which will provide the views to be rendered. We are passing a string value to ModelAndView. Once passed Spring will try to resolve the exact view by viewResolver bean which we have already defined in dispatcher servlet. As string name provided is JdbcInsert Spring will look for jsp named JdbcInsert.jsp in /WEB-INF/jsp/ location.

Create the View


To insert user details we will required a JSP. Which we will create now. Create a JSP named JdbcInsert.jsp in /WEB-INF/jsp/. In jsp we have used form tag from spring framework which will be used to map the property from bean to field in JSP.
<form:form commandName="insertUser" method="POST" action="insertJdbcContact.do" id="userdetailsid" > <fieldset> <legend>User details</legend> <ol> <li> <label for=name>Name</label> <form:input path="name" type="text" placeholder="First and last name" /> </li> <li> <label for=name>Date</label> <form:input path="dob" type="date" required="true" /> </li> <li> <label for=email>Email</label> <form:input path="email" type="text" required="true" /> </li> <li> <label for=phone>Phone</label> <form:input path="phone" type="text" required="true" /> </li> </ol> </fieldset> <fieldset> <legend>User address</legend> <ol> <li> <label for=address>Address</label> <form:input path="address" type="text" required="true" /> </li> <li> <label for=postcode>Post code</label> <form:input path="pincode" type="text" required="true" /> </li> <li>

<label for=country>Country</label> <form:input path="country" type="text" required="true" /> </li> </ol> </fieldset> <fieldset> <button type=submit>Save User Details!</button> </fieldset> </form:form>

Configure Dao Layer


Only Thin left now is DAO layer which actually insert the user details in DB. We are using JdbcTemplate for DB updation JdbcTemplate will require Datasource which we have already configured in applicationContext.xml.

package com.dao; import import import import import import java.sql.ResultSet; java.sql.SQLException; java.util.List; javax.sql.DataSource; org.springframework.jdbc.core.JdbcTemplate; org.springframework.jdbc.core.RowMapper;

import com.beans.VngMem; public class SpringJdbcDaoImpl implements SpringJdbcDao { private JdbcTemplate jdbcTemplate; public void setDataSource(DataSource dataSource) { this.jdbcTemplate = new JdbcTemplate(dataSource); } @Override public void insertMfssMemDts(VngMem contact) { String query = "insert into vng_mem (NAME,DOB,EMAIL,PHONE,ADDRESS,PINCODE,COUNTRY)" + " VALUES (?,?,?,?,?,?,?)"; jdbcTemplate.update( query, new Object[] { contact.getName(), contact.getDob(), contact.getEmail(), contact.getPhone(), contact.getAddress(), contact.getPincode(),

contact.getCountry() }); } }

**Update Here is the code for SpringJdbcService.java


package com.dao; package com.service; import com.beans.VngMem; public interface SpringJdbcService { VngMem searchMemDts(VngMem vngmem); void insertMemDts(VngMem MemDtlsbean); }

and SpringJdbcServiceImpl.java
package com.service; import org.springframework.jdbc.BadSqlGrammarException; import com.beans.VngMem; import com.dao.SpringJdbcDaoImpl; public class SpringJdbcServiceImpl implements SpringJdbcService { SpringJdbcDaoImpl springJdbcDao; public SpringJdbcDaoImpl getSpringJdbcDao() { return springJdbcDao; } public void setSpringJdbcDao(SpringJdbcDaoImpl springJdbcDao) { this.springJdbcDao = springJdbcDao; } public VngMem searchMemDts(VngMem vngmem) { try { return springJdbcDao.searchMemDts(vngmem); } catch (BadSqlGrammarException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return null;

} public void insertMemDts(VngMem MemDtlsbean) { springJdbcDao.insertMemDts(MemDtlsbean); } }