介绍

在Spring MVC框架中,获得请求参数的方式有好几种,Controller类的方法的参数也是由Spring容器负责注入的。自动按反射的方式进行注入的。这里都是修改Controller类实现案例

1.直接使用方法参数

@RequestMapping("demo01")
public String demo01(String goodsName){
    System.out.println("demo01 is ran…"+goodsName);
    return "index";
}

2.使用对象来接收方法参数

@RequestMapping("demo02")
public String demo02(Goods goods){
    System.out.println("demo02 is ran…");
    System.out.println("demo02:goods.getGoodsId()="+goods.getGoodsId());
    System.out.println("demo02:goods.getGoodsName()="+goods.getGoodsName());
    return "index";
}

3.直接使用ServletAPI

@RequestMapping("demo03")
public String demo03(HttpServletRequest request){
    System.out.println("demo03 is ran…");
    System.out.println("demo03:goodsName="+request.getParameter("goodsName"));
    System.out.println("demo03:goodsId="+request.getParameter("goodsId"));
    return "index";
}

4.当请求参数的名称与方法名称的参数不一致

@RequestMapping("demo04")
public String demo04(@RequestParam("goodsName") String name){
    System.out.println("demo04 is ran…");
    System.out.println("demo04:goodsName="+name);
    return "index";
}

5.直接从URL地址上获取请求参数

@RequestMapping("demo05/{goodsId}/{goodsName}.xhtml")
public String demo05(@PathVariable int goodsId, @PathVariable String goodsName){
    System.out.println("demo05 is ran…");
    System.out.println("demo05:goodsId="+goodsId);
    System.out.println("demo05:goodsName="+goodsName);
    return "index";
}