📜  Spring MVC CRUD示例(1)

📅  最后修改于: 2023-12-03 15:05:16.218000             🧑  作者: Mango

Spring MVC CRUD示例

本文将介绍一个完整的Spring MVC CRUD示例,该示例涵盖了创建,读取,更新和删除(CRUD)操作的实现过程。在本示例中,我们将使用Spring MVC框架来实现一个RESTful Web服务,它可以执行基本的CRUD操作。我们还将使用Hibernate来访问数据库,并使用JSP作为前端呈现模板。

技术栈
  • Spring MVC
  • Hibernate
  • JSP
  • MySQL
代码示例
创建实体类

我们首先需要创建一个实体类Customer,该类将与数据库中的表进行映射。在这个类中,我们定义了一些属性,例如ID,名称,地址和联系方式等。

@Entity
@Table(name = "customers")
public class Customer {
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    @Column(name = "name")
    private String name;
    
    @Column(name = "address")
    private String address;
    
    @Column(name = "phone")
    private String phone;
    
    // getter and setter methods
}

在这个实体类中,我们使用了Hibernate的注释来指定与数据库表之间的映射关系。

创建DAO接口和实现类

在这个示例中,我们定义了一个接口CustomerDAO,它为CRUD操作提供了各种方法。然后我们实现了该接口的实现类CustomerDAOImpl,它将利用Hibernate与数据库交互。

public interface CustomerDAO {

    public List<Customer> getCustomers();

    public void saveCustomer(Customer customer);

    public Customer getCustomer(Long id);

    public void deleteCustomer(Long id);
}

@Repository
public class CustomerDAOImpl implements CustomerDAO {

    @Autowired
    private SessionFactory sessionFactory;

    @Override
    public List<Customer> getCustomers() {
        Session currentSession = sessionFactory.getCurrentSession();
        Query<Customer> theQuery = currentSession.createQuery("from Customer", Customer.class);
        List<Customer> customers = theQuery.getResultList();
        return customers;
    }

    @Override
    public void saveCustomer(Customer customer) {
        Session currentSession = sessionFactory.getCurrentSession();
        currentSession.saveOrUpdate(customer);
    }

    @Override
    public Customer getCustomer(Long id) {
        Session currentSession = sessionFactory.getCurrentSession();
        Customer customer = currentSession.get(Customer.class, id);
        return customer;
    }

    @Override
    public void deleteCustomer(Long id) {
        Session currentSession = sessionFactory.getCurrentSession();
        Query theQuery = currentSession.createQuery("delete from Customer where id=:customerId");
        theQuery.setParameter("customerId", id);
        theQuery.executeUpdate();
    }
}

在接口的实现类中,我们注入了Hibernate的SessionFactory,它是与数据库进行交互的核心组件。我们实现了接口中定义的所有方法并实现了相应的Hibernate查询和操作。

创建控制器

我们需要创建一个控制器类来处理HTTP请求和响应。在这个类中,我们注入了CustomerService,它是对CRUD操作的另一层抽象。

@Controller
@RequestMapping("/customer")
public class CustomerController {

    @Autowired
    private CustomerService customerService;

    @GetMapping("/list")
    public String listCustomers(Model model) {
        List<Customer> customers = customerService.getCustomers();
        model.addAttribute("customers", customers);
        return "customers";
    }

    @GetMapping("/showFormForAdd")
    public String showFormForAdd(Model model) {
        Customer customer = new Customer();
        model.addAttribute("customer", customer);
        return "customer-form";
    }

    @PostMapping("/saveCustomer")
    public String saveCustomer(@ModelAttribute("customer") Customer customer) {
        customerService.saveCustomer(customer);
        return "redirect:/customer/list";
    }

    @GetMapping("/showFormForUpdate")
    public String showFormForUpdate(@RequestParam("customerId") Long id, Model model) {
        Customer customer = customerService.getCustomer(id);
        model.addAttribute("customer", customer);
        return "customer-form";
    }

    @GetMapping("/delete")
    public String deleteCustomer(@RequestParam("customerId") Long id) {
        customerService.deleteCustomer(id);
        return "redirect:/customer/list";
    }
}

在这个控制器中,我们使用了Spring的注释来处理HTTP请求和响应。我们注入了CustomerService,它是对CRUD操作的封装,使用CustomerService我们可以更好地隔离数据存储和控制器的逻辑。在控制器方法中,我们使用@ModelAttribute注释来接收表单提交的数据。

