前言:
在對管理後臺,一般都有對單表的CRUD操作,這些操作,爲了業務安全,都牽扯到一個參數校驗的問題,所以需要統一一下規範,好處在於,減少代碼的臃腫,讓代碼更清晰,講重點只需要關注業務即可,也減少後續維護成本….
使用技術點:
javax.validation或者org.springframework.util.Assert
CRUD使用javax.validation示例:
1.定義AddParam UpdateParam 兩個註解,用於後續的參數校驗
import javax.validation.groups.Default;
public interface AddParam extends Default {
}
import javax.validation.groups.Default;
public interface UpdateParam extends Default {
}
2.在對入參中實體類(DTO)中的屬性,加上一些參數校驗註解和上面兩個自定義註解
@Data
@ApiModel
public class EmergencyPersonnelDTO {
@ApiModelProperty("id,新增不必傳遞,修改必須傳遞")
@Null(message = "id必須爲null或空",groups = {AddParam.class})
@NotNull(message = "id不能爲空",groups = {UpdateParam.class})
private Integer id;
@ApiModelProperty("手機號")
@NotBlank(message = "手機號不能爲空")
private String tel;
@ApiModelProperty("姓名")
@NotBlank(message = "姓名不能爲空")
private String nick;
@ApiModelProperty("備註")
private String description;
@ApiModelProperty("崗位")
@NotBlank(message = "崗位不能爲空")
private String jobs;
@ApiModelProperty("鄉鎮街道 id")
@NotNull(message = "鄉鎮街道 id不能爲空")
private Integer aid;
}
Controller:
@Slf4j
@Api(tags = "XXX管理")
@RestController
@RequestMapping(value = "/test")
public class UEmergencyController {
@Resource
private IEmergencyService emergencyService;
@PostMapping(value = "list")
@ApiOperation(httpMethod = "POST", value = "列表", response = EmergencyEventEntity.class)
public ApiResult emergencyList(@ApiParam @RequestBody PageCondition<QueryDTO> pageCondition) {
if (pageCondition == null) {
pageCondition = new PageCondition<>();
}
return ApiResult.success(emergencyService.emergencyList(pageCondition));
}
@GetMapping(value = "view")
@ApiOperation(httpMethod = "GET", value = "查看", response = EmergencyEventEntity.class)
public ApiResult viewEmergency(@ApiParam @RequestParam(value = "id",required = false) Integer id) {
Assert.notNull(id, "id is not passed");
return ApiResult.success(emergencyService.viewEmergency(id));
}
@PostMapping(value = "add")
@ApiOperation(httpMethod = "POST", value = "添加", response = Boolean.class)
public ApiResult addEmergency(@ApiParam @RequestBody @Validated({AddParam.class}) EmergencyEventDTO dto) {
return ApiResult.success(emergencyService.addEmergency(dto));
}
@PostMapping(value = "update")
@ApiOperation(httpMethod = "POST", value = "修改", response = Boolean.class)
public ApiResult updateEmergency(@ApiParam @RequestBody @Validated({UpdateParam.class}) EmergencyEventDTO dto) {
return ApiResult.success(emergencyService.updateEmergency(dto));
}
@GetMapping(value = "del")
@ApiOperation(httpMethod = "GET", value = "刪除", response = Boolean.class)
public ApiResult delEmergency(@ApiParam @RequestParam(value = "id",required = false) Integer id) {
Assert.notNull(id, "id is not passed");
return ApiResult.success(emergencyService.delEmergency(id));
}
}
從以上代碼看,可以看到代碼很簡潔,參數校驗在controller層就已經完成,後續的業務層,只需要關注業務即可
PS:
1.注意AddParam和UpdateParam註解繼承了Default,在 validation的group特性中,如果不繼承,則不校驗默認分組(Default),
2.在屬性字段上不聲明分組,都是使用Default分組,
所以,根據需求,自定義註解來看要不要繼承Default...