In my other tutorials Spring MVC CRUD example with JDBC Spring MVC and Spring JDBC Example , Spring MVC and JDBC CRUD Example I have used XML configurations but in this tutorial I have used only Annotation, so it means it uses zero XML configurations. This 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. You will also see how DispatcherServlet, DataSource and ViewResolver are configured in Spring using only Annotation. This example also shows how to integrate Spring 4 with Maven 3.
You may also read https://roytuts.com/spring-boot-mvc-with-maven/
Spring Boot MVC and JDBC CRUD Example
For this tutorial 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-zero-xml
The final project looks like below
Step 2. Modify the pom.xml file as shown below.
<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-zero-xml</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>spring-mvc-zero-xml Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <java.version>1.8</java.version> <spring.version>4.3.0.RELEASE</spring.version> <mysqlconnector.version>5.1.36</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> <!-- Servlet --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.1</version> <scope>provided</scope> </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-zero-xml</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> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.6</version> <configuration> <failOnMissingWebXml>false</failOnMissingWebXml> </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 then delete web.xml file from WEB-INF
Step 5. Create WebMvcConfig class under src/main/java directory with the below source code
package com.roytuts.springmvc.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.view.InternalResourceViewResolver; @Configuration @EnableWebMvc @ComponentScan(basePackages = "com.roytuts.springmvc") @PropertySource(value = { "classpath:application.properties" }) public class WebMvcConfig extends WebMvcConfigurerAdapter { @Autowired private Environment environment; @Bean public ViewResolver getViewResolver() { InternalResourceViewResolver resolver = new InternalResourceViewResolver(); resolver.setPrefix("/views/"); resolver.setSuffix(".jsp"); return resolver; } @Bean public JdbcTemplate getJdbcTemplate() throws ClassNotFoundException { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName")); dataSource.setUrl(environment.getRequiredProperty("jdbc.url")); dataSource.setUsername(environment.getRequiredProperty("jdbc.username")); dataSource.setPassword(environment.getRequiredProperty("jdbc.password")); JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); return jdbcTemplate; } }
The above class is a configuration class for ViewResolver and JdbcTemplate and methods are annotated with @Bean because they will be automatically resolved as Spring beans. If we do not give any name to @Bean then it will automatically name the bean with the same return type with first letter in lower case. For examples, bean name for public ViewResolver getViewResolver() will be viewResolver and public JdbcTemplate getJdbcTemplate() will be jdbcTemplate. We have annotated with @EnableWebMvc because this class is used in Spring web MVC. We have an annotation @ComponentScan for base package “com.roytuts.springmvc” because we want to let Spring find the annotated classes with @Controller, @Repository, @Service etc. We have also retrieved the datasource properties using @PropertySource annotation.
Below is the application.properties file put under src/main/resources
jdbc.url=jdbc:mysql://localhost/roytuts jdbc.username=root jdbc.password= jdbc.driverClassName=com.mysql.jdbc.Driver
Step 6. Create WebAppInitializer class under src/main/java directory
package com.roytuts.springmvc.config; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRegistration; import org.springframework.web.WebApplicationInitializer; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; public class WebAppInitializer implements WebApplicationInitializer { @Override public void onStartup(ServletContext servletContext) throws ServletException { AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); context.register(WebMvcConfig.class); context.setServletContext(servletContext); ServletRegistration.Dynamic dispatcher = servletContext.addServlet("DispatcherServlet", new DispatcherServlet(context)); dispatcher.setLoadOnStartup(1); dispatcher.addMapping("/"); } }
So this class initializes few things like whatever we defined in the WebMvcConfig along with DispatcherServlet and Servlet mapping when the application starts up.
Step 7. Create a directory called views under webapp directory for putting created jsp views.
Step 8. Create MySQL table teacher in database roytuts
USE `roytuts`; /*Table structure for table `teacher` */ DROP TABLE IF EXISTS `teacher`; CREATE TABLE `teacher` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(20) COLLATE utf8_unicode_ci NOT NULL, `expertise` varchar(50) COLLATE utf8_unicode_ci NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Step 9. Dump some data into the table
insert into `teacher`(`id`,`name`,`expertise`) values (16,'Bibhas Chandra Dhara','Statistics'), (18,'UKR','System Programming'),(19,'New','Expert');
Step 10. Now create POJO class and mapper class which will map Java object to database table teacher
package com.roytuts.springmvc.model; public class Teacher { private int id; private String name; private String expertise; public Teacher() { } public Teacher(int id, String name, String expertise) { this.id = id; this.name = name; this.expertise = expertise; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getExpertise() { return expertise; } public void setExpertise(String expertise) { this.expertise = expertise; } @Override public String toString() { return "Teacher [id=" + id + ", name=" + name + ", expertise=" + expertise + "]"; } }
Mapper class
package com.roytuts.springmvc.mapper; import java.sql.ResultSet; import java.sql.SQLException; import org.springframework.jdbc.core.RowMapper; import com.roytuts.springmvc.model.Teacher; public class TeacherRowMapper implements RowMapper<Teacher> { @Override public Teacher mapRow(ResultSet rs, int row) throws SQLException { Teacher teacher = new Teacher(); teacher.setId(rs.getInt("id")); teacher.setName(rs.getString("name")); teacher.setExpertise(rs.getString("expertise")); return teacher; } }
Step 11. Create DAO class for querying database table
package com.roytuts.springmvc.dao; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import com.roytuts.springmvc.mapper.TeacherRowMapper; import com.roytuts.springmvc.model.Teacher; @Repository @Transactional public class TeacherDao { @Autowired private JdbcTemplate jdbcTemplate; public Teacher getTeacher(final int id) { Teacher teacher = jdbcTemplate.queryForObject("select * from teacher where id = ?", new Object[] { id }, new TeacherRowMapper()); return teacher; } public List<Teacher> getTeachers() { List<Teacher> teachers = jdbcTemplate.query("select * from teacher", new TeacherRowMapper()); return teachers; } public void addTeacher(final Teacher teacher) { jdbcTemplate.update("insert into teacher(name, expertise) values(?, ?)", new Object[] { teacher.getName(), teacher.getExpertise() }); } public void updateTeacher(final Teacher teacher) { jdbcTemplate.update("update teacher set name = ?, expertise = ? where id = ?", new Object[] { teacher.getName(), teacher.getExpertise(), teacher.getId() }); } public void deleteTeacher(final int id) { jdbcTemplate.update("delete from teacher where id = ?", new Object[] { id }); } }
Step 12. Create the service class for processing logic or business logic
package com.roytuts.springmvc.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.roytuts.springmvc.dao.TeacherDao; import com.roytuts.springmvc.model.Teacher; @Service public class TeacherService { @Autowired private TeacherDao teacherDao; public Teacher getTeacher(final int id) { return teacherDao.getTeacher(id); } public List<Teacher> getTeachers() { return teacherDao.getTeachers(); } public void addTeacher(final Teacher teacher) { teacherDao.addTeacher(teacher); } public void updateTeacher(final Teacher teacher) { teacherDao.updateTeacher(teacher); } public void deleteTeacher(final int id) { teacherDao.deleteTeacher(id); } }
Step 13. Create Spring controller class which will handle user request and response
package com.roytuts.springmvc.controllers; import java.util.List; 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.springmvc.model.Teacher; import com.roytuts.springmvc.service.TeacherService; @Controller public class TeacherController { @Autowired private TeacherService teacherService; @RequestMapping("/teacher/{id}") // by default Requestmethod is GET public String getTeacher(@PathVariable int id, ModelMap teacherModel) { Teacher teacher = teacherService.getTeacher(id); teacherModel.addAttribute("teacher", teacher); return "teacher"; } @RequestMapping(value = "/teachers", method = RequestMethod.GET) public String getTeachers(ModelMap teacherModel) { List<Teacher> teachers = teacherService.getTeachers(); teacherModel.addAttribute("teachers", teachers); return "teachers"; } @RequestMapping(value = "addTeacher") public String addPage() { return "add"; } @RequestMapping(value = "/add/teacher", method = RequestMethod.POST) public String addTeacher(@RequestParam(value = "name", required = true) String name, @RequestParam(value = "expertise", required = true) String expertise, ModelMap teacherModel) { Teacher teacher = new Teacher(); teacher.setName(name); teacher.setExpertise(expertise); teacherService.addTeacher(teacher); teacherModel.addAttribute("msg", "Teacher added successfully"); List<Teacher> teachers = teacherService.getTeachers(); teacherModel.addAttribute("teachers", teachers); return "teachers"; } @RequestMapping(value = "update/teacher/{id}", method = RequestMethod.GET) public String updatePage(@PathVariable("id") int id, ModelMap teacherModel) { teacherModel.addAttribute("id", id); Teacher teacher = teacherService.getTeacher(id); teacherModel.addAttribute("teacher", teacher); return "update"; } @RequestMapping(value = "/update/teacher", method = RequestMethod.POST) public String updateTeacher(@RequestParam int id, @RequestParam(value = "name", required = true) String name, @RequestParam(value = "expertise", required = true) String expertise, ModelMap teacherModel) { Teacher teacher = new Teacher(); teacher.setId(id); teacher.setName(name); teacher.setExpertise(expertise); teacherService.updateTeacher(teacher); List<Teacher> teachers = teacherService.getTeachers(); teacherModel.addAttribute("teachers", teachers); teacherModel.addAttribute("id", id); teacherModel.addAttribute("msg", "Teacher updated successfully"); return "teachers"; } @RequestMapping(value = "/delete/teacher/{id}") public String deleteTeacher(@PathVariable int id, ModelMap teacherModel) { teacherService.deleteTeacher(id); List<Teacher> teachers = teacherService.getTeachers(); teacherModel.addAttribute("teachers", teachers); teacherModel.addAttribute("msg", "Teacher delted successfully"); return "teachers"; } }
Step 14. Now create teacher.jsp file under webapp/views directory for displaying single teacher details
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <html> <title>Spring MVC Zero XML Example</title> <body> <h2>Spring MVC Zero XML Example</h2> Id : ${teacher.id} <br /> Name : ${teacher.name} <br /> Expertise : ${teacher.expertise} </body> </html>
Step 15. Create teachers.jsp file under webapp/views directory for displaying all teachers 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 Zero XML Example</title> <body> <h2>Spring MVC Zero XML Example</h2> <c:if test="${not empty msg}"> ${msg} </c:if> <c:choose> <c:when test="${teachers != null}"> <h3>List of Teachers</h3> <table cellpadding="5" cellspacing="5"> <thead> <tr> <th>ID</th> <th>Name</th> <th>Expertise</th> <th>Actions</th> </tr> </thead> <tbody> <c:forEach var="t" items="${teachers}"> <tr> <td>${t.id}</td> <td>${t.name}</td> <td>${t.expertise}</td> <td><a href="<%=request.getContextPath()%>/update/teacher/${t.id}">Update</a> <a href="<%=request.getContextPath()%>/delete/teacher/${t.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 16. Create add.jsp file under webapp/views directory for adding new teacher
<%@ 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 Zero XML Example</title> <body> <h2>Spring MVC Zero XML Example</h2> <c:if test="${not empty msg}"> ${msg} </c:if> <h3>Add User</h3> <form method="POST" name="add_teacher" action="<%=request.getContextPath()%>/add/teacher"> Name: <input name="name" value="${name}" type="text" /> <br /> <br /> Expertise: <input name="expertise" value="${expertise}" type="text" /> <br /> <br /> <input value="Add Teacher" type="submit" /> </form> </body> </html>
Step 17. Create update.jsp file under webapp/views directory for updating new teacher
<%@ 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 Zero XML Example</title> <body> <h2>Spring MVC Zero XML Example</h2> <c:if test="${not empty msg}"> ${msg} </c:if> <h3>Update User</h3> <form method="POST" name="update_teacher" action="<%=request.getContextPath()%>/update/teacher"> <input hidden="hidden" name="id" value="${id}" type="text" /> Name: <input name="name" value="${teacher.name}" type="text" /> <br /> <br /> Expertise: <input name="expertise" value="${teacher.expertise}" type="text" /> <br /> <br /> <input value="Update User" type="submit" /> </form> </body> </html>
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-zero-xml/teachers , you will below output in the browser
When you hit the URL http://localhost:8080/spring-mvc-zero-xml/teacher/16 in the browser, you will see the below output
When you click on the update link on page http://localhost:8080/spring-mvc-zero-xml/teachers in the browser, you will see the below output
When you click on the delete link on page http://localhost:8080/spring-mvc-zero-xml/teachers in the browser, you will see the below output
When you hit the URL http://localhost:8080/spring-mvc-zero-xml/addTeacher in the browser, you will see the below output
After add, update and delete of teacher the page navigates automatically to the all teachers page.
Spring Boot MVC and JDBC CRUD Example
Thanks for reading.
Keep thіs going please, great job!