创建服务类

最后,我们将实现一个CustomerService,它是对DAO的进一步封装。这将实现我们的CRUD操作的核心逻辑。在这个类中,我们注入了CustomerDAO,并实现了该类中定义的方法。

@Service
public class CustomerServiceImpl implements CustomerService {

    @Autowired
    private CustomerDAO customerDAO;

    @Override
    @Transactional
    public List<Customer> getCustomers() {
        return customerDAO.getCustomers();
    }

    @Override
    @Transactional
    public void saveCustomer(Customer customer) {
        customerDAO.saveCustomer(customer);
    }

    @Override
    @Transactional
    public Customer getCustomer(Long id) {
        return customerDAO.getCustomer(id);
    }

    @Override
    @Transactional
    public void deleteCustomer(Long id) {
        customerDAO.deleteCustomer(id);
    }
}

在这个服务类中,我们使用了Spring的注释来声明该类为服务,并使用@Transactional实现事务管理。

创建JSP模板

最后,我们需要定义JSP模板来呈现Web应用程序的视图。在这个示例中,我们将创建list-customers.jspcustomer-form.jsp两个JSP模板。

list-customers.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>List Customers</title>
    <link rel="stylesheet" href="${pageContext.request.contextPath}/resources/css/bootstrap.min.css">
</head>
<body>

<div class="container">
    <div class="row">
        <div class="col-md-12">
            <h3>List Customers</h3>
            <hr>
            <a href="${pageContext.request.contextPath}/customer/showFormForAdd" class="btn btn-primary">Add Customer</a>
            <br><br>
            <table class="table table-bordered">
                <thead>
                <tr>
                    <th>Name</th>
                    <th>Address</th>
                    <th>Phone</th>
                    <th>Actions</th>
                </tr>
                </thead>
                <tbody>
                <c:forEach var="customer" items="${customers}">
                    <tr>
                        <td>${customer.name}</td>
                        <td>${customer.address}</td>
                        <td>${customer.phone}</td>
                        <td>
                            <a href="${pageContext.request.contextPath}/customer/showFormForUpdate?customerId=${customer.id}" class="btn btn-info">Edit</a>
                            <a href="${pageContext.request.contextPath}/customer/delete?customerId=${customer.id}" class="btn btn-danger" onclick="return confirm('Are you sure?')">Delete</a>
                        </td>
                    </tr>
                </c:forEach>
                </tbody>
            </table>
        </div>
    </div>
</div>

</body>
</html>

在这个模板中,我们使用Bootstrap样式来使页面更加美观。我们在表中展示了所有客户的详细信息,并添加了添加,编辑和删除操作的链接。

customer-form.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Add Customer</title>
    <link rel="stylesheet" href="${pageContext.request.contextPath}/resources/css/bootstrap.min.css">
</head>
<body>

<div class="container">
    <div class="row">
        <div class="col-md-12">
            <h3>Add/Edit Customer</h3>
            <hr>
            <form:form action="${pageContext.request.contextPath}/customer/saveCustomer" method="POST"
                       commandName="customer">
                <table>
                    <tr>
                        <td><form:label path="name">Name:</form:label></td>
                        <td><form:input path="name"/></td>
                    </tr>
                    <tr>
                        <td><form:label path="address">Address:</form:label></td>
                        <td><form:input path="address"/></td>
                    </tr>
                    <tr>
                        <td><form:label path="phone">Phone:</form:label></td>
                        <td><form:input path="phone"/></td>
                    </tr>
                    <tr>
                        <td colspan="2"><input type="submit" value="Save" class="btn btn-primary"/></td>
                    </tr>
                </table>
            </form:form>
        </div>
    </div>
</div>

</body>
</html>

在这个模板中,我们使用了Spring的表单标签库来简化表单的创建过程。这将允许我们更容易地收集和处理表单提交的数据。

总结

在本文中,我们介绍了一个完整的Spring MVC CRUD示例。我们实现了基本的CRUD操作,并使用Hibernate进行与数据库的交互。我们使用了JSP模板来简化Web应用程序的视图设计,并使用Bootstrap样式使页面更加美观。通过这个示例,我们向您展示了如何使用Spring和Hibernate来构建能够进行CRUD操作的RESTful Web服务。