注:先在serviceImp里写一个判断是否为管理员登录的方法,之后可以方便调用
//校验是否为管理员
public ServerResponse checkAdminRole(User user){
if (user != null && user.getRole()==Const.Role.ROLE_ADMIN){
return ServerResponse.createBySuccess();
}
return ServerResponse.createByError();
}
数据库表:0代表为根节点,id为自增,parentId表示每个子分类所属的父分类。
1、增加分类
参数:父类节点分类ID parentId,分类名categoryName
思路:判断是否为管理员登录,如果为管理员登录,则判断从前端传来的parentId和categoryName是否为空,为空则从后端返回一个错误信息status=1,msg=“添加品类失败,参数错误”告知前端。反之则把parentId和category的值增加进数据库中。如果传来的parentId为空,则给它添加一个默认值为0,代表添加的当前分类为根节点。
- controller
//增加分类,parentId默认值为 0
@RequestMapping("add_Category.do")
@ResponseBody
public ServerResponse addCategory(HttpSession session,String categoryName,@RequestParam(value = "parentId",defaultValue="0") int parentId){
User user= (User) session.getAttribute(Const.CURRENT_USER);
if(user==null){
return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),"用户未登录,请登录");
}
//校验是否为管理员
// if (iUserService.checkAdminRole(user).isSuccess()){
// return iCategoryService.addCategory(categoryName,parentId);
// }else{
// return ServerResponse.createByErrorMessage("不是管理员,无权限操作");
// }
if(user.getRole()==Const.Role.ROLE_ADMIN){
return iCategoryService.addCategory(categoryName,parentId);
}else{
return ServerResponse.createByErrorMessage("不是管理员,无权限操作");
}
}
- serviceImp
//添加分类
public ServerResponse addCategory(String categoryName,Integer parentId){
//判断category是否为空和parentId是否为0,因为parentId默认值为0,则代表传过来的parentId参数为空
if(org.apache.commons.lang3.StringUtils.isBlank(categoryName) && parentId == 0){
return ServerResponse.createByErrorMessage("添加分类失败,参数错误");
}
Category category=new Category();
category.setName(categoryName);
category.setParentId(parentId);
category.setStatus(true);
int rowCount=categoryMapper.insert(category);
if (rowCount>0){
return ServerResponse.createBySuccessMessage("添加分类成功");
}
return ServerResponse.createByErrorMessage("添加分类失败");
}
- success
{
"status": 0,
"msg": "添加分类成功"
}
- fail
{
"status": 1,
"msg": "添加分类失败"
}
或者
{
"status": 1,
"msg": "添加品类失败,参数错误"
}
2、修改分类名称
参数:分类名的ID categoryId,新的分类名称categoryName
思路:判断是否为管理员登录,如果为管理员登录,则