spring boot完成数据库的添加功能

第一步 在Service中实现接口

public void doInsert(Person person){
    iPerson.save(person);
}

第二步 在后台Controller 中

//    跳转添加
    @RequestMapping("/toAdd")
    public String toAdd(Model model){
        List<Classes> list=classService.findClass();
        model.addAttribute("classes",list);
    //        List<Grade> list1=iGradeService.findAll();
    //        model.addAttribute("grade",list1);
        return "add";
    }

第三步 在前端的添加界面使用Ajax ,进行提交到后台

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/person/doAdd" id="form_add">
    姓名:<input type="text" name="name"><br>
    性别:<input type="text" name="sex"><br>
    生日:<input type="date" name="birthday"><br>
    身份证:<input type="text" name="card"><br>
    电话:<input type="text" name="telephone"><br>
    班级:<select name="sid">
            <option  th:each="classes:${classes}" th:text="${classes.cname}" th:value="${classes.cid}"></option>
         </select><br>
    <!--    年级:<select name="gid">-->
    <!--            <option  th:each="grade:${grade}" th:text="${grade.gname}" th:value="${grade.gid}"></option>-->
    <!--         </select><br>-->
    <input type="button" value="提交" id="submit">
</form>
</body>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
    $(function(){
        $("#submit").click(function(){
            // alert("123");
            // alert($("#form_add").serialize());
            $.ajax({
                type:'post',
                //将数据提交到后台
                url: "http://localhost:8080/person/doAdd",
                data:$("#form_add").serialize(),
                success: function (result) {
                   
                    alert("添加成功")
                    //跳转到新页面
                    window.location.href="/person/toIndex";
                    // alert(this.data);
                }
            });
        });
    });
</script>
</html>

serialize() 方法通过序列化表单值,创建 URL 编码文本字符串。

您可以选择一个或多个表单元素(比如 input 及/或 文本框),或者 form 元素本身。

序列化的值可在生成 AJAX 请求时用于 URL 查询字符串中。

第四步 将封装好的属性在Person实体类中接收

@RequestMapping("/doAdd")
//    @ResponseBody
    public String doAdd(Person person){

        personService.doInsert(person);
        return "redirect:/person/toIndex";
    }

这样基本上就实现了添加的功能,接下来就是在浏览器观看效果

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

平平常常一般牛

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值