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";
}
这样基本上就实现了添加的功能,接下来就是在浏览器观看效果
