43SpringMVC - 参数绑定(默认支持的参数类型)
需求
打开商品编辑页面,展示商品信息。
- 编辑商品信息,首先要显示商品详情
- 需要根据商品id查询商品信息,然后展示到页面。
- 请求的url:/itemEdit.action
- 参数:id(商品id)
- 响应结果:商品编辑页面,展示商品详细信息。
ItemService接口
编写ItemService接口如下图:
ItemServiceImpl实现类
@Override
public Item queryItemById(int id) {
Item item = this.itemMapper.selectByPrimaryKey(id);
return item;
}
ItemController
页面点击修改按钮,发起请求
http: // 127.0.0.1:8080/springmvc-web/itemEdit.action?id=1
需要从请求的参数中把请求的id取出来。
Id包含在Request对象中。可以从Request对象中取id。
想获得Request对象只需要在Controller方法的形参中添加一个参数即可。Springmvc框架会自动把Request对象传递给方法。
/**
* 根据id查询商品
*
* @param request
* @return
*/
@RequestMapping("/itemEdit")
public ModelAndView queryItemById(HttpServletRequest request) {
// 从request中获取请求参数
String strId = request.getParameter("id");
Integer id = Integer.valueOf(strId);
// 根据id查询商品数据
Item item = this.itemService.queryItemById(id);
// 把结果传递给页面
ModelAndView modelAndView = new ModelAndView();
// 把商品数据放在模型中
modelAndView.addObject("item", item);
// 设置逻辑视图
modelAndView.setViewName("itemEdit");
return modelAndView;
}
默认支持的参数类型
处理器形参中添加如下类型的参数处理适配器会默认识别并进行赋值。
HttpServletRequest: 通过request对象获取请求信息
HttpServletResponse: 通过response处理响应信息
HttpSession: 通过session对象得到session中存放的对象