看表可以知道分类目录主要有名字,目录级别,父级,展现时的排序
写Controller时考虑传入四个参数以及登录的session.
Controller:
@Autowired UserService userService; @Autowired CategoryService categoryService; /** * 后台添加目录 */ @ApiOperation("后台添加目录") @PostMapping("admin/category/add") @ResponseBody public ApiRestResponse addCategory(HttpSession session, @Valid @RequestBody AddCategoryReq addCategoryReq) { User currentUser = (User) session.getAttribute(Constant.IMOOC_MALL_USER); if (currentUser == null) { return ApiRestResponse.error(ImoocMallExceptionEnum.NEED_LOGIN); } //校验是否是管理员 boolean adminRole = userService.checkAdminRole(currentUser); if (adminRole) { //是管理员,执行操作 categoryService.add(addCategoryReq); return ApiRestResponse.success(); } else { return ApiRestResponse.error(ImoocMallExceptionEnum.NEED_ADMIN); } }
@ResponseBody加入这个注解是因为要是用POSTMAN 直接传入json字符串,方法传入参数不在使用传入四个参数的传统写法而是将四个参数写成类似于实体类的形式进行调用
/** * 描述: AddCategoryReq */ public class AddCategoryReq { @Size(min = 2, max = 5) @NotNull(message = "name不能为null") private String name; @NotNull(message = "type不能为null") @Max(3) private Integer type; @NotNull(message = "parentId不能为null") private Integer parentId; @NotNull(message = "orderNum不能为null") private Integer orderNum; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } public Integer getParentId() { return parentId; } public void setParentId(Integer parentId) { this.parentId = parentId; } public Integer getOrderNum() { return orderNum; } public void setOrderNum(Integer orderNum) { this.orderNum = orderNum; } }
Service:
@Autowired CategoryMapper categoryMapper; @Override public void add(AddCategoryReq addCategoryReq) { Category category = new Category(); BeanUtils.copyProperties(addCategoryReq, category); Category categoryOld = categoryMapper.selectByName(addCategoryReq.getName()); if (categoryOld != null) { throw new ImoocMallException(ImoocMallExceptionEnum.NAME_EXISTED); } int count = categoryMapper.insertSelective(category); if (count == 0) { throw new ImoocMallException(ImoocMallExceptionEnum.CREATE_FAILED); } }
BeanUtils.copyProperties(addCategoryReq, category); //两个类里面,字段类型一样,字段名一样拷贝过去(从哪里拷贝,拷贝到哪里)
使用此方法可以不用在使用set而是可以自动完成字段的拷贝
mapper:
Category selectByName(String naem);
<select id="selectByName" parameterType="java.lang.String" resultMap="BaseResultMap"> select <include refid="Base_Column_List"/> from imooc_mall_category where name = #{name,jdbcType=VARCHAR} </select>
测试时需要先进行登录,登录时会获取用户的信息,在后台添加新目录功能时会进行判断是否为管理员。也就是判断用户的权值。如果是调用service.add,如果不是,报错返回错位写在枚举类中。