This tutorial Spring MVC and JDBC CRUD example shows how MVC(Model, View, Controller) works in Spring 4.x. In this tutorial you will also find how JDBC works with Spring MVC. We will also see how annotation like @Autowired works in Spring MVC and JDBC CRUD example. You will also see how datasource is configured in Spring. This example shows how to integrate Spring 4 with Maven 3. You may also read Spring MVC and Spring JDBC Example

Spring MVC and JDBC CRUD with zero XML

For Spring MVC and JDBC CRUD example, we will create maven based web project in Eclipse.

If you already have an idea on how to create a maven project in Eclipse will be great otherwise I will tell you here how to create a maven project in Eclipse.

Prerequisites

The following configurations are required in order to run the application

Eclipse Kepler
JDK 1.8
Tomcat 8
Have maven 3 installed and configured
Spring 4 dependencies in pom.xml

Now we will see the below steps how to create a maven based project in Eclipse.
Step 1. Create a maven based web project in Eclipse

Go to File -> New -> Other. On popup window under Maven select Maven Project. Then click on Next. Select the workspace location – either default or browse the location. Click on Next. Now in next window select the row as highlighted from the below list of archtypes and click on Next button.

maven-arctype-webapp

Now enter the required fields (Group Id, Artifact Id) as shown below

Group Id : com.roytuts
Artifact Id : spring-mvc-jdbc

The created project looks like below image.

spring mvc and jdbc

Step 2. Modify the pom.xml file as shown below. As it is a Spring mvc project so we have added Spring web dependency. We have added MySQL dependency as we are working with mysql database. We have added jstl and jsp dependencies for jsp pages.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

	<modelVersion>4.0.0</modelVersion>
	<groupId>com.roytuts</groupId>
	<artifactId>spring-mvc-jdbc</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>spring-mvc-jdbc Maven Webapp</name>
	<url>http://maven.apache.org</url>

	<properties>
		<java.version>1.8</java.version>
		<spring.version>4.1.6.RELEASE</spring.version>
		<mysqlconnector.version>5.1.34</mysqlconnector.version>
	</properties>

	<dependencies>
		<!-- Spring -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>
		
		<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<!-- jstl -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>

		<!-- mysql java connector -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>${mysqlconnector.version}</version>
		</dependency>
	</dependencies>

	<build>
		<finalName>spring-mvc-jdbc</finalName>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>${java.version}</source>
					<target>${java.version}</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

Step 3. If you see JRE System Library[J2SE-1.5] then change the version by below process.

Do right-click on the project and go to Build -> Configure build path, under Libraries tab click on JRE System Library[J2SE-1.5], click on Edit button and select the appropriate jdk 1.8 from the next window. Click on Finish then Ok.

Change also the Compiler compliance level as 1.8 from Java -> Compiler.

Step 4. Now when the build process finished in Eclipse then modify the web.xml file with below source code.

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">

	<!-- dispatcher servlet acts as a front controller for each request/response -->
	<servlet>
		<servlet-name>spring-mvc-jdbc</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<!-- load Spring controllers while dispatcher servlet loads -->
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:controllers.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<!-- map URL suffix as .html -->
	<servlet-mapping>
		<servlet-name>spring-mvc-jdbc</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

</web-app>

Step 5. Create spring-config.xml file under src/main/resources directory with the below source code. We have declared the annotation support configuration for both transaction and other stereotype like @Service, @Repository etc. We have defined beans for data source, transaction, JDBC template and other custom beans in the below Spring config.

<?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:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:task="http://www.springframework.org/schema/task"
	xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd">

	<!-- Support annotation -->
	<context:annotation-config />

	<!-- support annotation transaction -->
	<tx:annotation-driven transaction-manager="txManager" />

	<!-- declare datasource -->
	<bean id="dataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<property name="url" value="jdbc:mysql://localhost:3306/cdcol" />
		<property name="username" value="root" />
		<property name="password" value="" />
	</bean>

	<bean id="txManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource" />
	</bean>

	<!-- spring jdbc template -->
	<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
		<property name="dataSource" ref="dataSource"></property>
	</bean>

	<!-- service -->
	<bean id="userDetailsService" class="com.roytuts.spring.service.impl.UserDetailsServiceImpl" />

	<!-- dao -->
	<bean id="userDetailsDao" class="com.roytuts.spring.dao.impl.UserDetailsDaoImpl" />

