在前端输入id,姓名,密码,利用选择框选择专业,性别。发送ajax的post请求实现数据库的user表中增加user。再返回页面实现局部刷新。
点击新建按钮
add-counselor.html
<script>
$('#submit').bind('click', function (event) {
event.preventDefault()
let counselorId = $('#counselorId').val()
if(counselorId.length<6){
alert('学工号长度最少6位')
return
}else if(counselorId.length>20){
alert('学工号长度最多20位')
return
}else if(counselorId.indexOf(' ') >=0){
alert('学工号不能包含空白符')
return
}
let password = $('#password').val()
if(password.length<6){
alert('密码长度最少6位')
return
}else if(password.length>20){
alert('密码长度最多20位')
return
}else if(password.indexOf(' ') >=0){
alert('密码不能包含空白符')
return
}
let repassword = $('#repassword').val()
if(password !== repassword){
alert('密码不一致')
return
}
let disciplineId = parseInt($('#discipline').find('option:selected').val())
if (disciplineId === 0){
alert('请选择辅导员所属专业');
return
}
let gender = parseInt($('#gender').find('option:selected').val())
let name = $('#name').val()
$.ajax({
type : 'post',
url: "/adminCounselor/addCounselor",
data: {
counselorId, password, disciplineId,name,gender},
success: function (res) {
alert(res.message)
$(location).attr('href', '/adminCounselor/findAllCounselor')
},
error: function (err) {
alert('添加辅导员失败')
}
})
})
</script>
adminCounselor.java
@GetMapping("/toAddCounselor")
public String toAddCounselor(Model model){
List<Discipline> disciplines = disciplineService.findAllDiscipline();
model.addAttribute("disciplines", disciplines);
return "/counselor/add-counselor";
}
@PostMapping("/addCounselor")
@ResponseBody
public Result<Counselor> addCounselor(HttpServletRequest request, HttpSession session){
// 参数
String counselorId = request.getParameter("counselorId");
String password = MD5Utils.code(request.getParameter("password"));
String name = request.getParameter("name");
int gender = Integer.parseInt(request.getParameter("gender"));
int disciplineId = Integer.parseInt(request.getParameter("disciplineId"));
User user = new User(counselorId, password, 4, "辅导员");
userService.saveUser(user);
Counselor counselor = new Counselor(counselorId, name, gender, disciplineId);
Counselor existedCounselor = counselorService.findCounselorByCounselorId(counselor);
Result<Counselor> result = new Result<>();
if(existedCounselor != null){
result.setMessage("该用户已存在");
}else if(counselorService.saveCounselor(counselor) == 1){
result.setMessage("添加辅导员成功");
}else{
result.setMessage("添加辅导员失败");
}
result.setData(counselor);
return result;
}
跳转到添加页面
add-counselor.html
<html xmlns:th="http://www.thymeleaf.org" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>添加辅导员</title>
<meta name="description" content="AdminLTE2定制版">
<meta name="keywords" content="AdminLTE2定制版">
<meta content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" name="viewport">
<link rel="stylesheet"