1、需要实现的功能
- 在 index.jsp 页面点击“新增”弹出对话框
- 去数据库中查询部门列表,显示在对话框内
- 对用户输入的数据进行校验
- jQuery 前端校验格式
- Ajax 校验用户名是否重复
- 后端校验(JSR303)——>重要数据
- 保存用户数据
URI 设计
/emp/{id}
,GET
请求,查询员工数据/emp
,POST
请求,保存员工数据/emp/{id}
,PUT
请求,修改员工数据-
2、Service
@Service
public class DepartmentService {
@Autowired
private DepartmentMapper departmentMapper;
public List<Department> getDepts() {
List<Department> list = departmentMapper.selectByExample(null);
return list;
}
}
@Service public class EmployeeService { @Autowired EmployeeMapper employeeMapper; /** * 员工保存 * @param employee */ public void saveEmp(Employee employee) { // TODO Auto-generated method stub employeeMapper.insertSelective(employee); } /** * 检验用户名是否可用 * * @param empName * @return true:代表当前姓名可用 fasle:不可用 */ public boolean checkUser(String empName) { // TODO Auto-generated method stub EmployeeExample example = new EmployeeExample(); Criteria criteria = example.createCriteria(); criteria.andEmpNameEqualTo(empName); long count = employeeMapper.countByExample(example); return count == 0; } ... }
3、Controller
```xml /**
- 处理和部门有关的请求
- @author zmh
@create 2021-11-29 19:41 */ @Controller public class DepartmentController {
@Autowired private DepartmentService departmentService;
/**
- 返回所有的部门信息
- @return
*/
@RequestMapping(“/depts”)
@ResponseBody
public Msg getDepts(){
List
list = departmentService.getDepts(); return Msg.success().add(“depts”,list); }
}@Controller public class DepartmentController {
@Autowired
private DepartmentService departmentService;
/**
* 返回所有的部门信息
* @return
*/
@RequestMapping("/depts")
@ResponseBody
public Msg getDepts(){
List<Department> list = departmentService.getDepts();
return Msg.success().add("depts",list);
}
}
```xml
/**
* 处理员工CRUD请求
*
* @author zmh
*
*/
@Controller
public class EmployeeController {
@Autowired
EmployeeService employeeService;
/**
* 根据id查询员工
* @param id
* @return
*/
@RequestMapping(value="/emp/{id}",method=RequestMethod.GET)
@ResponseBody
public Msg getEmp(@PathVariable("id")Integer id){
Employee employee = employeeService.getEmp(id);
return Msg.success().add("emp", employee);
}
/**
* 检查用户名是否可用
* @param empName
* @return
*/
@ResponseBody
@RequestMapping("/checkuser")
public Msg checkuser(@RequestParam("empName")String empName){
//先判断用户名是否是合法的表达式;
String regx = "(^[a-zA-Z0-9_-]{6,16}$)|(^[\u2E80-\u9FFF]{2,5})";
if(!empName.matches(regx)){
return Msg.fail().add("va_msg", "用户名必须是6-16位数字和字母的组合或者2-5位中文");
}
//数据库用户名重复校验
boolean b = employeeService.checkUser(empName);
if(b){
return Msg.success();
}else{
return Msg.fail().add("va_msg", "用户名不可用");
}
}
/**
* 员工保存
* 1、支持JSR303校验
* 2、导入Hibernate-Validator
*
*
* @return
*/
@RequestMapping(value="/emp",method=RequestMethod.POST)
@ResponseBody
public Msg saveEmp(@Valid Employee employee,BindingResult result){
if(result.hasErrors()){
//校验失败,应该返回失败,在模态框中显示校验失败的错误信息
Map<String, Object> map = new HashMap<>();
List<FieldError> errors = result.getFieldErrors();
for (FieldError fieldError : errors) {
System.out.println("错误的字段名:"+fieldError.getField());
System.out.println("错误信息:"+fieldError.getDefaultMessage());
map.put(fieldError.getField(), fieldError.getDefaultMessage());
}
return Msg.fail().add("errorFields", map);
}else{
employeeService.saveEmp(employee);
return Msg.success();
}
}
......
}
4、修改 index.jsp
在 body 部分添加如下内容:
<!-- 新增员工信息的模态框 -->
<div class="modal fade" id="empAddModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="myModalLabel">添加员工</h4>
</div>
<div class="modal-body">
<form class="form-horizontal">
<div class="form-group">
<label class="col-sm-2 control-label">姓名</label>
<div class="col-sm-10">
<input type="text" name="empName" class="form-control" id="empName_add_input"
placeholder="xxx">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">性别</label>
<div class="col-sm-10">
<label class="radio-inline">
<input type="radio" name="gender" id="gender1_add_input" value="M" checked="checked"> 男
</label>
<label class="radio-inline">
<input type="radio" name="gender" id="gender2_add_input" value="W"> 女
</label>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">邮箱</label>
<div class="col-sm-10">
<input type="text" name="email" class="form-control" id="email_add_input"
placeholder="xxx@xxx.com">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">部门</label>
<div class="col-sm-4">
<!--传送部门id即可-->
<select class="form-control" name="dId" id="dept_add_select"></select>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
<button type="button" class="btn btn-primary" id="emp_save_btn">保存</button>
</div>
</div>
</div>
</div>
js 部分添加如下内容:
<script type="text/javascript">
......
/**
* 重置表单的内容和样式
*/
function reset_form(ele) {
//拿到DOM对象,调用reset方法,清空内容
$(ele)[0].reset();
//清空样式
$(ele).find("*").removeClass("has-error has-success");
$(ele).find(".help-block").text("");
}
/**
* 点击新增按钮,弹出模态框
*/
$("#emp_add_modal_btn").click(function () {
//1、先调用方法重置表单
reset_form("#empAddModal form");
//2、再调用方法查部门信息
getDepts("#dept_add_select");
//3、弹出模态框
$("#empAddModal").modal({
//点击背景不会消失
backdrop: "static"
})
});
/**
* 发送 Ajax 请求,查处部门信息,显示在下拉列表中
*/
function getDepts(ele) {
//先清空下拉列表的值,再发送请求
$(ele).empty();
$.ajax({
url: "${APP_PATH}/depts",
type: "GET",
success: function (result) {
$.each(result.data.depts, function () {
let optionEle = $("<option></option>").append(this.deptName).attr("value", this.deptId);
optionEle.appendTo(ele);
});
}
})
}
/**
* 显示校验结果的提示信息
*/
function show_validate_msg(ele, status, msg) {
//清除当前元素的校验状态
$(ele).parent().removeClass("has-success has-error");
$(ele).next("span").text("");
if ("success" == status) {
$(ele).parent().addClass("has-success");
$(ele).next("span").text(msg);
} else if ("error" == status) {
$(ele).parent().addClass("has-error");
$(ele).next("span").text(msg);
}
}
/**
* 前端 jQuery 校验表单数据是否合法(使用正则表达式)
*/
function validate_add_form() {
//1、校验姓名
let empName = $("#empName_add_input").val();
let regName = /(^[a-zA-Z0-9_-]{6,16}$)|(^[\u2E80-\u9FFF]{2,5})/;
if (!regName.test(empName)) {
show_validate_msg("#empName_add_input", "error", "用户名必须是2-5位中文或者6-16位英文和数字的组合");
return false;
} else {
show_validate_msg("#empName_add_input", "success", "");
}
//2、校验邮箱
let email = $("#email_add_input").val();
let regEmail = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;
if (!regEmail.test(email)) {
show_validate_msg("#email_add_input", "error", "邮箱格式不正确");
return false;
} else {
show_validate_msg("#email_add_input", "success", "");
}
return true;
}
/**
* 校验用户名是否重复
*/
$("#empName_add_input").change(function () {
$.ajax({
url: "${APP_PATH}/checkUser",
data: "empName=" + this.value,
type: "GET",
success: function (result) {
if (result.code == 100) {
show_validate_msg("#empName_add_input", "success", "用户名可用");
$("#emp_save_btn").attr("ajax-va", "success");
} else {
show_validate_msg("#empName_add_input", "error", result.data.va_msg);
$("#emp_save_btn").attr("ajax-va", "error");
}
}
})
});
/**
* 新增用户数据,点击保存按钮
*/
$("#emp_save_btn").click(function () {
//1、前端 jQuery 校验数据格式
if (!validate_add_form()) {
return false;
}
//2、校验用户名是否可用
if ($(this).attr("ajax-va") == "error") {
return false;
}
//3、发送 Ajax POST 请求保存新增员工信息
$.ajax({
url: "${APP_PATH}/emp",
type: "POST",
data: $("#empAddModal form").serialize(),
success: function (result) {
if (result.code == 100) {
//保存成功,关闭模态框,来到最后一页
$("#empAddModal").modal('hide');
to_page(totalPages + 1);
} else {
//显示失败信息,有哪个字段的错误信息就显示哪个字段的;
if (undefined != result.data.errorFields.email) {
//显示邮箱错误信息
show_validate_msg("#email_add_input", "error", result.data.errorFields.email);
}
if (undefined != result.data.errorFields.empName) {
//显示员工名字的错误信息
show_validate_msg("#empName_add_input", "error", result.data.errorFields.empName);
}
}
}
});
});
</script>
搞定