English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

table. It has

CRUD (Create, Read, Update, and Delete) applications are the most important applications for creating any project. They provide ideas for developing large projects. In SpringMVC, we can develop a simple CRUD application.

在这里,我们使用 JdbcTemplate Here, we use

JdbcTemplate

to interact with the database.99Create a table4Here, we use the emp table existing in the MySQL database


table. It has

1fields: ID, name, salary, and name.

Spring MVC CRUD Example

 java-- .0.//<!/https:/mvnrepository.com/spring-Add the dependencies to the pom.xml file. -->
org.springframework
    jdbc/<dependency>
    <groupId>org.springframework-pom.xml/<artifactId>jdbc
    <version>5.1.1.RELEASE</version>
</dependency>
java-- .0.//<!/https:/webmvc/webmvc-org.apache.tomcat -->
org.springframework
    tomcat/<dependency>
    jasper-<groupId>org.apache.tomcat/<artifactId>jdbc
    <version>9connector12</version>
</dependency>
    java-- .0.//<!/https:/.0/.0-<artifactId>tomcat -->
org.springframework  
    alpha/<dependency>  
    jasper-api/<artifactId>jdbc  
    <version>3<artifactId>servlet-api-1</version>  
</dependency>
java-- .0.//<!/https:/.0/jstl -->
org.springframework
    alpha/<dependency>
    javax.servlet/<artifactId>jdbc
    <version>1.2</version>
</dependency>
    java-- .0.//<!/https:/<groupId>javax.servlet/<groupId>javax.servlet-<groupId>mysql-<artifactId>jstl -->
org.springframework
    mysql/<dependency>
    java-<groupId>mysql-<artifactId>mysql/<artifactId>jdbc
    <version>8connector11</version>
</dependency>
    java-- .0.//<!/https:/mvnrepository.com/spring-artifact -->
org.springframework
    jdbc/<dependency>
    <groupId>org.springframework-<artifactId>spring/<artifactId>jdbc
    <version>5.1.1.RELEASE</version>
</dependency>

2Create a bean class

Here, the bean class contains variables corresponding to the fields existing in the database (as well as setter and getter methods).

Emp.java

package com.3codebox.beans;  
  
public class Emp {  
private int id;  
private String name;  
private float salary;  
private String designation;  
  
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 float getSalary() {  
    return salary;  
}  
public void setSalary(float salary) {  
    this.salary = salary;  
}  
public String getDesignation() {  
    return designation;  
}  
public void setDesignation(String designation) {  
    this.designation = designation;  
}  
  
}

3Create a controller class

EmpController.java

package com.3codebox.controllers;   
import java.util.List;  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;  
import org.springframework.web.bind.annotation.PathVariable;  
import org.springframework.web.bind.annotation.RequestMapping;  
import org.springframework.web.bind.annotation.RequestMethod;   
import com.3codebox.beans.Emp;  
import com.3codebox.dao.EmpDao;  
@Controller  
public class EmpController {  
    @Autowired  
    EmpDao dao;//will inject dao from XML file  
      
