使用spring mvc实现简单的增删改查

使用spring mvc实现简单的增删改查

希望通过这个练习能够让初学者更好的掌握spring mvc的基本知识,来实现对用户基本信息的增删改查操作,先来创建一个User的javabean:

package com.monkey1024.bean;

import org.springframework.format.annotation.DateTimeFormat;

import java.time.LocalDate;

public class User {

    private String name;

    private String phone;

    private String address;

    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private LocalDate birthday;


    public User(){}

    public User(String name, String phone, String address, LocalDate birthday) {
        this.name = name;
        this.phone = phone;
        this.address = address;
        this.birthday = birthday;
    }

    //省略setter和getter
}

这里的增删改查不涉及数据库的操作,模拟编写一个数据初始化的工具类,里面需要做数据初始化,提供增删改查的方法:

package com.monkey1024.util;

import com.monkey1024.bean.User;

import java.time.LocalDate;
import java.util.*;

public class DataUtil {


    private static HashMap<String, User> dataMap = new HashMap<>();

    //模拟初始化数据

    static{
        User user1 = new User("jack", "15188888888", "北京", LocalDate.of(2010, 10, 10));
        User user2 = new User("andy", "13766666666", "上海", LocalDate.of(2014, 11, 11));
        User user3 = new User("paul", "13099999999", "广州", LocalDate.of(2012, 12, 12));

        dataMap.put("1", user1);
        dataMap.put("2", user2);
        dataMap.put("3", user3);
    }

    /**
     * 查找全部数据
     * @return
     */
    public static HashMap<String, User> findAll(){
        return dataMap;
    }

    /**
     * 根据id查找用户
     * @param id
     * @return
     */
    public static User findById(String id){
        return dataMap.get(id);
    }

    /**
     * 创建用户
     * @param user
     * @throws Exception
     */
    public static void create(User user) throws Exception{
        //遍历map找到key的最大值
        Set<Map.Entry<String, User>> entries = dataMap.entrySet();
        Iterator<Map.Entry<String, User>> iterator = entries.iterator();
        int max = 3;
        while (iterator.hasNext()) {
            Map.Entry<String, User> next = iterator.next();
            int i = Integer.parseInt(next.getKey());
            if (i > max) {
                max = i;
            }
        }

        //将最大值做自增运算,然后作为key放入map中
        dataMap.put(++max+"", user);
    }

    /**
     * 更新用户
     * @param id
     * @param user
     */
    public static void update(String id, User user) throws Exception {
        dataMap.put(id, user);
    }

    /**
     * 根据id删除用户
     * @param id
     * @throws Exception
     */
    public static void delete(String id) throws Exception {
        dataMap.remove(id);
    }
}

创建controller:

package com.monkey1024.controller;


import com.monkey1024.bean.User;
import com.monkey1024.util.DataUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;

@Controller
public class UserController {

    /**
     * 查找所有用户
     * @return
     * @throws Exception
     */
    @RequestMapping("findAll")
    public ModelAndView findAll() throws Exception{

        HashMap<String, User> allUser = DataUtil.findAll();

        ModelAndView mv = new ModelAndView();
        mv.addObject("allUser",allUser);
        mv.setViewName("user_list");

        return mv;
    }

    /**
     * 根据id查找
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping("findById")
    public ModelAndView findById(String id) throws Exception{

        ModelAndView mv = new ModelAndView();
        User user = DataUtil.findById(id);
        HashMap<String, User> allUser = new HashMap<>();
        allUser.put(id, user);

        mv.addObject("allUser", allUser);
        mv.addObject("id", id);
        mv.setViewName("user_list");
        return mv;
    }

    /**
     * 新增
     * @param user
     * @return
     */
    @RequestMapping("create")
    public String create(User user) throws Exception{

        DataUtil.create(user);

        return "redirect:findAll";
    }

    /**
     * 更新
     * @param id
     * @param user
     * @return
     */
    @RequestMapping("update")
    public String update(String id, User user) throws Exception{
            DataUtil.update(id, user);

        return "redirect:findAll";
    }

    @RequestMapping("goUpdate")
    public ModelAndView goUpdate(String id)throws Exception{

        User user = DataUtil.findById(id);
        ModelAndView mv = new ModelAndView();
        mv.addObject("user", user);
        mv.addObject("id", id);
        mv.setViewName("user_update");

        return mv;
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @RequestMapping("delete")
    public String delete(String id) throws Exception{

            DataUtil.delete(id);

        return "redirect:findAll";
    }
}

springmvc的配置文件:

<?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:p="http://www.springframework.org/schema/p"
       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">



