SpringMVC参数绑定(从请求中接受参数)

时间:2022-08-08 19:35:14

参数绑定(从请求中接收参数)

1)默认类型:
在controller方法中可以有也可以没有,看自己需求随意添加. httpservletRqeust,httpServletResponse,httpSession,Model(ModelMap其实就是Mode的一个子类
,一般用的不多)
2)基本类型:string,double,float,integer,long.boolean
3)pojo类型:页面上input框的name属性值必须要等于pojo的属性名称
4)vo类型:页面上input框的name属性值必须要等于vo中的属性.属性.属性....
5)自定义转换器converter:
作用:由于springMvc无法将string自动转换成date所以需要自己手动编写类型转换器
需要编写一个类实现Converter接口
在springMvc.xml中配置自定义转换器
在springMvc.xml中将自定义转换器配置到注解驱动上

下面是自己练习的例子


(service和dao层略过,都是mybatis的内容)

package cn.com.controller;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import cn.com.po.Items;
import cn.com.service.ItemService;

@Controller
public class ItemController {
@Autowired
private ItemService itemServcie;

@RequestMapping("/list")
public ModelAndView getItemList() {
// 调用service层查询list
List<Items> itemsList = itemServcie.getItemsList();
// 获取一个ModelAndview实例对象
ModelAndView modelAndView = new ModelAndView();
// 将查询出来的list放入Model中
modelAndView.addObject("itemList", itemsList);
// 指定view视图
modelAndView.setViewName("itemList");
System.out.println("进来一个请求");
return modelAndView;
}

@RequestMapping("/itemEdit")
public String editItem(Integer id,Model model){
System.out.println("获取到的参数"+id);
Items item = itemServcie.getItemById(id);
model.addAttribute("item", item);
//editItem.jsp进行渲染(如果返回的是字符串,springMVC则将字符串解析为页面名称)
//这里页面名称没有写全,是因为在SpringMVC.xml配置文件中配置了头/WEB-INF/jsp/和尾巴.jsp
return "editItem";
}
@RequestMapping("/updateitem")
public String updateitem(Items items){//直接用pojo接受参数
//参数已经封装到items中,再添加一个时间信息
items.setCreatetime(new Date());
itemServcie.updateitem(items);
return "itemList";
}
}