@PathVariable绑定URI模板变量值
@PathVariable是用来获得请求url中的动态参数的
@PathVariable用于将请求URL中的模板变量映射到功能处理方法的参数上。//通俗来讲配置url和方法的一个关系
@RequestMapping("/item/{itemId}")
@ResponseBody
private TbItem getItemById(@PathVariable Long itemId) {
TbItem tbItem = itemService.getItemById(itemId);
return tbItem;}
在SpringMVC中获得参数主要有两种方法:
第一种是request.getParameter("name"),例如:
@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;}
第二种是用注解@RequestParam直接获取
@RequestParam注解主要的参数:
value:参数名字,即入参的请求参数名字,如username表示请求的参数区中的名字为username的参数的值将传入;
required:是否必须,默认是true,表示请求中一定要有相应的参数,否则将报404错误码;
defaultValue:默认值,表示如果请求中没有同名参数时的默认值。
@RequestMapping("/itemEdit")
public String queryItemById(@RequestParam(value = "itemId", required = true, defaultValue = "1") Integer id,
ModelMap modelMap) {
// 根据id查询商品数据
Item item = this.itemService.queryItemById(id);
// 把商品数据放在模型中
modelMap.addAttribute("item", item);
return "itemEdit";}