springboot利⽤切⾯集合@valid注解和BindingResult进⾏所有con。。。
1.⾸先在需要校验的参数上加上注解:
@Null 限制只能为null
@NotNull 限制必须不为null
@AssertFalse 限制必须为false
@AssertTrue 限制必须为true
@DecimalMax(value) 限制必须为⼀个不⼤于指定值的数字
@DecimalMin(value) 限制必须为⼀个不⼩于指定值的数字
@Digits(integer,fraction) 限制必须为⼀个⼩数,且整数部分的位数不能超过integer,⼩数部分的位数不能超过fraction
@Future 限制必须是⼀个将来的⽇期
@Max(value) 限制必须为⼀个不⼤于指定值的数字
@Min(value) 限制必须为⼀个不⼩于指定值的数字
@Past 限制必须是⼀个过去的⽇期
@Pattern(value) 限制必须符合指定的正则表达式
@Size(max,min) 限制字符长度必须在min到max之间
@Past 验证注解的元素值(⽇期类型)⽐当前时间早
@NotEmpty 验证注解的元素值不为null且不为空(字符串长度不为0、集合⼤⼩不为0)
@NotBlank 验证注解的元素值不为空(不为null、去除⾸位空格后长度为0),不同于@NotEmpty,@NotBlank只应⽤于字符串且在⽐较时会去除字符串的空格@Email 验证注解的元素值是Email,也可以通过正则表达式和flag指定⾃定义的email格式
2.在controller中加上@valid注解 和BindingResult 对象 另外加上⼀套restful风格的增删改查:
package p.ller;
import ums.ResultEnum;
import p.ruleEnginemon.util.Result;
import p.ruleEnginemon.util.ResultUtil;
import p.ruleEnginemon.vo.RuleQueryVo;
import p.del.*;
import p.ruleEngine.dao.vo.RuleVo;
import p.ruleEngine.service.service.ITRuleFactorService;
import p.ruleEngine.service.service.ITRuleService;
import p.ruleEngine.service.util.DateUtil;
slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import ansaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* 规则
*/
@SuppressWarnings("all")
@Slf4j
@RestController
@RequestMapping("rule")
public class RuleController extends BaseController {
@Autowired
private ITRuleService itRuleService;
@Autowired
private ITRuleFactorService itRuleFactorService;
//region API
//region API
/
**
* select all
*
* @param ruleQueryVo
* @return
*/
@GetMapping("list")
public Result selectList(RuleQueryVo ruleQueryVo) {
log.info("⼊参:" + ruleQueryVo);
Map<String, Object> resultMap = null;
try {
resultMap = itRuleService.selectByList(ruleQueryVo);
} catch (Exception e) {
(ResultEnum.SERVER_ERROR, e.getMessage());
}
return ResultUtil.success(resultMap);
}
/**
* select by id
* GetMapping风格的必须加上@PathVariable 不然获取不到参数
* @param id
* @return
*/
@GetMapping("edit/{id}")
public Result selectById(@PathVariable(value = "id", required = true) Integer id) {
log.info("id:{}" + id);
ModelAndView mv = new ModelAndView();
TRule tRule = itRuleService.selectById(id);
if (tRule == null) {
mv.addObject("msg", "请注意,您正在访问⽆效资源。操作被禁⽌。");
mv.setViewName("error/errorPage");
/*  return mv;*/
}
return ResultUtil.success(tRule);
}
/**
* add rule
* @PostMapping 这种风格必须加上@RequestBody 不然获取不到参数
* @param tRule
* @param erros
* @return
*/
@Transactional(rollbackFor = Exception.class)
@PostMapping("")
public Result insertRule(@Valid @RequestBody TRule tRule, BindingResult erros) {        log.info("tRule:{}" + tRule);
TRule rule = new TRule();
rule.RuleName());
TRule ruleOne = itRuleService.selectByRuleName(rule);
if (ruleOne != null) {
(ResultEnum.RULE_IS_REPEAT);
}
tRule.setCreateTime(new Date());
tRule.setUpdateTime(new Date());
springboot aopint addRule = itRuleService.insertRule(tRule);
if (addRule > 0) {
TRule tRules = itRuleService.selectByRuleName(rule);
for (TRuleFactor tRuleFactor : RuleFactors()) {
//mabatis的特性使⽤引⽤对象可直接获取到刚新增的id 不受事务影响不⽤查⼀遍                tRuleFactor.Id());
tRuleFactor.setCreateTime(new Date());
tRuleFactor.setCreateTime(new Date());
tRuleFactor.setUpdateTime(new Date());
itRuleFactorService.insertRuleFactor(tRuleFactor);
}
} else {
(ResultEnum.INSET_ERROE);
}
return ResultUtil.success();
}
/**
* update rule
*
* @param tRule
* @param erros
* @return
*/
@Transactional(rollbackFor = Exception.class)
@PutMapping
public Result updateRule(@Valid @RequestBody TRule tRule, BindingResult erros) {        log.info("tRule:{}" + tRule);
int ruleIsUse = itRuleService.Id());
if (ruleIsUse > 0) {
(ResultEnum.RULE_ALREADY_USE);
}
int updateRule = itRuleService.updateRule(tRule);
if (updateRule > 0) {
List<TRuleFactor> list = itRuleFactorService.Id());            for (TRuleFactor tRuleFactor : list) {
itRuleFactorService.Id());
}
for (TRuleFactor tRuleFactor : RuleFactors()) {
tRuleFactor.Id());
tRuleFactor.setCreateTime(new Date());
tRuleFactor.setUpdateTime(new Date());
itRuleFactorService.insertRuleFactor(tRuleFactor);
}
} else {
(ResultEnum.UPDATE_ERROE);
}
return ResultUtil.success();
}
/
**
* delete rule
*
* @param id
* @return
*/
@Transactional(rollbackFor = Exception.class)
@DeleteMapping("/{id}")
public Result deleteRule(@PathVariable Integer id) {
log.info("id:{}" + id);
if (id == null) {
(ResultEnum.DATA_IS_NULL, "请传⼊参数");
}
TRule rule = itRuleService.selectById(id);
if (rule != null) {
if ("invalid".Status())) {
int deleteRule = itRuleService.deleteRule(id);
if (deleteRule > 0) {
List<TRuleFactor> ruleFac = itRuleFactorService.selectFactorByRuleId(id);                    for (TRuleFactor tRuleFactor : ruleFac) {
for (TRuleFactor tRuleFactor : ruleFac) {
itRuleFactorService.Id());
}
} else {
(ResultEnum.DELETE_ERROE);
}
} else {
(ResultEnum.DELETE_ERROE, "该变量为启⽤状态");
}
} else {
(ResultEnum.DATA_IS_NULL);
}
return ResultUtil.success();
}
/
/endregion API
}
3.在common项⽬中定义切⾯ 在进⼊controller之前进⾏参数校验 如不通过 直接返回给前端错误信息:
切⾯类:AutoValidateParam:
package com.d.springbootmon.validate;
import com.ums.ResultEnum;
import com.d.springbootmon.util.ResultUtil;
slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
/**
* ⾃动验证controller层的参数
*
* @author zhangqb
* @date 2019/4/1
*/
@Slf4j
@Aspect
@Component
@Order(2)
public class AutoValidateParam {
/**
* 定义切⼊点
*/
@Pointcut("execution(public * com.d.*.web..*.*(..))")
public void cutService() {
public void cutService() {
}
/**
* 在切⼊点开始处切⼊内容
*
* @param joinPoint
*/
@Around("cutService()")
public Object around(ProceedingJoinPoint joinPoint) {
Object result = null;
// 验证结果
ValidateResult validateResult = new ValidateResult(Boolean.TRUE, "参数合法性校验通过!");
// 获取所有的请求参数
Object[] args = Args();
if (null != args && args.length > 0) {
for (Object obj : args) {
if (obj instanceof BindingResult) {
// 参数验证
validateResult = validate((BindingResult) obj);
break;
}
}
}
// 验证通过执⾏拦截⽅法,否则不执⾏
if (validateResult.isValidatePass()) {
try {
// 执⾏拦截⽅法
result = joinPoint.proceed();
} catch (Throwable ex) {
<("AOP执⾏拦截⽅法时异常, {}", ex);
result = (ResultEnum.UNKNOWN_ERROR, "AOP执⾏拦截⽅法时异常!" + ex.getMessage());            }
} else {
result = (ResultEnum.PARAMETER_ERROR, ErrorMessage());
}
return result;
}
/**
* 验证
*
* @param bindingResult
* @return
*/
private ValidateResult validate(BindingResult bindingResult) {
// 参数验证结果
ValidateResult validateResult = ParamValidateUtil.validating(bindingResult);
log.info("请求参数验证结果:{}", validateResult);
return validateResult;
}
}
还有两个是返回前端的封装类。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。