springmvc通过HttpServletRequest进行参数传递

@RequestMapping("/itemEdit")
    public String itemEdit(HttpServletRequest request, Model model) {
        //从Request中取id
        String strId = request.getParameter("id");
        Integer id = null;
        //如果id有值则转换成int类型
        if (strId != null && !"".equals(strId)) {
            id = new Integer(strId);
        } else {
            //出错
            return null;
        }
        Items items = itemService.getItemById(id);
        //创建ModelAndView
        //ModelAndView modelAndView = new ModelAndView();
        //向jsp传递数据
        //modelAndView.addObject("item", items);
        model.addAttribute("item", items);
        //设置跳转的jsp页面
        //modelAndView.setViewName("editItem");
        //return modelAndView;
        return "editItem";
    }

要根据id查询商品数据,需要从请求的参数中把请求的id取出来。Id应该包含在Request对象中。可以从Request对象中取id

 

如果想获得Request对象只需要在Controller方法的形参中添加一个参数即可。Springmvc框架会自动把Request对象传递给方法。

 

1.1.1 默认支持的参数类型

 

处理器形参中添加如下类型的参数处理适配器会默认识别并进行赋值。

 

1.1.1.1 HttpServletRequest

 

通过request对象获取请求信息

 

1.1.1.2 HttpServletResponse

 

通过response处理响应信息

 

1.1.1.3 HttpSession

 

通过session对象得到session中存放的对象

 

1.1.1.4 Model/ModelMap

 

ModelMapModel接口的实现类,通过ModelModelMap向页面传递数据,如下:

 

//调用service查询商品信息
Items item = itemService.findItemById(id);
model.addAttribute("item", item);

 

页面通过${item.XXXX}获取item对象的属性值。

使用ModelModelMap的效果一样,如果直接使用Modelspringmvc会实例化ModelMap

 

如果使用Model则可以不使用ModelAndView对象,Model对象可以向页面传递数据,View对象则可以使用String返回值替代。不管是Model还是ModelAndView,
其本质都是使用Request对象向jsp传递数据。

 

 

 

 

 

原文地址:https://www.cnblogs.com/niwotaxuexiba/p/10187450.html