1、JSR303校验
对填入的数据自动做一些约束
package com.xuecheng.content.model.dto; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.Size; import java.math.BigDecimal; @Data @ApiModel(value="AddCourseDto", description="新增课程基本信息") public class AddCourseDto { @NotEmpty(message = "课程名称不能为空") @ApiModelProperty(value = "课程名称", required = true) private String name; @NotEmpty(message = "适用人群不能为空") @Size(message = "适用人群内容过少",min = 10) @ApiModelProperty(value = "适用人群", required = true) private String users; @ApiModelProperty(value = "课程标签") private String tags; @NotEmpty(message = "课程分类不能为空") @ApiModelProperty(value = "大分类", required = true) private String mt; @NotEmpty(message = "课程分类不能为空") @ApiModelProperty(value = "小分类", required = true) private String st; @NotEmpty(message = "课程等级不能为空") @ApiModelProperty(value = "课程等级", required = true) private String grade; @ApiModelProperty(value = "教学模式(普通,录播,直播等)", required = true) private String teachmode; @ApiModelProperty(value = "课程介绍") private String description; @ApiModelProperty(value = "课程图片", required = true) private String pic; @NotEmpty(message = "收费规则不能为空") @ApiModelProperty(value = "收费规则,对应数据字典", required = true) private String charge; @ApiModelProperty(value = "价格") private Float price; @ApiModelProperty(value = "原价") private Float originalPrice; @ApiModelProperty(value = "qq") private String qq; @ApiModelProperty(value = "微信") private String wechat; @ApiModelProperty(value = "电话") private String phone; @ApiModelProperty(value = "有效期") private Integer validDays; }
@ApiOperation("新增课程") @PostMapping("/course") public CourseBaseInfoDto createCourseBase(@RequestBody @Validated AddCourseDto addCourseDto){ //获取到用户所属机构的id Long companyId = 1232141425L; // int i = 1/0; CourseBaseInfoDto courseBase = courseBaseInfoService.createCourseBase(companyId, addCourseDto); return courseBase; }
getBindingResult
getBindingResult是Spring MVC中的一个方法,用于获取表单数据绑定的结果对象。
在Spring MVC中,当处理表单提交时,会将表单数据绑定到一个Java对象中,这个过程称为数据绑定。当数据绑定出现错误时,Spring MVC会将错误信息存储在一个BindingResult对象中,我们可以使用getBindingResult方法来获取这个对象,从而获取表单数据绑定的结果。
BindingResult对象包含了以下信息:
- 绑定的表单数据字段名
- 绑定的表单数据类型
- 绑定的表单数据值
- 错误信息,如验证失败的错误信息
我们可以使用BindingResult对象来检查表单数据绑定是否成功,以及是否存在错误。如果存在错误,我们可以进一步处理这些错误信息,例如显示在页面上或者进行其他的操作。
下面是一个简单的示例:
@PostMapping("/submit-form") public String submitForm(@Valid MyForm form, BindingResult bindingResult) { if (bindingResult.hasErrors()) { // 处理错误信息 } // 处理表单提交 }
在上面的代码中,我们使用@Valid注解来标注MyForm对象,表示需要对其进行数据验证。如果数据验证失败,Spring MVC会将错误信息存储在bindingResult对象中,我们可以通过调用bindingResult.hasErrors()方法来检查是否存在错误信息。如果存在错误信息,我们可以进一步处理这些信息。
MethodArgumentNotValidException
//MethodArgumentNotValidException @ResponseBody @ExceptionHandler(MethodArgumentNotValidException.class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) public RestErrorResponse methodArgumentNotValidException(MethodArgumentNotValidException e){ BindingResult bindingResult = e.getBindingResult(); //存储错误信息 List<String> errors = new ArrayList<>(); bindingResult.getFieldErrors().stream().forEach(item->{ errors.add(item.getDefaultMessage()); }); //将list中的错误信息拼接起来 String errMessage = StringUtils.join(errors, ","); //记录异常 log.error("系统异常{}",e.getMessage(),errMessage); //解析出异常信息 RestErrorResponse restErrorResponse = new RestErrorResponse(errMessage); return restErrorResponse; }
JSR303分组校验
由于增加和修改都可能用到同一个DTO,这时候就需要分组校验
package com.xuecheng.base.exception; /** * @author Mr.M * @version 1.0 * @description 用于分级校验,定义一些常用的组 * @date 2023/2/14 9:37 */ public class ValidationGroups { public interface Inster{}; public interface Update{}; public interface Delete{}; }
2、参数合法性校验
3、修改课程接口
@Override public CourseBaseInfoDto updateCourseBase(Long companyId, EditCourseDto editCourseDto) { //拿到课程id Long courseId = editCourseDto.getId(); //查询课程信息 CourseBase courseBase = courseBaseMapper.selectById(courseId); if(courseBase == null){ XueChengPlusException.cast("课程不存在"); } //数据合法性校验 //根据具体的业务逻辑去校验 //本机构只能修改本机构的课程 if(!companyId.equals(courseBase.getCompanyId())){ XueChengPlusException.cast("本机构只能修改本机构的课程"); } //封装数据 BeanUtils.copyProperties(editCourseDto,courseBase); //修改时间 courseBase.setChangeDate(LocalDateTime.now()); //更新数据库 int i = courseBaseMapper.updateById(courseBase); if(i<=0){ XueChengPlusException.cast("修改课程失败"); } //更新营销信息 //todo:更新营销信息 //查询课程信息 CourseBaseInfoDto courseBaseInfo = getCourseBaseInfo(courseId); return courseBaseInfo; }
4、课程查询计划查询
<!-- 通用查询结果列 --> <sql id="Base_Column_List"> id, pname, parentid, grade, media_type, start_time, end_time, description, timelength, orderby, course_id, course_pub_id, status, is_preview, create_date, change_date </sql> <resultMap id="treeNodeResultMap" type="com.xuecheng.content.model.dto.TeachplanDto"> <id column="one_id" property="id" /> <result column="one_pname" property="pname" /> <result column="one_parentid" property="parentid" /> <result column="one_grade" property="grade" /> <result column="one_mediaType" property="mediaType" /> <result column="one_stratTime" property="stratTime" /> <result column="one_endTime" property="endTime" /> <result column="one_orderby" property="orderby" /> <result column="one_courseId" property="courseId" /> <result column="one_coursePubId" property="coursePubId" /> <!--映射子节点,一对多映射,ofType list中的对象类型--> <collection property="teachPlanTreeNodes" ofType="com.xuecheng.content.model.dto.TeachplanDto"> <id column="two_id" property="id" /> <result column="two_pname" property="pname" /> <result column="two_parentid" property="parentid" /> <result column="two_grade" property="grade" /> <result column="two_mediaType" property="mediaType" /> <result column="two_stratTime" property="stratTime" /> <result column="two_endTime" property="endTime" /> <result column="two_orderby" property="orderby" /> <result column="two_courseId" property="courseId" /> <result column="two_coursePubId" property="coursePubId" /> <!--一对一映射--> <association property="teachplanMedia" javaType="com.xuecheng.content.model.po.TeachplanMedia"> <id column="teachplanMeidaId" property="id"/> <result column="mediaFilename" property="mediaFilename"/> <result column="mediaId" property="mediaId"/> </association> </collection> </resultMap> <select id="selectTreeNodes" parameterType="long" resultMap="treeNodeResultMap"> select one.id one_id, one.pname one_pname, one.parentid one_parentid, one.grade one_grade, one.media_type one_mediaType, one.start_time one_stratTime, one.end_time one_endTime, one.orderby one_orderby, one.course_id one_courseId, one.course_pub_id one_coursePubId, two.id two_id, two.pname two_pname, two.parentid two_parentid, two.grade two_grade, two.media_type two_mediaType, two.start_time two_stratTime, two.end_time two_endTime, two.orderby two_orderby, two.course_id two_courseId, two.course_pub_id two_coursePubId, m1.media_fileName mediaFilename, m1.id teachplanMeidaId, m1.media_id mediaId from teachplan one inner join teachplan two on two.parentid = one.id left join teachplan_media m1 on two.id = m1.teachplan_id where one.parentid = 0 and one.course_id = #{id} order by one.orderby,two.orderby </select>
5、新增修改课程计划
业务层代码:
private int getTeachplanCount(Long courseId,Long parentId){ LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>(); queryWrapper = queryWrapper.eq(Teachplan::getCourseId, courseId).eq(Teachplan::getParentid, parentId); Integer count = teachplanMapper.selectCount(queryWrapper); return count+1; } @Override public void saveTeachplan(SaveTeachplanDto saveTeachplanDto) { //通过课程计划id判断是新增和修改 Long teachplanId = saveTeachplanDto.getId(); if(teachplanId ==null){ //新增 Teachplan teachplan = new Teachplan(); BeanUtils.copyProperties(saveTeachplanDto,teachplan); //确定排序字段,找到它的同级节点个数,排序字段就是个数加1 select count(1) from teachplan where course_id=117 and parentid=268 Long parentid = saveTeachplanDto.getParentid(); Long courseId = saveTeachplanDto.getCourseId(); int teachplanCount = getTeachplanCount(courseId, parentid); teachplan.setOrderby(teachplanCount); teachplanMapper.insert(teachplan); }else{ //修改 Teachplan teachplan = teachplanMapper.selectById(teachplanId); //将参数复制到teachplan BeanUtils.copyProperties(saveTeachplanDto,teachplan); teachplanMapper.updateById(teachplan); } }