SpringMVC中使用RestFul风格

  1. 传统风格

    1
    2
    3
    4
    5
    6
    7
    //http://localhost:8080/4/add?a=1&b=2
    @RequestMapping("/add1")
    public String test1(int a, int b, Model model){
    int res = a + b;
    model.addAttribute("msg","结果为"+res);
    return "test";
    }
  2. RestFul风格

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    // http://localhost:8080/4/add/a/b
    @RequestMapping("/add2/{a}/{b}")
    public String test2(@PathVariable int a, @PathVariable int b, Model model){
    int res = a + b;
    model.addAttribute("msg","结果为"+res);
    return "test";
    }
    // 或者
    @GetMapping("/add3/{a}/{b}")
    public String test3(@PathVariable int a, @PathVariable int b, Model model){
    int res = a + b;
    model.addAttribute("msg","结果为"+res);
    return "test";
    }

    使用好处:

    • 简洁: 使路径变得更加简洁
    • 高效: 获得参数更加方便,框架会自动进行类型转换
    • 安全:
      • 不会暴露变量名
      • 通过路径变量的类型可以约束访问参数,如果类型不一样,则访问不到对应的请求方法,而不会是参数转换失败