    /*It displays a form to input data, here "command" is a reserved request attribute 
     *which is used to display object data into form 
     */  
    @RequestMapping("/empform")  
    public String showform(Model m){  
        m.addAttribute("command", new Emp());
        return "empform"; 
    }  
    /*It saves the object into the database. The @ModelAttribute puts request data 
     *  into the model object. You need to mention RequestMethod.POST method  
     *  because the default request is GET*/  
    @RequestMapping(value="/save", method = RequestMethod.POST)  
    public String save(@ModelAttribute("emp") Emp emp){  
        dao.save(emp);  
        return "redirect:/viewemp";//will redirect to viewemp request mapping  
    }  
    /* It provides a list of employees in the model object */  
    @RequestMapping("/viewemp"  
    public String viewemp(Model m){  
        List<Emp> list = dao.getEmployees();  
        m.addAttribute("list", list);
        return "viewemp";  
    }  
    /* It displays object data into form for the given id.  
     * The @PathVariable puts URL data into variable.*/  
    @RequestMapping(value="/editemp/{id}"  
    public String edit(@PathVariable int id, Model m){  
        Emp emp = dao.getEmpById(id);  
        m.addAttribute("command", emp);
        return "empeditform";  
    }  
    /* It updates the model object. */  
    @RequestMapping(value="/editsave", method = RequestMethod.POST)  
    public String editsave(@ModelAttribute("emp") Emp emp){  
        dao.update(emp);  
        return "redirect:/viewemp";  
    }  
    /* It deletes the record for the given id in the URL and redirects to /viewemp */  
    @RequestMapping(value="/deleteemp/{id}", method = RequestMethod.GET)  
    public String delete(@PathVariable int id){  
        dao.delete(id);  
        return "redirect:/viewemp";  
    }   
}

4Create DAO class

Let us create a DAO class to access the required data in the database.

EmpDao.java

package com.3codebox.dao;  
import java.sql.ResultSet;  
import java.sql.SQLException;  
import java.util.List;  
import org.springframework.jdbc.core.BeanPropertyRowMapper;  
import org.springframework.jdbc.core.JdbcTemplate;  
import org.springframework.jdbc.core.RowMapper;  
import com.3codebox.beans.Emp;  
  
public class EmpDao {  
JdbcTemplate template;  
  
public void setTemplate(JdbcTemplate template) {  
    this.template = template;  
}  
public int save(Emp p){  
    String sql="insert into Emp99(name,salary,designation) values('"+p.getName()+"',"+p.getSalary()+"',"+p.getDesignation()+"')";  
    return template.update(sql);  
}  
public int update(Emp p){  
    String sql="update Emp99 set name='"+p.getName()+"', salary="+p.getSalary()+"designation='"+p.getDesignation()+"' where id="+p.getId()+"";  
    return template.update(sql);  
}  
public int delete(int id){  
    String sql = "delete from Emp99 where id="+id+"";  
    return template.update(sql);  
}  
public Emp getEmpById(int id){  
    String sql = "select * from Emp99 where id=?";  
    return template.queryForObject(sql, new Object[]{id}, new BeanPropertyRowMapper<Emp>(Emp.class));  
}  
public List<Emp> getEmployees(){  
    return template.query("select * from Emp99",new RowMapper<Emp>(){  
        public Emp mapRow(ResultSet rs, int row) throws SQLException {  
            Emp e = new Emp();  
            e.setId(rs.getInt(1));  
            e.setName(rs.getString(2));  
            e.setSalary(rs.getfloat(3));  
            e.setDesignation(rs.getString(4));  
            return e;  
        }  
    });  
}  
}

5provide the controller entries in the web.xml file

web.xml

<?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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>SpringMVC</display-name>
   <servlet  
    <servlet-name>spring</servlet-name>  
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
    <load-on-startup>1</load-on-startup>    
</servlet>  
<servlet-mapping>  
    <servlet-name>spring</servlet-name>  
    <url-pattern>/</url-pattern>  
</servlet-mapping>  
</web-app>

6Define Bean in xml file

spring-servlet.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:mvc="http://www.springframework.org/schema/mvc"
    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
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com.w3codebox.controllers></context:component-scan>  
  
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
<property name="prefix" value="/WEB-INF/jsp/></property>  
<property name="suffix" value=".jsp"></property>  
</bean>  
  
<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>  
<property name="url" value="jdbc:mysql:<//localhost:3306/test"></property>  
<property name="username" value=""></property>  
<property name="password" value=""></property>  
</bean>  
  
<bean id="jt" class="org.springframework.jdbc.core.JdbcTemplate">  
<property name="dataSource" ref="ds"></property>  
</bean>  
  
<bean id="dao" class="com.w3codebox.dao.EmpDao">  
<property name="template" ref="jt"></property>  
</bean>     
</beans>

7、Create the requested page

index.jsp

<a href="empform">Add Employee</a>
<a href="viewemp">View Employees</a>

8、Create other view components

empform.jsp

<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>  
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>  
        <h1>Add new Employee</h1>
       <form:form method="post" action="save">  
        <table >  
         <tr  
          td>Name : </> 
          <td><form:input path="name"  /></>
         </>  
         <tr  
          td>Salary :</>  
          <td><form:input path="salary" /></>
         </> 
         <tr  
          td>Designation :</>  
          <td><form:input path="designation" /></>
         </> 
         <tr  
          td> </>  
          <td><input type="submit" value="Save" /></>  
         </>  
        </>  
       </form:form>

empeditform.jsp

Here"/SpringMVCCRUDSimple" is the project name. If you are using a different project name, please change this name. For real-time applications, you can provide the full URL.

<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>  
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>  
        <h1>Edit Employee</h1>
       <form:form method="POST" action="/SpringMVCCRUDSimple/editsave">  
        <table >  
        <tr
        td></>  
         <td><form:hidden  path="id" /></>
         </> 
         <tr  
          td>Name : </> 
          <td><form:input path="name"  /></>
         </>  
         <tr  
          td>Salary :</>  
          <td><form:input path="salary" /></>
         </> 
         <tr  
          td>Designation :</>  
          <td><form:input path="designation" /></>
         </> 
         
         <tr  
          td> </>  
          <td><input type="submit" value="Edit Save" /></>  
         </>  
        </>  
       </form:form>

viewemp.jsp

    <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>  
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>  
    <h1>Employees List/h1>
    <table border="2" width="70%" cellpadding="2">
    <tr><th>Id/>/>/>/>/>/>/>
    <c:forEach var="emp" items="${list}" 
    <tr
    ${emp.id}/>
    ${emp.name}/>
    ${emp.salary}/>
    ${emp.designation}/>
    <td><a href="editemp/${emp.id}>Edit/a>/>
    <td><a href="deleteemp/${emp.id}>Delete/a>/>
    </>
    </c:forEach
    </>
    <br/>
    <a href="empform">Add new Employee</a>/a>

Output:


Click Add Employeeyou will see the following table.


Fill in the form and then Click Saveto add the entry to the database.


Now, click EditTo make some changes to the provided content data.


Now, click Edit and Save, to add the entry with changes to the database.


Now, click DeleteDelete an entry from the database.