</beans>

Step 6. Create controllers.xml file under classpath directory src/main/resources. Through this config file we import other Spring config files, we scan all the Spring controller classes and also we define view resolver in order to use jsp pages as presentation layer.

<?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:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

	<import resource="classpath:spring-config.xml" />

	<!-- Scan the package where Spring Controllers are placed -->
	<context:component-scan base-package="com.roytuts.spring.controllers" />

	<!-- Resolves logical String-based view names to actual View types -->
	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="viewClass"
			value="org.springframework.web.servlet.view.JstlView" />
		<!-- Where pages are kept -->
		<property name="prefix" value="/pages/" />
		<!-- What is the page extension -->
		<property name="suffix" value=".jsp" />
	</bean>

</beans>

Step 7. Create a directory called pages under webapp directory for putting created jsp views. Notice how we have configured this view directory in view resolver in the above spring config.

Step 8. Create MySQL table user_details in database cdcol to store user information.

USE `cdcol`;

/*Table structure for table `user_details` */

DROP TABLE IF EXISTS `user_details`;

CREATE TABLE `user_details` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `first_name` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
  `last_name` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
  `email` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  `dob` varchar(16) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Step 9. Dump some data into the table in order to test the application.

/*Data for the table `user_details` */

insert  into `user_details`(`id`,`first_name`,`last_name`,`email`,`dob`) values (7,'Soumitra','Roy','contact@roytuts.com','30-08-1986'),(8,'Souvik','Sanyal','souvik.sanyal@email.com','30-09-1991');

Step 10. Now create POJO class and mapper class which will map Java object to database table user_details.

package com.roytuts.model;

public class UserDetails {

	private int id;
	private String firstName;
	private String lastName;
	private String email;
	private String dob;

	public UserDetails() {
	}

	public UserDetails(int id, String firstName, String lastName, String email, String dob) {
		this.id = id;
		this.firstName = firstName;
		this.lastName = lastName;
		this.email = email;
		this.dob = dob;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getDob() {
		return dob;
	}

	public void setDob(String dob) {
		this.dob = dob;
	}

}

Mapper class implements Spring’s parameterized Rowmapper to provide mapping between database table and Java class.

package com.roytuts.model.mapper;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.jdbc.core.RowMapper;

import com.roytuts.model.UserDetails;

public class UserDetailsRowMapper implements RowMapper<UserDetails> {

	public UserDetails mapRow(ResultSet rs, int row) throws SQLException {
		UserDetails userDetails = new UserDetails();
		userDetails.setId(rs.getInt("id"));
		userDetails.setFirstName(rs.getString("first_name"));
		userDetails.setLastName(rs.getString("last_name"));
		userDetails.setEmail(rs.getString("email"));
		userDetails.setDob(rs.getString("dob"));
		return userDetails;
	}

}

Step 11. Create DAO interface for querying database table. This interface is implemented by several client classes in order to provide their own implementations. It is always recommended to write code to interface rather than to class to provide loose coupling between components through dependency injection.

package com.roytuts.spring.dao;

import java.util.List;

import com.roytuts.model.UserDetails;

public interface UserDetailsDao {

	public UserDetails getUserDetails(int id);

	public List<UserDetails> getAllUserDetails();

	public int addUserDetails(UserDetails userDetails);

	public int updateUserDetails(UserDetails userDetails);

	public int deleteUserDetails(int id);

}

Step 12. Create the corresponding DAO implementation class. Here in the below class we have applied transaction while modifying or writing data to database otherwise data may not be in consistent state in the database. You may also apply transaction while reading data.

package com.roytuts.spring.dao.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import org.springframework.transaction.annotation.Transactional;

import com.roytuts.model.UserDetails;
import com.roytuts.model.mapper.UserDetailsRowMapper;
import com.roytuts.spring.dao.UserDetailsDao;

public class UserDetailsDaoImpl implements UserDetailsDao {

	@Autowired
	private JdbcTemplate jdbcTemplate;
        
        @Transactional
	public UserDetails getUserDetails(int id) {
		UserDetails userDetails = (UserDetails) jdbcTemplate.queryForObject("select * from user_details where id = ?",
				new Object[] { id }, new UserDetailsRowMapper());
		return userDetails;
	}

