上个文章整合了SSM框架,现在我们来看看在Controller层我们的处理器方法怎么对前端传过来的参数进行绑定。(这里演示的是同步开发)
默认的参数绑定
默认的参数绑定,我们只需要在方法的参数接收HttpServletRequest、HttpServletResponse、HttpSession
需求:在我们修改商品信息的时候,需要根据id查询商品信息
- 修改jsp页面中的超链接
<td><a href="${pageContext.request.contextPath }/updateItemUI?id=${item.id}">修改</a></td>
- 编写controller
@RequestMapping("/updateItemUI")
public ModelAndView updateItemUI(HttpServletRequest request){
String id = request.getParameter("id");
Item item = itemService.findItemById(Integer.valueOf(id));
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject(item);
modelAndView.setViewName("editItem");
return modelAndView;
}
也可以下面这种方式(不推荐使用原生对象,因为这样就没有使用springmvc相关的功能):
@RequestMapping("/updateItemUI")
public void updateItemUI(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String id = request.getParameter("id");
Item item = itemService.findItemById(Integer.valueOf(id));
request.setAttribute("item",item);
request.getRequestDispatcher("/WEB-INF/views/editItem.jsp").forward(request,response);
}
绑定简单类型
我们可以在处理器方法声明需要接收的参数,当请求参数的名字和处理器形参一致的时候,springmvc进行自动的参数绑定。
比如:
整型 Integer int
Long long
字符串 String
单精度 Float float
双精度 Double double
布尔类型 Boolean boolean 请求参数传递 true或者false 1或0
@RequestMapping("/updateItemUI")
public ModelAndView updateItemUI(Integer id){
Item item = itemService.findItemById(id);
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("item",item);
modelAndView.setViewName("editItem");
return modelAndView;
}
使用@RequestParam
@RequestParam注解中有三个属性。分别是value、required(默认true)、defaultValue。
设置value值可以帮我们处理前后端参数不一致,设置required为true时不传这个参数会报错,如果没有设置参数也可以设置一个默认的值
@RequestMapping("/updateItemUI")
public ModelAndView updateItemUI(@RequestParam("id") Integer itemId){
Item item = itemService.findItemById(itemId);
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("item",item);
modelAndView.setViewName("editItem");
return modelAndView;
}
注意:这里的itemId和前端中的id不一致,使用了@RequestParam进行了处理
使用Model/ModelMap
我们可以直接在处理器方法上声明model,它实际上是一个map集合,我们将要返回的数据放入这个map集合,返回一个字符串,这个字符串实际上就是视图的名字。这个实际上是处理器适配器自动帮我们创建了一个ModelAndView对象返回给前端控制器
简图:
@RequestMapping("/queryItemList")
public String queryItemList(Model model){
List<Item> list = itemService.findItemAll();
model.addAttribute("list",list);
return "itemList";
}
绑定pojo类型
需求:在我们修改完商品信息之后,点击提交,更新数据
@RequestMapping("/updateItem")
public String updateItem(Item item){
itemService.updateItem(item);
return "success";
}
绑定包装的pojo类型
- 编写dto
public class QueryDto {
private Item item;
public Item getItem() {
return item;
}
public void setItem(Item item) {
this.item = item;
}
}
- 编写controller
@RequestMapping("/queryItemByWhere")
public String queryItemByWhere(QueryDto queryDto){
System.out.println(queryDto);
return "success";
}
注意:这里前端必须传递的参数为item.属性
绑定集合或者数组
注意:通过测试可以发现list集合不能直接声明在方法的参数中,需要用Javabean包起来
可以支持数组绑定:
@RequestMapping("/queryItemByWhere")
public String queryItemByWhere(Integer[] ids){
System.out.println(ids);
return "success";
}