小谷充电项目技术学习(1)--若以框架响应约定和数据校验
1.ruoyi知识点
BaseController
BaseController中的方法了解,知道有这样的方法后使用时可以点去看源码
//1.将前台传递过来的日期格式的字符串,自动转化为Date类型
@InitBinder
public void initBinder(WebDataBinder binder){}
//2.设置请求的分页数据
protected void startPage(){PageUtils.startPage();}
//3.清理分页的线程变量
protected void clearPage(){PageUtils.clearPage();}
//4.响应请求分页数据
@SuppressWarnings({ "rawtypes", "unchecked" })
protected TableDataInfo getDataTable(List<?> list){}
//5.返回成功
public AjaxResult success(){return AjaxResult.success();}
//6.返回成功消息
public AjaxResult success(String message){return AjaxResult.success(message);}
//7.返回成功消息
public AjaxResult success(Object data){return AjaxResult.success(data);}
//8.返回失败消息
public AjaxResult error(){return AjaxResult.error();}
//9.返回失败消息
public AjaxResult error(String message){return AjaxResult.error(message);}
//10.返回警告消息
public AjaxResult warn(String message){return AjaxResult.warn(message);}
//11.响应返回结果
protected AjaxResult toAjax(int rows){return rows > 0 ? AjaxResult.success() : AjaxResult.error();}
//12.响应返回结果
protected AjaxResult toAjax(boolean result){return result ? success() : error();}
另外还有SysRoleController、PageUtils、AjaxResult这几个类,为CRUD操作做了一些使用的约定:
1.分页查询
分页查询的响应返回值为:TableDataInfo
在controller中按照约定方式调用继承的方法后,分页查询只需要写正常的查询即可。而且和前端的组件是相切合的。
@RequiresPermissions("system:role:list")
@GetMapping("/list") //查询角色的分页数据
public TableDataInfo list(SysRole role)//role用来pojo入参获取查询参数
{
startPage(); //调用BaseController中的分页方法
List<SysRole> list = roleService.selectRoleList(role); //执行分页查询
return getDataTable(list);//调用BaseController中的方法封装分页数据
}
2.增删改查
新增、修改、删除的响应值为:AjaxResult
用toAjax方法返回
@Operation(summary = "修改柜机类型")
@PutMapping
public AjaxResult edit(@RequestBody CabinetType cabinetType)
{
return toAjax(cabinetTypeService.updateById(cabinetType));
}
@Operation(summary = "修改柜机类型")
@PutMapping
public AjaxResult edit(@RequestBody CabinetType cabinetType)
{
return toAjax(cabinetTypeService.updateById(cabinetType));
}
@Operation(summary = "删除柜机类型")
@DeleteMapping("/{ids}")
public AjaxResult remove(@PathVariable Long[] ids)
{
return toAjax(cabinetTypeService.removeBatchByIds(Arrays.asList(ids)));
}
3.查询全部数据
@Operation(summary = "删除柜机类型")
@DeleteMapping("/{ids}")
public AjaxResult remove(@PathVariable Long[] ids)
{
return toAjax(cabinetTypeService.removeBatchByIds(Arrays.asList(ids)));
}
2.数据校验
新增和修改数据的时候往往有很多的数据校验,spring-boot-starter-validation是Spring Boot提供的一个starter,它为应用程序提供了Bean Validation API的支持。Bean Validation是Java EE的一部分,用于验证JavaBean的属性是否符合规范。使用Spring Boot和spring-boot-starter-validation,您可以轻松地使用注解来验证请求参数、对象等是否符合要求。
加入依赖
在使用spring-boot-starter-validation时,需要添加相关的依赖。
share-common-core模块已引入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
基本注解
空检查
@Null 验证对象是否为null
@NotNull 验证对象是否不为null, 无法查检长度为0的字符串
@NotBlank 检查约束字符串是不是Null还有被Trim的长度是否大于0,只对字符串,且会去掉前后空格.
@NotEmpty 检查约束元素是否为NULL或者是EMPTY.
Booelan检查
@AssertTrue 验证 Boolean 对象是否为 true
@AssertFalse 验证 Boolean 对象是否为 false
长度检查
@Size(min=, max=) 验证对象(Array,Collection,Map,String)长度是否在给定的范围之内
@Length(min=, max=) 验证注解的元素值长度在min和max区间内
日期检查
@Past 验证 Date 和 Calendar 对象是否在当前时间之前
@Future 验证 Date 和 Calendar 对象是否在当前时间之后
@Pattern 验证 String 对象是否符合正则表达式的规则
数值检查,建议使用在Stirng,Integer类型,不建议使用在int类型上,因为表单值为“”时无法转换为int,但可以转换为Stirng为"",Integer为null
@Min 验证 Number 和 String 对象是否大等于指定的值
@Max 验证 Number 和 String 对象是否小等于指定的值
@DecimalMax 被标注的值必须不大于约束中指定的最大值. 这个约束的参数是一个通过BigDecimal定义的最大值的字符串表示.小数存在精度
@DecimalMin 被标注的值必须不小于约束中指定的最小值. 这个约束的参数是一个通过BigDecimal定义的最小值的字符串表示.小数存在精度
@Digits 验证 Number 和 String 的构成是否合法
@Digits(integer=,fraction=) 验证字符串是否是符合指定格式的数字,interger指定整数精度,fraction指定小数精度。
@Range(min=, max=) 验证注解的元素值在最小值和最大值之间
@Range(min=10000,max=50000,message="range.bean.wage")
@Valid 写在方法参数前,递归的对该对象进行校验, 如果关联对象是个集合或者数组,那么对其中的元素进行递归校验,如果是一个map,则对其中的值部分进行校验.(是否进行递归验证)
@CreditCardNumber信用卡验证
@Email 验证是否是邮件地址,如果为null,不进行验证,算通过验证。
@ScriptAssert(lang= ,script=, alias=)
@URL(protocol=,host=, port=,regexp=, flags=)
实体类添加校验注解
@Data
@Schema(description = "柜机类型")
public class CabinetType extends BaseEntity
{
private static final long serialVersionUID = 1L;
/** 名称 */
@Schema(description = "名称")
@NotBlank(message = "名称名称不能为空")
private String name;
/** 总插槽数量 */
@Schema(description = "总插槽数量")
@NotNull(message = "总插槽数量不能为空")
private Integer totalSlots;
/** 描述 */
@Schema(description = "描述")
private String description;
/** 状态(0正常 1停用) */
@Schema(description = "状态")
private String status;
}
接口方法使用@Validated注解
@Operation(summary = "新增柜机类型")
@PostMapping
public AjaxResult add(@RequestBody @Validated CabinetType cabinetType)
{
return toAjax(cabinetTypeService.save(cabinetType));
}
@Operation(summary = "修改柜机类型")
@PutMapping
public AjaxResult edit(@RequestBody @Validated CabinetType cabinetType)
{
return toAjax(cabinetTypeService.updateById(cabinetType));
}
校验失败的异常捕获
share-common-security模块全局异常处理器GlobalExceptionHandler类,捕获参数校验异常
/**
* 自定义验证异常
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
public Object handleMethodArgumentNotValidException(MethodArgumentNotValidException e)
{
log.error(e.getMessage(), e);
String message = e.getBindingResult().getFieldError().getDefaultMessage();
return AjaxResult.error(message);
}

浙公网安备 33010602011771号