        @Transactional
	public List<UserDetails> getAllUserDetails() {
		List<UserDetails> userDetails = (List<UserDetails>) jdbcTemplate.query("select * from user_details",
				new UserDetailsRowMapper());
		return userDetails;
	}

	@Transactional
	public int addUserDetails(UserDetails userDetails) {
		SimpleJdbcInsert simpleJdbcInsert = new SimpleJdbcInsert(jdbcTemplate);
		simpleJdbcInsert.withTableName("user_details").usingGeneratedKeyColumns("id");
		Map<String, Object> parameters = new HashMap<String, Object>(4);
		parameters.put("first_name", userDetails.getFirstName());
		parameters.put("last_name", userDetails.getLastName());
		parameters.put("email", userDetails.getEmail());
		parameters.put("dob", userDetails.getDob());
		Number insertedId = simpleJdbcInsert.executeAndReturnKey(parameters);
		return insertedId.intValue();
	}

	@Transactional
	public int updateUserDetails(UserDetails userDetails) {
		String sql = "update user_details set first_name = ?, last_name = ?, email = ?, dob = ? where id = ?";
		int resp = jdbcTemplate.update(sql, new Object[] { userDetails.getFirstName(), userDetails.getLastName(),
				userDetails.getEmail(), userDetails.getDob(), userDetails.getId() });
		return resp;

	}

	@Transactional
	public int deleteUserDetails(int id) {
		int resp = jdbcTemplate.update("delete from user_details where id = ?", id);
		return resp;
	}

}

Step 13. Create the service interface for processing logic or business logic.

package com.roytuts.spring.service;

import java.util.List;

import com.roytuts.model.UserDetails;

public interface UserDetailsService {

	public UserDetails getUserDetails(int id);

	public List<UserDetails> getAllUserDetails();

	public int addUserDetails(UserDetails userDetails);

	public int updateUserDetails(UserDetails userDetails);

	public int deleteUserDetails(int id);

}

Step 14. Create the corresponding service implementation class. This service class communicates with DAO layer and gets data and finally applies business processing logic on those data and sends to the controller layer which then pass to the presentation layer for displaying on view.

package com.roytuts.spring.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.roytuts.model.UserDetails;
import com.roytuts.spring.dao.UserDetailsDao;
import com.roytuts.spring.service.UserDetailsService;

public class UserDetailsServiceImpl implements UserDetailsService {

	@Autowired
	private UserDetailsDao userDetailsDao;

	public UserDetails getUserDetails(int id) {
		return userDetailsDao.getUserDetails(id);
	}

	public List<UserDetails> getAllUserDetails() {
		return userDetailsDao.getAllUserDetails();
	}

	@Override
	public int addUserDetails(UserDetails userDetails) {
		return userDetailsDao.addUserDetails(userDetails);
	}

	@Override
	public int updateUserDetails(UserDetails userDetails) {
		return userDetailsDao.updateUserDetails(userDetails);
	}

	@Override
	public int deleteUserDetails(int id) {
		return userDetailsDao.deleteUserDetails(id);
	}

	public UserDetailsDao getUserDetailsDao() {
		return userDetailsDao;
	}

}

Step 15. Create Spring controller class which will handle user request and response.

package com.roytuts.spring.controllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.roytuts.model.UserDetails;
import com.roytuts.spring.service.UserDetailsService;

@Controller
@RequestMapping("/")
public class UserDetailsController {

	@Autowired
	private UserDetailsService userDetailsService;

	@RequestMapping(value = "user/{id}", method = RequestMethod.GET)
	public String getUserDetails(@PathVariable int id, ModelMap userModel) {
		userModel.addAttribute("userDetails", userDetailsService.getUserDetails(id));
		return "user";
	}

	@RequestMapping(value = "users", method = RequestMethod.GET)
	public String getUsersDetails(ModelMap userModel) {
		userModel.addAttribute("userDetails", userDetailsService.getAllUserDetails());
		return "users";
	}

	@RequestMapping(value = "addUser")
	public String addPage() {
		return "add";
	}

