Skip to content

Instantly share code, notes, and snippets.

@sunwu51
Created May 14, 2019 08:00
Show Gist options
  • Save sunwu51/3d7054c034df5eaaac09a963f46ae4fc to your computer and use it in GitHub Desktop.
Save sunwu51/3d7054c034df5eaaac09a963f46ae4fc to your computer and use it in GitHub Desktop.

SpringBoot Rest接口

1 请求参数的接收

从客户端来看请求参数四种形式:路径参数、查询字符串、表单参数、json参数、其他参数。 从服务端来看请求参数分为

  • RequestParam 对应查询参数和表单参数
  • PathVariable 对应路径参数
  • RequestBody 对应Json/xml等内容参数
  • RequestHeader 对应请求头中参数
  • CookieValue 对应cookie参数
    //----1 路径参数
    @GetMapping("/path/{id}")
    public String path(@PathVariable("id")int id){
        return "id is "+id;
    }
    //---2 查询参数
    @GetMapping("/querystring")
    public String querystring(int id){
        return "id is "+id;
    }
    //直接用对象可以映射参数(对象需要有get/set方法)
    @GetMapping("/querystring2")
    public String querystring2(Item item){
        return "id is "+item.id;
    }
    //---3 表单参数
    @PostMapping("/form")
    public String form(int id){
        return "id is "+id;
    }
    //直接用对象接收参数也可以直接映射(对象需要有get/set方法)
    @PostMapping("/form2")
    public String form2(Item item){
        return "id is "+item.id;
    }
    //---4 json参数
    @PostMapping("/json")
    public String json(@RequestBody Item item){
        return "id is "+item.id+",name is "+item.name;
    }

小结:

  • 从后台
  • 如参数类型无法转换成功(int但传了string),会报400。
  • !!!对象映射的对象,一定要有set和get方法,否则映射失败。
  • 如果函数参数名想和传递的参数名不一样可以用@RequestParam,详情往下看。
  • 数组参数使用String[] arr进行接收。

2 请求参数的校验

直接利用@RequestParam注解进行简单必需性校验

//request默认是true,如果手动改成了false,则会被设为null,defaultValue是没有传的时候的默认值
//!!注 int类型没有null值,所以如果int参数是非必须的,一定要设defaultValue

@RequestParm(value="id",request=false,defaultValue="11")int id

使用@Size @Max @Pattern等注解进行进一步校验,一定要在当前Controller类上加@Validated否则上述注解不生效。

@Max(33) int id

@Size(min = 6,max=100)@Pattern(regexp = "\\d+")

使用对象映射的直接在对象上添加上述注解,同样需要Controller类上添加@Validated才会进行校验。

@Data
class Item {
    int id;
    @NotNull
    @Size(min=3)
    String name;
}

3 响应参数

分为Rest接口倾向的 字符串Json以及MVC倾向的view

//########################################
//整个类添加@RestController注解后
// 字符串
public String s1(){return "123";}
// json
public Item j1(){return new Item();}
public Map j2(){return new HashMap();}
//########################################
//不添加@RestController注解
// 字符串
public ResponseEntity<String></String> s1(){
    return new ResponseEntity<>("123",HttpStatus.OK);
}
// json
public ResponseEntity<Item> j1(){
    return new ResponseEntity<>(new Item(),HttpStatus.OK);
}
public ResponseEntity<Map> j2(){
    return new ResponseEntity<>(new HashMap(),HttpStatus.OK);
}
// view
public ModelAndView hello(String name) {
    HashMap<String,Object> map=new HashMap<>();
    map.put("name",name);
    return new ModelAndView("hello",map);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment