Vous êtes sur la page 1sur 12

Spring MVC with JdbcTemplate Example

Last Updated on 15 September 2016 | Print Email


[SALE NOW] Top Java Programming Courses (Coupon Code:
APR10103)
Spring makes it easy to work with JDBC through the use of JdbcTemplate and related classes
in the org.springframework.jdbc.core and related packages. For an

introductory tutorial for the basics of JdbcTemplate, see: Spring JDBC Template Simple
Example. This tutorial goes further by demonstrating how to integrate JdbcTemplate in a
Spring MVC application. The sample application in this tutorial manages a contact list that
looks like this:

The sample application is developed using the following pieces of software/technologies:

Java 7

Eclipse Kepler

Spring framework 4.0

JSTL 1.2

MySQL Database 5.5


Maven 3

1. Creating MySQL database


Execute the following MySQL script to create a database named contactdb and a table
named contact:
1
create database contactdb;
2
3 CREATE TABLE `contact` (
4 `contact_id` int(11) NOT NULL AUTO_INCREMENT,
5 `name` varchar(45) NOT NULL,
6 `email` varchar(45) NOT NULL,
7 `address` varchar(45) NOT NULL,
`telephone` varchar(45) NOT NULL,
8 PRIMARY KEY (`contact_id`)
9 ) ENGINE=InnoDB AUTO_INCREMENT=25 DEFAULT CHARSET=utf8
10

2. Creating Maven Project in Eclipse


Its recommended to use spring-mvc-archetype to create the project (See: Creating a Spring
MVC project using Maven and Eclipse in one minute). Heres the projects final structure:

The following XML section in pom.xmlfile is for adding dependencies configuration to the
project:
1 <properties>
<java.version>1.7</java.version>
2 <spring.version>4.0.3.RELEASE</spring.version>
3 <cglib.version>2.2.2</cglib.version>
4 </properties>
5
6 <dependencies>
7 <!-- Spring core & mvc -->
<dependency>
8 <groupId>org.springframework</groupId>
9 <artifactId>spring-context</artifactId>
10 <version>${spring.version}</version>
11 </dependency>
12
13 <dependency>
<groupId>org.springframework</groupId>
14 <artifactId>spring-webmvc</artifactId>
15 <version>${spring.version}</version>
16 </dependency>
17 <dependency>
<groupId>org.springframework</groupId>
18 <artifactId>spring-orm</artifactId>
19 <version>${spring.version}</version>
20 <type>jar</type>
21 <scope>compile</scope>
22 </dependency>
23
<!-- CGLib for @Configuration -->
24 <dependency>
25 <groupId>cglib</groupId>
26 <artifactId>cglib-nodep</artifactId>
27 <version>${cglib.version}</version>
28 <scope>runtime</scope>
</dependency>
29
30
31 <!-- Servlet Spec -->
32 <dependency>
33 <groupId>javax.servlet</groupId>
34 <artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
35 <scope>provided</scope>
36 </dependency>
37 <dependency>
38 <groupId>javax.servlet.jsp</groupId>
39 <artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
40 <scope>provided</scope>
41 </dependency>
42 <dependency>
43 <groupId>jstl</groupId>
<artifactId>jstl</artifactId>
44
<version>1.2</version>
45 </dependency>
46
47 </dependencies>
48
49
50
51
52
53
54
55
56

3. Coding Model Class


The model class - Contact.java - is pretty simple:
1
2 package net.codejava.spring.model;
3
4 public class Contact {
5 private int id;
6 private String name;
private String email;
7 private String address;
8 private String telephone;
9
10 public Contact() {
11 }
12
13 public Contact(String name, String email, String address, String telephone) {
this.name = name;
14 this.email = email;
15 this.address = address;
16 this.telephone = telephone;
17 }
18
// getters and setters
19
}
20
21
This class simply maps a row in the table contact to a plain old Java object (POJO) - Contact.

4. Coding DAO Classes


The ContactDAO interface defines methods for performing CRUD operations on
the contact table:
1 package net.codejava.spring.dao;
2
import java.util.List;
3
4 import net.codejava.spring.model.Contact;
5
6
7
8 /**
* Defines DAO operations for the contact model.
9 * @author www.codejava.net
10 *
11 */
12 public interface ContactDAO {
13
14 public void saveOrUpdate(Contact contact);
15
public void delete(int contactId);
16
17 public Contact get(int contactId);
18
19 public List<Contact> list();
20 }
21

And here is an implementation - ContactDAOImpl.java:


1 package net.codejava.spring.dao;
2
import java.sql.ResultSet;
3
import java.sql.SQLException;
4 import java.util.List;
5
6 import javax.sql.DataSource;
7
8 import net.codejava.spring.model.Contact;
9
10 import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
11 import org.springframework.jdbc.core.ResultSetExtractor;
12 import org.springframework.jdbc.core.RowMapper;
13
14 /**
15 * An implementation of the ContactDAO interface.
16 * @author www.codejava.net
*
17 */
18 public class ContactDAOImpl implements ContactDAO {
19
20 private JdbcTemplate jdbcTemplate;
21
22 public ContactDAOImpl(DataSource dataSource) {
jdbcTemplate = new JdbcTemplate(dataSource);
23 }
24
25
26
27
28
29 @Override
public void saveOrUpdate(Contact contact) {
30
// implementation details goes here...
31 }
32
33 @Override
34 public void delete(int contactId) {
35 // implementation details goes here...
}
36
37 @Override
38 public List<Contact> list() {
39 // implementation details goes here...
40 }
41
42 @Override
public Contact get(int contactId) {
43 // implementation details goes here...
44 }
45
46 }
47
48
49
Pay attention to the beginning section that declares a JdbcTemplate and
a DataSource object is injected via the constructor:
1 private JdbcTemplate jdbcTemplate;
2
3 public ContactDAOImpl(DataSource dataSource) {
4 jdbcTemplate = new JdbcTemplate(dataSource);
}
5
Now, lets look at implementation details of each method.
Insert or update a new contact:
1 public void saveOrUpdate(Contact contact) {
if (contact.getId() > 0) {
2
// update
3 String sql = "UPDATE contact SET name=?, email=?, address=?, "
4 + "telephone=? WHERE contact_id=?";
5 jdbcTemplate.update(sql, contact.getName(), contact.getEmail(),
6 contact.getAddress(), contact.getTelephone(), contact.getId());
} else {
7 // insert
8 String sql = "INSERT INTO contact (name, email, address, telephone)"
9 + " VALUES (?, ?, ?, ?)";
10 jdbcTemplate.update(sql, contact.getName(), contact.getEmail(),
11 contact.getAddress(), contact.getTelephone());
}
12
13 }
14
15
16
Note that if the contact object having ID greater than zero, update it; otherwise that is an insert.
Delete a contact:
1 public void delete(int contactId) {
2 String sql = "DELETE FROM contact WHERE contact_id=?";
3 jdbcTemplate.update(sql, contactId);
}
4
List all contact:
1
2 public List<Contact> list() {
3 String sql = "SELECT * FROM contact";
4 List<Contact> listContact = jdbcTemplate.query(sql, new RowMapper<Contact>() {
5
6 @Override
public Contact mapRow(ResultSet rs, int rowNum) throws SQLException {
7 Contact aContact = new Contact();
8
9 aContact.setId(rs.getInt("contact_id"));
10 aContact.setName(rs.getString("name"));
11 aContact.setEmail(rs.getString("email"));
aContact.setAddress(rs.getString("address"));
12
aContact.setTelephone(rs.getString("telephone"));
13
14 return aContact;
15 }
16
17 });
18
19 return listContact;
}
20
21
Notice the use of RowMapper to map a row in the result set to a POJO object.
Get a particular contact:
1 public Contact get(int contactId) {
String sql = "SELECT * FROM contact WHERE contact_id=" + contactId;
2 return jdbcTemplate.query(sql, new ResultSetExtractor<Contact>() {
3
4 @Override
5 public Contact extractData(ResultSet rs) throws SQLException,
6 DataAccessException {
7 if (rs.next()) {
Contact contact = new Contact();
8 contact.setId(rs.getInt("contact_id"));
9 contact.setName(rs.getString("name"));
10 contact.setEmail(rs.getString("email"));
11 contact.setAddress(rs.getString("address"));
12 contact.setTelephone(rs.getString("telephone"));
return contact;
13
14
15 }
16
17 return null;
18 }
19
20 });
}
21
22
Notice the use of ResultSetExtractor to extract a single row as a POJO.

5. Coding MVC Configuration


Java-based classes and annotations are used to configure this Spring MVC application. Heres
code of the MvcConfiguration class:
1 package net.codejava.spring.config;
2
import javax.sql.DataSource;
3
4
import net.codejava.spring.dao.ContactDAO;
5 import net.codejava.spring.dao.ContactDAOImpl;
6
7 import org.springframework.context.annotation.Bean;
8 import org.springframework.context.annotation.ComponentScan;
9 import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
10 import org.springframework.web.servlet.ViewResolver;
11 import org.springframework.web.servlet.config.annotation.EnableWebMvc;
12 import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
13 import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
14 import org.springframework.web.servlet.view.InternalResourceViewResolver;
15
@Configuration
16 @ComponentScan(basePackages="net.codejava.spring")
17 @EnableWebMvc
18 public class MvcConfiguration extends WebMvcConfigurerAdapter{
19
20 @Bean
public ViewResolver getViewResolver(){
21 InternalResourceViewResolver resolver = new InternalResourceViewResolver();
22 resolver.setPrefix("/WEB-INF/views/");
23 resolver.setSuffix(".jsp");
24 return resolver;
25 }
26
@Override
27 public void addResourceHandlers(ResourceHandlerRegistry registry) {
28 registry.addResourceHandler("/resources/**").addResourceLocations("/resource
29 }
30
31 @Bean
32
33
34
35 public DataSource getDataSource() {
36 DriverManagerDataSource dataSource = new DriverManagerDataSource();
37 dataSource.setDriverClassName("com.mysql.jdbc.Driver");
38 dataSource.setUrl("jdbc:mysql://localhost:3306/contactdb");
39 dataSource.setUsername("root");
dataSource.setPassword("P@ssw0rd");
40
41 return dataSource;
42 }
43
44 @Bean
45 public ContactDAO getContactDAO() {
46 return new ContactDAOImpl(getDataSource());
}
47 }
48
49
50
51
Notice the getDataSource() method returns a configured DataSource bean. You may have
to change the database URL, username and password according to your environments.
The getContactDAO() method returns an implementation of the ContactDAO interface, which
is the ContactDAOImplclass. This bean will be injected to the controller class, which is
described below.

6. Coding Controller Class


Skeleton of the HomeController class:
1 public class HomeController {
2
3 @Autowired
4 private ContactDAO contactDAO;
5
6 // handler methods go here...
}
7
Notice we use the @Autowired annotation to let Spring inject an instance of
the ContactDAOimplementation into this controller automatically. Each handler method uses
this contactDAO object to perform necessary CRUD operations. Lets see implementation
details of each method.
Handler method for listing all contacts (also served as home page):
1 @RequestMapping(value="/")
2 public ModelAndView listContact(ModelAndView model) throws IOException{
List<Contact> listContact = contactDAO.list();
3 model.addObject("listContact", listContact);
4 model.setViewName("home");
5
6
return model;
7 }
8

Handler method for displaying new contact form:


1 @RequestMapping(value = "/newContact", method = RequestMethod.GET)
2 public ModelAndView newContact(ModelAndView model) {
3 Contact newContact = new Contact();
4 model.addObject("contact", newContact);
5 model.setViewName("ContactForm");
return model;
6 }
7

Handler method for inserting/updating a contact:


1 @RequestMapping(value = "/saveContact", method = RequestMethod.POST)
2 public ModelAndView saveContact(@ModelAttribute Contact contact) {
3 contactDAO.saveOrUpdate(contact);
4 return new ModelAndView("redirect:/");
}
5

Handler method for deleting a contact:


1 @RequestMapping(value = "/deleteContact", method = RequestMethod.GET)
2 public ModelAndView deleteContact(HttpServletRequest request) {
3 int contactId = Integer.parseInt(request.getParameter("id"));
4 contactDAO.delete(contactId);
return new ModelAndView("redirect:/");
5
}
6

Handler method for retrieving details of a particular contact for editing:


1
@RequestMapping(value = "/editContact", method = RequestMethod.GET)
2 public ModelAndView editContact(HttpServletRequest request) {
3 int contactId = Integer.parseInt(request.getParameter("id"));
4 Contact contact = contactDAO.get(contactId);
5 ModelAndView model = new ModelAndView("ContactForm");
model.addObject("contact", contact);
6
7 return model;
8 }
9

7. Coding Contact Listing Page (Home Page)


Heres source code of the home.jsp page that displays the contact list as well as action links
for creating new, editing and deleting a contact.
1
2
3
4 <%@page contentType="text/html" pageEncoding="UTF-8"%>
5 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
6 "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
7
8 <html>
9 <head>
10 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
11 <title>Contact Manager Home</title>
12 </head>
<body>
13 <div align="center">
14 <h1>Contact List</h1>
15 <h3><a href="/newContact">New Contact</a></h3>
16 <table border="1">
17 <th>No</th>
<th>Name</th>
18 <th>Email</th>
19 <th>Address</th>
20 <th>Telephone</th>
21 <th>Action</th>
22
<c:forEach var="contact" items="${listContact}" varStatus="status">
23 <tr>
24 <td>${status.index + 1}</td>
25 <td>${contact.name}</td>
26 <td>${contact.email}</td>
27 <td>${contact.address}</td>
<td>${contact.telephone}</td>
28 <td>
29 <a href="/editContact?id=${contact.id}">Edit</a>
30 &nbsp;&nbsp;&nbsp;&nbsp;
31 <a href="/deleteContact?id=${contact.id}">Delete</a>
32 </td>
33
</tr>
34 </c:forEach>
35 </table>
36 </div>
37 </body>
</html>
38
39
40
41
Notice this JSP page uses JSTL and EL expressions.
8. Coding Contact Form Page
The contact form page (ContactForm.jsp) displays details of a contact for creating new or
updating old one. Heres its full source code:
1
2
3
4 <%@ page language="java" contentType="text/html; charset=UTF-8"
5 pageEncoding="UTF-8"%>
6 <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
7 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
8
<html>
9 <head>
10 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
11 <title>New/Edit Contact</title>
12 </head>
<body>
13 <div align="center">
14 <h1>New/Edit Contact</h1>
15 <form:form action="saveContact" method="post" modelAttribute="contact">
16 <table>
17 <form:hidden path="id"/>
<tr>
18 <td>Name:</td>
19 <td><form:input path="name" /></td>
20 </tr>
21 <tr>
<td>Email:</td>
22
<td><form:input path="email" /></td>
23 </tr>
24 <tr>
25 <td>Address:</td>
26 <td><form:input path="address" /></td>
</tr>
27 <tr>
28 <td>Telephone:</td>
29 <td><form:input path="telephone" /></td>
30 </tr>
31 <tr>
<td colspan="2" align="center"><input type="submit" value="Save"></td>
32 </tr>
33 </table>
34 </form:form>
35 </div>
</body>
36 </html>
37
38
39
40

Vous aimerez peut-être aussi