	@RequestMapping(value = "add/user", method = RequestMethod.POST)
	public String addUser(@RequestParam(value = "fname", required = true) String fname,
			@RequestParam(value = "lname", required = true) String lname,
			@RequestParam(value = "email", required = true) String email,
			@RequestParam(value = "dob", required = true) String dob, ModelMap userModel) {
		UserDetails userDetails = new UserDetails();
		userDetails.setFirstName(fname);
		userDetails.setLastName(lname);
		userDetails.setEmail(email);
		userDetails.setDob(dob);
		int resp = userDetailsService.addUserDetails(userDetails);
		if (resp > 0) {
			userModel.addAttribute("msg", "User with id : " + resp + " added successfully.");
			userModel.addAttribute("userDetails", userDetailsService.getAllUserDetails());
			return "users";
		} else {
			userModel.addAttribute("msg", "User addition failed.");
			return "add";
		}
	}

	@RequestMapping(value = "delete/user/{id}", method = RequestMethod.GET)
	public String deleteUser(@PathVariable("id") int id, ModelMap userModel) {
		int resp = userDetailsService.deleteUserDetails(id);
		userModel.addAttribute("userDetails", userDetailsService.getAllUserDetails());
		if (resp > 0) {
			userModel.addAttribute("msg", "User with id : " + id + " deleted successfully.");
		} else {
			userModel.addAttribute("msg", "User with id : " + id + " deletion failed.");
		}
		return "users";
	}

	@RequestMapping(value = "update/user/{id}", method = RequestMethod.GET)
	public String updatePage(@PathVariable("id") int id, ModelMap userModel) {
		userModel.addAttribute("id", id);
		userModel.addAttribute("userDetails", userDetailsService.getUserDetails(id));
		return "update";
	}

