详细笔记的第一遍:学习ssm的整合-CRUD的第7天(2021-11-27)4
27、新增JSR303校验
一般对于比较重要的数据,前端做完校验之后,还需要后端校验。 因为:前端的校验不安全,用户可以绕过js,或者修改元素对应的前端代码。来通过校验。 比如:右键元素,点击检查。可以对代码进行修改。
后端校验,我们使用SpringMVC通过的JSR303进行校验。 包括数据库里面需要对字段empName加上唯一性约束。
想要项目支持JSR303校验,需要导入Hibernate-Validator pom文件。
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.4.1.Final</version>
</dependency>
当前项目的所有pom文件:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.rtl</groupId>
<artifactId>ssm-crud</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.8</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.2</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.7</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.27</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.0.0</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.4.1.Final</version>
</dependency>
</dependencies>
</project>
如何使用JSR校验呢? 第一步: 我们需要对empName设置正则表达式规则: java bean类的Employee对象的属性empName上面添加注解:@Pattern
对于属性empName:
@Pattern(regexp = "^([a-zA-Z0-9_-]|[\\u4E00-\\u9FA5]){2,20}$",
message = "用户名必须为2到12个字符,允许中文,英文大小写,数字,下划线,减号")
private String empName;
对于属性email 可以使用注解@Email 也可以写@Pattern
@Pattern(regexp = "^([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})",
message = "邮箱格式不正确")
private String email;
第二步: 后面这个BindingResult对象是将校验的结果进行了封装。
@RequestMapping(value = "/emp",method = RequestMethod.POST)
@ResponseBody
public Msg saveEmp(@Valid Employee employee , BindingResult result){
employeeService.saveEmployee(employee);
return Msg.success();
}
27、 2021-11-27 18:33 2021-11-21 19:53
1、conttroller
2、index.jsp 我们之前绑定的保存按钮事件: 先进行校验,校验成功之后,再执行新增数据到DB中。
现在补充的就是: 向后端发送ajax请求,新增数据到DB之前,需要校验。 所有index.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<title>首页</title>
<%
pageContext.setAttribute("APP_PATH",request.getContextPath());
%>
<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.5.1.min.js"></script>
<!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
<!-- 可选的 Bootstrap 主题文件(一般不用引入) -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap-theme.min.css" integrity="sha384-6pzBo3FDv/PJ8r2KRkGHifhEocL+1X2rVCTTkUfGk7/0pbek5mMa1upzvWbrUbOZ" crossorigin="anonymous">
<!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous"></script>
</head>
<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" id="empAddModalForm">
<div class="form-group">
<label class="col-sm-2 control-label">empName</label>
<div class="col-sm-10">
<input type="text" name="empName" class="form-control" id="empName_add_input" placeholder="empName">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">email</label>
<div class="col-sm-10">
<input type="text" name="email" class="form-control" id="email_add_input" placeholder="email@qq.com">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">gender</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="F"> 女
</label>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">deptName</label>
<div class="col-sm-4">
<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>
<div class="container">
<%--显示标题--%>
<div class="row">
<div class="col-md-12">
<h1>SSM_CRUD</h1>
</div>
</div>
<%--按钮--%>
<div class="row">
<div class="col-md-4 col-md-offset-8">
<button class="btn btn-primary" id="emp_add_modal_btn">新增</button>
<button class="btn btn-danger">删除</button>
</div>
</div>
<%--表格数据--%>
<div class="row">
<div class="col-md-12">
<table class="table table-hover" id="emps_table">
<thead>
<tr>
<th>#</th>
<th>empName</th>
<th>email</th>
<th>gender</th>
<th>deptName</th>
<th>操作</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<%--分页信息--%>
<div class="row">
<%--分页文字信息--%>
<div class="col-md-6" id="page_info_area"></div>
<%--分页条信息--%>
<div class="col-md-6" id="page_nav_area">
</div>
</div>
</div>
<script type="text/javascript">
var totalRecord;
$(function (){
to_page(1);
});
function to_page(pn){
$.ajax({
url:"${APP_PATH}/emps",
data:"pn="+pn,
type:"GET",
success:function (result) {
build_emp_table(result);
build_page_info(result);
build_page_nav(result);
}
});
}
function build_emp_table(result){
$("#emps_table tbody").empty();
var emps = result.extend.pageInfo.list;
$.each(emps,function (index, item) {
var empIdTd = $("<td></td>").append(item.empId);
var empNameTd = $("<td></td>").append(item.empName);
var genderTd = $("<td></td>").append(item.gender=='M'?"男":"女");
var emailTd = $("<td></td>").append(item.email);
var deptNameTd = $("<td></td>").append(item.department.deptName);
var editBtnId = $("<button></button>")
.addClass("btn btn-primary btn-sm")
.append($("<span></span>").addClass("glyphicon glyphicon-pencil"))
.append("编辑");
var delBtnId = $("<button></button>")
.addClass("btn btn-danger btn-sm")
.append($("<span></span>").addClass("glyphicon glyphicon-trash"))
.append("删除");
var btnTd = $("<td></td>")
.append(editBtnId)
.append(" ")
.append(delBtnId);
$("<tr></tr>").append(empIdTd)
.append(empNameTd)
.append(emailTd)
.append(genderTd)
.append(deptNameTd)
.append(btnTd)
.appendTo("#emps_table tbody");
});
}
function build_page_info(result){
$("#page_info_area").empty();
$("#page_info_area")
.append("当前第"+result.extend.pageInfo.pageNum +"页," +
"总共"+ result.extend.pageInfo.pages+"页," +
"总共"+ result.extend.pageInfo.total+"条记录");
totalRecord = result.extend.pageInfo.total;
}
function build_page_nav(result){
$("#page_nav_area").empty();
var ul = $("<ul></ul>").addClass("pagination");
var firstPageLi = $("<li></li>").append($("<a></a>").append("首页").attr("href","#"));
var prePageLi = $("<li></li>").append($("<a></a>").append("«"));
if(result.extend.pageInfo.hasPreviousPage == false){
firstPageLi.addClass("disabled");
prePageLi.addClass("disabled");
}else{
firstPageLi.click(function(){
to_page(1);
});
prePageLi.click(function(){
to_page(result.extend.pageInfo.pageNum - 1);
});
}
var nextPageLi = $("<li></li>").append($("<a></a>").append("»"));
var lastPageLi = $("<li></li>").append($("<a></a>").append("末页").attr("href","#"));
if(result.extend.pageInfo.hasNextPage == false){
nextPageLi.addClass("disabled");
lastPageLi.addClass("disabled");
}else{
nextPageLi.click(function(){
to_page(result.extend.pageInfo.pageNum + 1);
});
lastPageLi.click(function(){
to_page(result.extend.pageInfo.pages);
});
}
ul.append(firstPageLi).append(prePageLi);
$.each(result.extend.pageInfo.navigatepageNums,function(index,item){
var numLi = $("<li></li>").append($("<a></a>").append(item ));
if(result.extend.pageInfo.pageNum == item){
numLi.addClass("active");
}
numLi.click(function(){
to_page(item);
});
ul.append(numLi);
});
ul.append(nextPageLi).append(lastPageLi);
var navEle = $("<nav></nav>").append(ul);
navEle.appendTo("#page_nav_area");
}
function reset_form(ele){
$(ele)[0].reset();
$(ele).find("*").removeClass("has-error has-success");
$(ele).find(".help-block").text("");
}
$("#emp_add_modal_btn").click(function(){
reset_form("#empAddModalForm");
getDepts();
$("#empAddModal").modal({
backdrop:"static"
});
});
function getDepts(){
$("#dept_add_select").empty();
$.ajax({
url:"${APP_PATH}/depts",
type:"GET",
success:function (result){
$.each(result.extend.depts,function (){
var optionEle = $("<option></option>")
.append(this.deptName)
.attr("value",this.id);
optionEle.appendTo("#dept_add_select");
});
}
});
}
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);
}
}
function validate_add_form(){
var empName = $("#empName_add_input").val();
var regName = /^([a-zA-Z0-9_-]|[\u4E00-\u9FA5]){2,20}$/;
if(!regName.test(empName)){
show_validate_msg("#empName_add_input","error","用户名为2到12个字符,允许中文,英文大小写,数字,下划线,减号");
return false;
}else{
show_validate_msg("#empName_add_input","success","");
}
var email = $("#email_add_input").val();
var 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(){
var empName = this.value;
$.ajax({
url:"${APP_PATH}/checkEmpName",
data:"empName=" + empName,
type:"POST",
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.extend.va_msg);
$("#emp_save_btn").attr("ajax-va","error");
}
}
});
});
$("#emp_save_btn").click(function (){
if(!validate_add_form()){
return false;
}
if($("#emp_save_btn").attr("ajax-va")=="error"){
return false;
}
$.ajax({
url:"${APP_PATH}/emp",
type:"POST",
data:$("#empAddModalForm").serialize(),
success:function (result){
if(result.code == 100){
$("#empAddModal").modal("hide");
to_page(totalRecord);
}else{
if(undefined != result.extend.errorFields.email){
show_validate_msg("#email_add_input","error",result.extend.errorFields.email);
}
if(undefined != result.extend.errorFields.empName){
show_validate_msg("#empName_add_input","error",result.extend.errorFields.empName);
}
}
}
});
});
</script>
</body>
</html>
EmployeeController:
package com.rtl.crud.controller;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rtl.crud.bean.Employee;
import com.rtl.crud.bean.Msg;
import com.rtl.crud.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
@Controller
public class EmployeeController {
@Autowired
private EmployeeService employeeService;
public String getEmps(@RequestParam(value = "pn",defaultValue = "1")Integer pn, Model model){
PageHelper.startPage(pn,5);
List<Employee> emps = employeeService.getAll();
PageInfo pageInfo = new PageInfo(emps,5);
model.addAttribute("pageInfo",pageInfo);
return "list";
}
public PageInfo getEmpsWithPageInfoToJson(@RequestParam(value = "pn",defaultValue = "1")Integer pn){
PageHelper.startPage(pn,5);
List<Employee> emps = employeeService.getAll();
PageInfo pageInfo = new PageInfo(emps,5);
return pageInfo;
}
@RequestMapping(value = "/emps")
@ResponseBody
public Msg getEmpsWithMsgToJson(@RequestParam(value = "pn",defaultValue = "1")Integer pn){
PageHelper.startPage(pn,5);
List<Employee> emps = employeeService.getAll();
PageInfo pageInfo = new PageInfo(emps,5);
Msg msg = Msg.success().add("pageInfo", pageInfo);
return msg;
}
@RequestMapping(value = "/emp",method = RequestMethod.POST)
@ResponseBody
public Msg saveEmp(@Valid Employee employee , BindingResult result){
if(result.hasErrors()){
HashMap<String, Object> map = new HashMap<>();
List<FieldError> errors = result.getFieldErrors();
for (FieldError error : errors) {
System.out.println("错误的字段名:"+error.getField());
System.out.println("错误的信息:"+error.getDefaultMessage());
map.put(error.getField(),error.getDefaultMessage());
}
return Msg.fail().add("errorFields",map);
}else{
employeeService.saveEmployee(employee);
return Msg.success();
}
}
@ResponseBody
@RequestMapping(value = "/checkEmpName")
public Msg checkEmpName(@RequestParam("empName") String empName){
String regx = "^([a-zA-Z0-9_-]|[\\u4E00-\\u9FA5]){2,20}$";
boolean isMatchRegex = empName.matches(regx);
if(!isMatchRegex){
return Msg.fail().add("va_msg","后端校验:用户名为2到12个字符,允许中文,英文大小写,数字,下划线,减号");
}
Boolean b = employeeService.checkEmpName(empName);
if(b){
return Msg.success();
}else{
return Msg.fail().add("va_msg","用户名已经存在");
}
}
}
EmployeeService:
package com.rtl.crud.service;
import com.rtl.crud.bean.Employee;
import com.rtl.crud.bean.EmployeeExample;
import com.rtl.crud.dao.EmployeeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class EmployeeService {
@Autowired
private EmployeeMapper employeeMapper;
public List<Employee> getAll(){
return employeeMapper.selectByExampleWithDept(null);
}
public Employee getEmployeeById(Integer empId){
return employeeMapper.selectByPrimaryKeyWithDept(empId);
}
public void saveEmployee(Employee employee){
employeeMapper.insertSelective(employee);
}
public Boolean checkEmpName(String empName){
EmployeeExample example = new EmployeeExample();
EmployeeExample.Criteria criteria = example.createCriteria();
criteria.andEmpNameEqualTo(empName);
long count = employeeMapper.countByExample(example);
return count == 0;
}
}
|