Developing a Spring 3 Framework MVC application step by step tutorial

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>
		<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>*.do</url-pattern>
	</servlet-mapping>
	<listener>
		<listener-class>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” in JBTSpringMVC>>WebContent>>WEB-INF. This file contains the view resolver details.

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/spring-beans-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 String name;
	private String dob;
	private String email;
	private String phone;
	private String address;
	private Long pincode;
	private 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;

/*
 * Code By Javabeginnerstutorial.com
 */

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.beans.VngMem;

@Controller
public class JBTJdbcController {

	@Autowired
	com.service.SpringJdbcService Service;

	@RequestMapping(value = "/searchJdbcContact", method = RequestMethod.GET)
	public ModelAndView searchContact() {
		ModelAndView mav = new ModelAndView("JdbcSearch");
		VngMem bean = new VngMem();

		mav.addObject("searchUserGet", bean);
		return mav;
	}

	@RequestMapping(value = "/searchJdbcContact", method = RequestMethod.POST)
	public ModelAndView searchContact(
			@ModelAttribute("searchlist2") VngMem vngmem) {
		ModelAndView mav = new ModelAndView("JdbcSearchResult");

		VngMem bean1 = null;
		try {
			bean1 = Service.searchMemDts(vngmem);
		} catch (Exception e) {
		}

		mav.addObject("searchResultPost", bean1);
		return mav;
	}

	@RequestMapping(value = "/insertJdbcContact", method = RequestMethod.GET)
	public ModelAndView insertMemDtls() {
		ModelAndView mav = new ModelAndView("JdbcInsert");

		VngMem bean = new VngMem();
		mav.addObject("insertUser", bean);
		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 {
			Service.insertMemDts(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 java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import 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 insertMemDts(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() });

	}

	// @Override
	public VngMem searchMemDts(VngMem vngmem) {

		String queryinitial = "select * from vng_mem where NAME ='"
				+ vngmem.getName() + "'";

		System.out.println("query formed with all the argument - "
				+ queryinitial);

		RowMapper rm = null;// = new RowMapper() ;
		List listcontacct = jdbcTemplate.query(queryinitial,
				new RowMapper() {
					public Object mapRow(ResultSet resultSet, int rowNum)
							throws SQLException {
						return new VngMem(resultSet.getString("name"),
								resultSet.getString("dob"), resultSet
										.getString("email"), resultSet
										.getString("phone"), resultSet
										.getString("address"), resultSet
										.getLong("PINCODE"), resultSet
										.getString("country"));
					}
				});

		if (listcontacct.size() > 0)
			return listcontacct.get(0);

		return new VngMem();
	}

}

 

**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);

	}

}

Hope it now help every one. 🙂

Everything is now setup. Now DAO layer can insert user details in DB. But we have used HSQLDB for in project.  If you want to know how to configure HSQLDB please visit here. After configure HSQLDB start server and click link http://localhost:8080/JBTSpringMVC/insertJdbcContact.do.

Application Source Code

A Demo application has been deployed on appshot.com @ http://javabeginnerstutorial.appspot.com/insertJdbcContact.do

Check this application to know how it works. Till now we have covered only ‘C‘ of CRUD operation rest operation will be cvered in next Articles.

Note*:: This application till now doesn’t have any kind of validation. Which we will explore in later article.

Download Project from below link
 ……

729 Comments Developing a Spring 3 Framework MVC application step by step tutorial

  1. Ashish

    Can you share the code base for this wonderful demonstration ?

    Please create a download link for codebase. As everyone requires it.

    Reply
  2. buying a fitbit

    This is a very good tip particularly to those new to the blogosphere.
    Brief but very accurate information… Thank you for sharing this one.
    A must read post!

    Reply
  3. buying a fitbit

    This is a very good tip particularly to those new to the blogosphere.
    Brief but very accurate information… Thank you for sharing this one.
    A must read post!

    Reply
  4. LavakumarReddy

    Hi Iam LavakumarReddy Velidandla,I Got Little bit Hope,That I can Develop my Own Web Applications By using Spring,After reading this.It helped lot for me.

    Reply

Leave A Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.