Spring MVC 单车管理:增删改查功能实现
package com.bike.web;
import com.bike.dto.JsonResult;
import com.bike.dto.Page;
import com.bike.pojo.Bike;
import com.bike.pojo.Category;
import com.bike.service.BikeService;
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 org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
/**
 * 单车控制器,处理与单车相关的请求
 */
@Controller
@RequestMapping('/bike')
public class BikeController {
    @Autowired
    private BikeService bikeService;
    @Autowired
    private CategoryService categoryService;
    //跳转到 bike管理页面
    @RequestMapping('/bikeManage')
    public String bikeManage(){
        return 'bike';
    }
    /**
     * 添加或更新单车信息
     * @param bikeIcon 单车图标
     * @param bike 单车信息
     * @param request HTTP 请求
     * @param bCount 单车数量
     * @return 操作结果
     */
    @RequestMapping(value = '/addOrUpdate',method = RequestMethod.POST)
    @ResponseBody
    public JsonResult addOrUpdate(MultipartFile bikeIcon, Bike bike, HttpServletRequest request,Integer bCount){
        if(bCount != null) return bikeService.add(bikeIcon,bike,request,bCount);
            return bikeService.update(bikeIcon,bike,request);
    }
    /**
     * 分页获取所有单车信息
     * @param page 当前页码
     * @param rows 每页显示条数
     * @return 分页数据
     */
    @RequestMapping('/showAll')
    @ResponseBody
    public Page<Bike> show(Integer page, Integer rows){
        return bikeService.findAllToPage(page,rows);
    }
    /**
     * 删除单车信息
     * @param bids 单车 ID,多个 ID 用逗号分隔
     * @param cids 分类 ID,多个 ID 用逗号分隔
     * @return 操作结果
     */
    @RequestMapping(value = '/remove',method = RequestMethod.POST)
    @ResponseBody
    public JsonResult remove(String bids,String cids){
        return bikeService.deleteById(bids,cids);
    }
    /**
     * 根据 ID 获取单车信息
     * @param bid 单车 ID
     * @return 单车信息
     */
    @RequestMapping('/loadForm')
    @ResponseBody
    public Bike loadForm(Integer bid){
        return bikeService.findById(bid);
    }
    /**
     * 获取所有单车分类信息
     * @return 单车分类列表
     */
    @RequestMapping(value = '/loadCategory',method = RequestMethod.POST)
    @ResponseBody
    public List<Category> loadCategory(){
        return categoryService.findAll();
    }
}
代码分析
这段代码定义了一个名为 BikeController 的控制器类,用于处理与单车相关的 HTTP 请求。
核心代码
addOrUpdate()方法: 负责处理添加或更新单车信息的请求。showAll()方法: 负责分页获取所有单车信息。remove()方法: 负责删除指定 ID 的单车信息。loadForm()方法: 负责根据 ID 获取单车信息,用于回显表单数据。
这些方法都依赖于 BikeService 和 CategoryService 来完成具体的业务逻辑。
原文地址: https://www.cveoy.top/t/topic/iWh 著作权归作者所有。请勿转载和采集!