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

xiaoxiao2021-02-28  27

一 功能需求

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

二 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串");
转载请注明原文地址: https://www.6miu.com/read-2628569.html

最新回复(0)