在spring-bootrestapi中传递和验证RequestParam

栏目: Java · 发布时间: 7年前

内容简介:@RequestParam将方法参数绑定到Web请求参数,语法:@RequestParam <数据类型> <变量名称>;代码案例:

@RequestParam将方法参数绑定到Web请求参数,语法:

@RequestParam <数据类型> <变量名称>;

代码案例:

@RestController
@RequestMapping("/api")
@Validated
public class HelloWorldController {

   
   @GetMapping("/hello")
   public ResponseEntity<?> sayHello(
         @RequestParam @Size(min= 1, max = 5, message =
 "firstname length must be between 1 and 5") String firstname,
         @RequestParam String middlename,
         @RequestParam(required = false) String lastname){
      /* check lastname value */
      lastname = lastname != null ? lastname : "{lastname-is-optional}";
      return ResponseEntity.ok("Hello " + firstname + " " + middlename + " " + lastname);
   }
}
  • @Validated  - 对控制器的每个方法执行验证(如果有)。
  • @RequestParam  - 在变量中接受Web请求参数。( 注意 :所有使用 @RequestParam 注释的变量接受的请求参数都是强制对应的,除非该参数设置 required = false  @RequestParam(required = false)
  • javax.validation.constraints@Size 用于验证请求参数的长度,不符合条件将抛出   ConstraintViolationException
  • @RequestParam String middlename,:接受变量 middlename中的 强制对应 参数。如果请求中不存在参数,则spring将抛出   MissingServletRequestParameterException
  •  @RequestParam(required = false) String lastname):接受变量 lastname中的 可选 参数。

如果结合Swagger的API注释,你的代码如下:

@ApiOperation(value = "")
@RequestMapping(method = GET, value = "/customcollection/{id}/data")
public Iterable<CustomeType> getData(@ApiParam(value = "The identifier of the time series.")
                            @PathVariable String id,
                            @ApiParam(name = "startDate", value = "start date", defaultValue = "")
                            @RequestParam("startDate") String startDate,
                            @ApiParam(name = "endDate", value = "end date", defaultValue = "")
                            @RequestParam("endDate") String endDate)

其中ApiParam是swagger的参数,RequestParam是REST API,如果使用模型对象替代一个个RequestParam,则更加使得代码精简,然后使用 JSR 303:Bean Validation 对模型对象中字段进行校验:

public class Person {
   @NotNull
   private int id;

   @NotBlank
   @Size(min = 1, max = 20)
   private String firstName;

   @NotBlank
   @Pattern(regexp ="[SOME REGULAR EXPRESSION]")
   private String lastName;

   @Min(0)
   @Max(100)
   private int age;

   //... Constructor, getters, setters, ...
}

使用Swagger和SpringFox文档化Spring Boot REST API

Spring Boot


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Mathematica Cookbook

Mathematica Cookbook

Sal Mangano / O'Reilly Media / 2009 / GBP 51.99

As the leading software application for symbolic mathematics, Mathematica is standard in many environments that rely on math, such as science, engineering, financial analysis, software development, an......一起来看看 《Mathematica Cookbook》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具