spring-springmvc-mybatis整合笔记(5)——添加商品修改功能

本文详细记录了如何在Spring MVC和MyBatis整合的项目中实现商品修改功能,从功能需求、Service接口新增方法、Controller处理到@RequestMapping的使用,以及返回值类型如ModelAndView、String和void的场景解析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一 功能需求

在商品列表中点击需要修改的商品,跳转到商品修改页面,在该页面做商品的修改。

二 service接口新增方法

由于逆向工程已经生成了实现这一功能我们需要的方法,这里直接在service接口中新增方法:

    @Override
    public ItemsCustom findItemsById(int id) throws Exception {
        Items items = itemsMapper.selectByPrimaryKey(id);
        ItemsCustom itemsCustom = new ItemsCustom();
        BeanUtils.copyProperties(items,itemsCustom);
        return itemsCustom;
    }

    @Override
    public void updateItems(Integer id, ItemsCustom itemsCustom) throws Exception {

        /*
        对于关键业务的处理 以及对ID为空的校验
        空指针异常一定要杜绝!
         */
        itemsMapper.updateByPrimaryKeyWithBLOBs(itemsCustom);
    }

三 Controller新增方法

 @RequestMapping("/editItems")
    public String editItems(Model model, Integer id) throws Exception{
        ItemsCustom itemsCustom = itemsService.findItemsById(id);
        model.addAttribute("id",id);
        model.addAttribute("itemsCustom",itemsCustom);
        return "editItem";
    }

    //商品提交页面
    //itemsQueryVo是包装类型的pojo
    @RequestMapping("/editItemSubmit")
    public String editItemSubmit(Model model,Integer id,@ModelAttribute(value="itemsCustom") ItemsCustom itemsCustom) throws Exception
    {
        //进行数据回显
        model.addAttribute("id",id);
//        model.addAttribute("item",itemsCustom);


        itemsService.updateItems(id,itemsCustom);
        //请求转发
//        return "forward:queryItems.action";

        return "editItem";
        //重定向
//        return "redirect:queryItems.action";
    }

四 @RequestMapping

作用:

  • 窄化URL请求
  • 限制HTTP请求方法: 如@RequestMapping(value="/editItems",method={RequestMethod.POST, RequestMethod.GET})

五 方法返回值

1 ModelAndView 

直接返回一个视图,需要添加Object与ViewName

2 String

返回视图名称,可以在方法参数中定义model(相当于定义了Request)

  • 返回真正视图名称  
  • 重定向 浏览器中URL地址会发生改变,Request中携带的数据将不能带过去。
//重定向到商品查询列表
//return "redirect:queryItems.action";
  •  转发
    //页面转发
    return "forward:queryItems.action";

3 void

在方法上需要定义形参Request与Response

转发:

request.getRequestDispatcher("页面路径").forward(request, response);

重定向

response.sendRedirect("url")

通过response指定响应结果,例如响应json数据如下:

response.setCharacterEncoding("utf-8");
response.setContentType("application/json;charset=utf-8");
response.getWriter().write("json串");
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值