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

Spring MVC CRUD示例

CRUD(创建,读取,更新和删除)应用程序是用于创建任何项目的最重要的应用程序。它提供了开发大型项目的灵感。在SpringMVC中,我们可以开发一个简单的CRUD应用程序。

在这里,我们使用 JdbcTemplate 进行数据库交互。

创建一个表

在这里,我们使用的是MySQL数据库中存在的emp99表。它具有4个字段: ID,名称,薪水和名称。


Spring MVC CRUD示例

1、将依赖项添加到pom.xml文件。

pom.xml

 <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.1.1.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-jasper -->
<dependency>
    <groupId>org.apache.tomcat</groupId>
    <artifactId>tomcat-jasper</artifactId>
    <version>9.0.12</version>
</dependency>
    <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>  
    <groupId>javax.servlet</groupId>  
    <artifactId>servlet-api</artifactId>  
    <version>3.0-alpha-1</version>  
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>
    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.11</version>
</dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.1.1.RELEASE</version>
</dependency>

2. Creazione della classe bean

In questo contesto, la classe bean contiene le variabili corrispondenti ai campi esistenti nel database (nonché i metodi setter e getter).

Emp.java

package com.w3codebox.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;  
}  
  
}

3、创建控制器类

EmpController.java

package com.w3codebox.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.w3codebox.beans.Emp;  
import com.w3codebox.dao.EmpDao;  
@Controller  
public class EmpController {  
    @Autowired  
    EmpDao dao; // will inject dao from XML file  
      
    /* Visualizza un modulo per inserire i dati, qui "command" è un attributo di richiesta riservato]} 
     * che viene utilizzato per visualizzare i dati dell'oggetto nel modulo 
     */  
    @RequestMapping("/empform")  
    public String showform(Model m){  
        m.addAttribute("command", new Emp());
        return "empform"; 
    }  
    /* Salva l'oggetto nel database. Il @ModelAttribute inserisce i dati della richiesta 
     /* In un oggetto modello. Devi menzionare il metodo RequestMethod.POST */  
     /* Poiché la richiesta predefinita è GET*/  
    @RequestMapping(value="/save", method = RequestMethod.POST)  
    public String save(@ModelAttribute("emp") Emp emp){  
        dao.save(emp);  
        return "redirect:/viewemp";//redirigerà alla mappatura di richiesta viewemp  
    }  
    /* Fornisce l'elenco dei dipendenti nel modello oggetto */  
    @RequestMapping("/viewemp")  
    public String viewemp(Model m){  
        List<Emp> list = dao.getEmployees();  
        m.addAttribute("list", list);
        return "viewemp";  
    }  
    /* Visualizza i dati dell'oggetto in un modulo per l'id fornito.*/  
     * Il @PathVariable inserisce i dati dell'URL nella variabile.*  
    @RequestMapping(value="/editemp/{id}")  
    public String edit(@PathVariable int id, Model m){  
        Emp emp = dao.getEmpById(id);  
        m.addAttribute("command",emp);
        return "empeditform";  
    }  
    /* Aggiorna l'oggetto modello. */  
    @RequestMapping(value="/editsave",method = RequestMethod.POST)  
    public String editsave(@ModelAttribute("emp") Emp emp){  
        dao.update(emp);  
        return "redirect:/viewemp";  
    }  
    /* Elimina il record per l'id fornito nell'URL e reindirizza a /viewemp */  
    @RequestMapping(value="/deleteemp/{id}",method = RequestMethod.GET)  
    public String delete(@PathVariable int id){  
        dao.delete(id);  
        return "redirect:/viewemp";  
    }   
}

4. Creazione della classe DAO

Creiamo una classe DAO per accedere ai dati necessari nel database.

EmpDao.java

package com.w3codebox.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.w3codebox.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;  
        }  
    });  
}  
}

5、Nel file web.xml fornire l'entry del controller

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>

6、在xml文件中定义Bean

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、Creare la pagina della richiesta

index.jsp

<a href="empform">Aggiungi dipendente</a>
<a href="viewemp">Visualizza dipendenti</a>

8、Creare altri componenti di vista

empform.jsp

<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>  
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>  
        <h1>Aggiungi nuovo dipendente</h1>
       <form:form method="post" action="save">  
        <table>  
         <tr>  
          <td>Nome : </td> 
          <td><form:input path="name" /></td>
         </tr>  
         <tr>  
          <td>Stipendio :</td>  
          <td><form:input path="salary" /></td>
         </tr> 
         <tr>  
          <td>Designazione :</td>  
          <td><form:input path="designation" /></td>
         </tr> 
         <tr>  
          <td> </td>  
          <td><input type="submit" value="Salva" /></td>  
         </tr>  
        </table>  
       </form:form>

empeditform.jsp

L'indirizzo "'/SpringMVCCRUDSimple'" è il nome del progetto. Se stai utilizzando un altro nome di progetto, cambia questo nome. Per applicazioni in tempo reale, puoi fornire l'URL completo.

<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>  
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>  
        <h1>Modifica Dipendente</h1>
       <form:form method="POST" action="/SpringMVCCRUDSimple/editsave">  
        <table>  
        <tr>
        <td></td>  
         <td><form:hidden path="id" /></td>
         </tr> 
         <tr>  
          <td>Nome : </td> 
          <td><form:input path="name" /></td>
         </tr>  
         <tr>  
          <td>Stipendio :</td>  
          <td><form:input path="salary" /></td>
         </tr> 
         <tr>  
          <td>Designazione :</td>  
          <td><form:input path="designation" /></td>
         </tr> 
         
         <tr>  
          <td> </td>  
          <td><input type="submit" value="Modifica Salva" /></td>  
         </tr>  
        </table>  
       </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>Lista dei dipendenti</h1>
    <table border="2" width="70%" cellpadding="2">
    <tr><th>Id</th><th>Nome</th><th>Stipendio</th><th>Designazione</th><th>Modifica</th><th>Elimina</th></tr>
    <c:forEach var="emp" items="${list}"> 
    <tr>
    <td>${emp.id}</td>
    <td>${emp.name}</td>
    <td>${emp.salary}</td>
    <td>${emp.designation}</td>
    <td><a href="editemp/${emp.id}">Modifica</a></td>
    <td><a href="deleteemp/${emp.id}">Elimina</a></td>
    </tr>
    </c:forEach>
    </table>
    <br/>
    <a href="empform">Aggiungi nuovo dipendente</a>

Output:


Clicca Aggiungi dipendentevedrai la seguente tabella.


Compila il modulo e poi Clicca su salvareper aggiungere l'elemento al database.


Ora, clicca ModificaPer apportare alcune modifiche ai dati forniti.


Ora, clicca Modifica e salvaper aggiungere l'elemento modificato al database.


Ora, clicca EliminaElimina elemento dal database.