    <mvc:annotation-driven/>
    <!-- 注册组件扫描器 -->
    <context:component-scan base-package="com.monkey1024.*"/>
    <!-- 视图解析器 -->
    <bean class="org.springframework.web.servlet.view.BeanNameViewResolver"/>


    <!--内部视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>

下面的jsp使用的是bootstrap+jQuery
展示列表user_list.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>monkey1024</title>
    <link href="css/bootstrap.css" rel="stylesheet">

</head>
<body>
<div class="container theme-showcase" role="main">
    <div class="page-header">
        <form id="queryById" action="/findById" method="post">
            <input type="text" name="id" placeholder="请输入id" value="${id}">
            <button id="query" type="button" class="btn btn-sm btn-primary">查询</button>
            <a id="add" type="button" class="btn btn-sm btn-success" href="/jsp/user_add.jsp">添加</a>
        </form>

    </div>
    <div class="row">
        <div class="">
            <table class="table table-striped">
                <thead>
                <tr>
                    <th>编号</th>
                    <th>姓名</th>
                    <th>手机</th>
                    <th>生日</th>
                    <th>地址</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody>
                    <c:forEach items="${allUser}" var="user">
                        <tr>
                            <td>${user.key}</td>
                            <td>${user.value.name}</td>
                            <td>${user.value.phone}</td>
                            <td>${user.value.birthday}</td>
                            <td>${user.value.address}</td>
                            <td>
                                <a type="button" class="btn btn-sm btn-info" href="/delete?id=${user.key}">删除</a>
                                <a type="button" class="btn btn-sm btn-warning" href="/goUpdate?id=${user.key}">修改</a>
                            </td>
                        </tr>
                    </c:forEach>
                </tbody>
            </table>
        </div>
    </div>
</div>
<script src="js/jquery-3.3.1.min.js"></script>
<script src="js/bootstrap.js"></script>
<script>
    $(function () {

        $("#query").click(function () {
            $("#queryById").submit();
        })

    });

</script>
</body>
</html>

添加用户user_addjsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>monkey1024</title>
    <link href="${pageContext.request.contextPath}/css/bootstrap.css" rel="stylesheet">
</head>
<body>
<div class="page-header"></div>
<div class="container">
    <form action="/create" method="post" style="max-width: 330px;padding: 15px;margin: 0 auto;">
        <div class="form-group">
            <label for="name">姓名:</label>
            <input type="text" class="form-control" id="name" name="name">
        </div>
        <div class="form-group">
            <label for="phone">手机:</label>
            <input type="text" class="form-control" id="phone" name="phone">
        </div>
        <div class="form-group">
            <label for="birthday">生日:</label>
            <input type="date" class="form-control" id="birthday" name="birthday">
        </div>
        <div class="form-group">
            <label for="address">地址:</label>
            <input type="text" class="form-control" id="address" name="address">
        </div>
        <input type="submit" value="提交">
    </form>
</div>
<script src="${pageContext.request.contextPath}/js/jquery-3.3.1.min.js"></script>
<script src="${pageContext.request.contextPath}/js/bootstrap.js"></script>
</body>
</html>

修改用户的user_update.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>monkey1024</title>
    <link href="${pageContext.request.contextPath}/css/bootstrap.css" rel="stylesheet">
</head>
<body>
<div class="page-header"></div>
<div class="container">
    <form action="/update" method="post" style="max-width: 330px;padding: 15px;margin: 0 auto;">
        <input name="id" type="hidden" value="${id}">
        <div class="form-group">
            <label for="name">姓名:</label>
            <input type="text" class="form-control" id="name" name="name" value="${user.name}">
        </div>
        <div class="form-group">
            <label for="phone">手机:</label>
            <input type="text" class="form-control" id="phone" name="phone" value="${user.phone}">
        </div>
        <div class="form-group">
            <label for="birthday">生日:</label>
            <input type="date" class="form-control" id="birthday" name="birthday" value="${user.birthday}">
        </div>
        <div class="form-group">
            <label for="address">地址:</label>
            <input type="text" class="form-control" id="address" name="address" value="${user.address}">
        </div>
        <input type="submit" value="提交">
    </form>
</div>
<script src="${pageContext.request.contextPath}/js/jquery-3.3.1.min.js"></script>
<script src="${pageContext.request.contextPath}/js/bootstrap.js"></script>
</body>
</html>