Spring Boot实战:构建RESTful API实现分类管理
package com.bike.web;
import com.bike.dto.JsonResult;
import com.bike.enums.ResultEnum;
import com.bike.pojo.Category;
import com.bike.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
@Controller
@RequestMapping('/category')
public class CategoryController {
@Autowired
private CategoryService categoryService;
//跳转到category页面
@RequestMapping('/categoryManage')
public String categoryMange(){
return 'category';
}
//显示所有分类
@RequestMapping('/showAll')
@ResponseBody
public List<Category> showAll(){
return categoryService.findAll();
}
//添加或更新分类 addOrUpdate
@RequestMapping(value = '/addOrUpdate',method = RequestMethod.POST)
@ResponseBody
public JsonResult addOrUpdate(Category category){
if(category == null) return new JsonResult(false, ResultEnum.SYSTEM_ERROR);
if(category.getCid() == null ) return categoryService.add(category);
return categoryService.update(category);
}
//删除分类
@RequestMapping(value = '/remove',method = RequestMethod.POST)
@ResponseBody
public JsonResult remove(Integer cid){
return categoryService.deleteById(cid);
}
//回显分类的表单数据
@RequestMapping('/loadForm')
@ResponseBody
public Category loadForm(Integer cid){
return categoryService.findById(cid);
}
}
代码分析
以上代码是一个基于Spring框架的Java类,作为一个控制器(Controller),用于处理与分类(Category)相关的请求,并提供RESTful API接口。
主要功能:
- 跳转到category页面:
/category/categoryManage, 返回'category'字符串, 可能是跳转到名为category的模板页面。 - 显示所有分类:
/category/showAll, 返回所有分类的JSON列表。 - 添加或更新分类:
/category/addOrUpdate(POST), 根据是否有cid判断是添加还是更新操作, 返回操作结果的JSON。 - 删除分类:
/category/remove(POST), 根据cid删除分类, 返回操作结果的JSON。 - 回显分类的表单数据:
/category/loadForm, 根据cid查询分类信息, 返回分类对象的JSON,用于前端编辑。
核心代码分析:
addOrUpdate()方法:- 接收一个
Category对象作为参数。 - 如果
category为空,返回系统错误。 - 如果
category的cid为空,调用categoryService.add()方法添加分类。 - 否则,调用
categoryService.update()方法更新分类。 - 返回一个
JsonResult对象,表示操作结果。
- 接收一个
remove()方法:- 接收一个
Integer类型的cid参数。 - 调用
categoryService.deleteById()方法删除对应分类。 - 返回一个
JsonResult对象,表示操作结果。
- 接收一个
loadForm()方法:- 接收一个
Integer类型的cid参数。 - 调用
categoryService.findById()方法查询对应分类信息。 - 返回一个
Category对象。
- 接收一个
用法流程:
- 添加分类: 发送POST请求到
/category/addOrUpdate,携带Category对象的参数(cid为空)。 - 更新分类: 发送POST请求到
/category/addOrUpdate,携带Category对象的参数(cid不为空)。 - 删除分类: 发送POST请求到
/category/remove,携带cid参数。 - 回显分类表单数据: 发送GET请求到
/category/loadForm,携带cid参数。
注意:
- 这段代码只是一个控制器类的片段,需要配合相应的服务类、数据访问层等才能完整实现分类管理功能。
- 代码中使用了Spring MVC框架的注解,例如
@Controller、@RequestMapping、@ResponseBody等,用于简化Web开发。
原文地址: http://www.cveoy.top/t/topic/i28 著作权归作者所有。请勿转载和采集!