	@RequestMapping(value = "update/user", method = RequestMethod.POST)
	public String updateUser(@RequestParam int id, @RequestParam(value = "fname", required = true) String fname,
			@RequestParam(value = "lname", required = true) String lname, @RequestParam("email") String email,
			@RequestParam("dob") String dob, ModelMap userModel) {
		UserDetails userDetails = new UserDetails();
		userDetails.setId(id);
		userDetails.setFirstName(fname);
		userDetails.setLastName(lname);
		userDetails.setEmail(email);
		userDetails.setDob(dob);
		int resp = userDetailsService.updateUserDetails(userDetails);
		userModel.addAttribute("id", id);
		if (resp > 0) {
			userModel.addAttribute("msg", "User with id : " + id + " updated successfully.");
			userModel.addAttribute("userDetails", userDetailsService.getAllUserDetails());
			return "users";
		} else {
			userModel.addAttribute("msg", "User with id : " + id + " updation failed.");
			userModel.addAttribute("userDetails", userDetailsService.getUserDetails(id));
			return "update";
		}
	}

}

Step 16. Now create user.jsp file under webapp/pages directory for displaying single user details.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<html>
<title>Spring MVC and JDBC CRUD Example</title>
<body>
	<h2>Spring MVC and JDBC CRUD Example</h2>
	Id : ${userDetails.id}
	<br /> First Name : ${userDetails.firstName}
	<br /> Last Name : ${userDetails.lastName}
	<br /> Email : ${userDetails.email}
	<br /> DOB : ${userDetails.dob}
</body>
</html>

Step 17. Create users.jsp file under webapp/pages directory for displaying all users details

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<title>Spring MVC and JDBC CRUD Example</title>
<body>
	<h2>Spring MVC and JDBC CRUD Example</h2>
	<c:if test="${not empty msg}">
        ${msg}
    </c:if>
	<c:choose>
		<c:when test="${userDetails != null}">
			<h3>List of Users</h3>
			<table cellpadding="5" cellspacing="5">
				<thead>
					<tr>
						<th>ID</th>
						<th>First Name</th>
						<th>Last Name</th>
						<th>Email</th>
						<th>DOB</th>
						<th>Actions</th>
					</tr>
				</thead>
				<tbody>
					<c:forEach var="user" items="${userDetails}">
						<tr>
							<td>${user.id}</td>
							<td>${user.firstName}</td>
							<td>${user.lastName}</td>
							<td>${user.email}</td>
							<td>${user.dob}</td>
							<td><a
								href="<%=request.getContextPath()%>/update/user/${user.id}">Update</a>
								&nbsp; <a
								href="<%=request.getContextPath()%>/delete/user/${user.id}"
								onclick="return confirm('Do you really want to delete?')">Delete</a></td>
						</tr>
					</c:forEach>
				</tbody>
			</table>
		</c:when>
		<c:otherwise>
        No User found in the DB!
        </c:otherwise>
	</c:choose>
</body>
</html>

Step 18. Create add.jsp file under webapp/pages directory for adding new user.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<title>Spring MVC and JDBC CRUD Example</title>
<body>
	<h2>Spring MVC and JDBC CRUD Example</h2>
	<c:if test="${not empty msg}">
        ${msg}
    </c:if>
	<h3>Add User</h3>
	<form method="POST" name="add_user"
		action="<%=request.getContextPath()%>/add/user">
		Name: <input name="fname" value="${firstName}" type="text" /> <br />
		<br /> Last Name: <input name="lname" value="${lastName}" type="text" />
		<br /> <br /> Email: <input name="email" value="${email}"
			type="text" /><br /> <br /> DOB: <input name="dob" value="${dob}"
			type="text" /><br /> <br /> <input value="Add User" type="submit" />
	</form>
</body>
</html>

Step 19. Create update.jsp file under webapp/pages directory for updating new user.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<title>Spring MVC and JDBC CRUD Example</title>
<body>
	<h2>Spring MVC and JDBC CRUD Example</h2>
	<c:if test="${not empty msg}">
        ${msg}
    </c:if>
	<h3>Update User</h3>
	<form method="POST" name="update_user"
		action="<%=request.getContextPath()%>/update/user">
		<input hidden="hidden" name="id" value="${id}" type="text" /> First
		Name: <input name="fname" value="${userDetails.firstName}" type="text" />
		<br />
		<br /> Last Name: <input name="lname" value="${userDetails.lastName}"
			type="text" /> <br /> <br /> Email: <input name="email"
			value="${userDetails.email}" type="text" /><br />
		<br /> DOB: <input name="dob" value="${userDetails.dob}" type="text" /><br />
		<br /> <input value="Update User" type="submit" />
	</form>
</body>
</html>

Now we have finished writing code for Spring MVC and JDBC CRUD example. So let’s test the application.

Step 20. Now run the application on Tomcat server 8 and when the application successfully deployed onto the server, please hit the URL http://localhost:8080/spring-mvc-jdbc/users , you will below output in the browser.

spring mvc and jdbc crud example

When you hit the URL http://localhost:8080/spring-mvc-jdbc/user in the browser, you will see the below output.

spring mvc and jdbc crud example

When you click on the update link on page http://localhost:8080/spring-mvc-jdbc/users in the browser, you will see the below output

spring mvc and jdbc crud example

When you click on the delete link on page http://localhost:8080/spring-mvc-jdbc/users in the browser, you will see the below output

spring mvc and jdbc crud example

When you hit the URL http://localhost:8080/spring-mvc-jdbc/addUser in the browser, you will see the below output

spring mvc and jdbc crud example

After addition of user the page navigates automatically to the all users page

spring mvc and jdbc crud

The newly added user information is inserted into database

spring mvc and jdbc crud example

Hope you will be able to apply similar concept to your own project after completing this Spring MVC and JDBC CRUD example.

Thanks for reading.

Tags:

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on Roy Tutorials | TwitterFacebook Google PlusLinkedin | Reddit

7 thoughts on “Spring MVC and JDBC CRUD Example

  1. What is this error?
    SEVERE: Servlet.service() for servlet [spring-mvc-jdbc] in context with path [/spring-mvc-jdbc] threw exception [Request processing failed; nested exception is org.springframework.jdbc.UncategorizedSQLException: StatementCallback; uncategorized SQLException for SQL [select * from user_details]; SQL state [S0022]; error code [0]; Column ‘first_name’ not found.; nested exception is java.sql.SQLException: Column ‘first_name’ not found.] with root cause
    java.sql.SQLException: Column ‘first_name’ not found.

  2. what is the need of the row mapper class in the project if we not write the row mapper class can any other alternative way to configure the crud operation using springjdbc. can u plz clarified me.
    can u mention some of spinet of code
    thanks a lot….

Leave a Reply

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