Spring校验@RequestParams和@PathVariables参数

我们在写Rest API接口时候会用到很多的@RequestParam和@PathVariable进行参数的传递,但是在校验的时候,不像使用@RequestBody那样的直接写在实体类中,我们这篇文章讲解一下如何去校验这些参数。

依赖配置


  • 要使用Java Validation API,我们必须添加validation-api依赖项:
  1. <dependency>

  2. <groupId>javax.validation</groupId>

  3. <artifactId>validation-api</artifactId>

  4. <version>2.0.1.Final</version>

  5. </dependency>

  • 通过添加@Validated注解来启用控制器中的@RequestParams和@PathVariables的验证:
  1. @RestController

  2. @RequestMapping("/")

  3. @Validated

  4. public class Controller {

  5. // ...

  6. }

校验@RequestParam


  • 我们将数字作为请求参数传递给控制器方法
  1. @GetMapping("/name-for-day")

  2. public String getNameOfDayByNumber(@RequestParam Integer dayOfWeek) {

  3. // ...

  4. }

  • 我们保证dayOfWeek的值在1到7之间,我们使用@Min和@Max注解
  1. @GetMapping("/name-for-day")

  2. public String getNameOfDayByNumber(@RequestParam @Min(1) @Max(7) Integer dayOfWeek) {

  3. // ...

  4. }

任何与这些条件不匹配的请求都将返回HTTP状态500,并显示默认错误消息。

如果我们尝试调用http://localhost:8080/name-for-day?dayOfWeek=24这将返回以下响应信息:

  1. There was an unexpected error (type=Internal Server Error, status=500).

  2. getNameOfDayByNumber.dayOfWeek: must be less than or equal to 7

当然我们也可以在@Min和@Max注解后面加上 message参数进行修改默认的返回信息。

校验@PathVariable


和校验@RequestParam一样,我们可以使用javax.validation.constraints包中的注解来验证@PathVariable。

  • 验证String参数不是空且长度小于或等于10
  1. @GetMapping("/valid-name/{name}")

  2. public void test(@PathVariable("name") @NotBlank @Size(max = 10) String username) {

  3. // ...

  4. }

  • 任何名称参数超过10个字符的请求都会导致以下错误消息:
  1. There was an unexpected error (type=Internal Server Error, status=500).

  2. createUser.name:size must be between 0 and 10

通过在@Size注解中设置message参数,可以覆盖默认消息。

其实我们可以看到校验@RequestParam和@PathVariable参数和我们校验@RequestBody方式一致,只不过一个是写在了实体中,一个写在了外部,当然我们也可以将@RequestParam的参数写入到实体类中,进行使用@RequestParam注解进行引入,比如我们使用一个分页的实例

  • 分页实体类
  1. /**

  2. * Licensed to the Apache Software Foundation (ASF) under one

  3. * or more contributor license agreements.  See the NOTICE file

  4. * distributed with this work for additional information

  5. * regarding copyright ownership.  The ASF licenses this file

  6. * to you under the Apache License, Version 2.0 (the

  7. * "License"); you may not use this file except in compliance

  8. * with the License.  You may obtain a copy of the License at

  9. * <p>

  10. * http://www.apache.org/licenses/LICENSE-2.0

  11. * <p>

  12. * Unless required by applicable law or agreed to in writing, software

  13. * distributed under the License is distributed on an "AS IS" BASIS,

  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

  15. * See the License for the specific language governing permissions and

  16. * limitations under the License.

  17. */

  18. package com.zhuanqb.param.page;

  19. import lombok.AllArgsConstructor;

  20. import lombok.Data;

  21. import lombok.NoArgsConstructor;

  22. import lombok.ToString;

  23. import org.hibernate.validator.constraints.NotBlank;

  24. import org.hibernate.validator.constraints.NotEmpty;

  25. import javax.validation.constraints.Max;

  26. import javax.validation.constraints.Min;

  27. import javax.validation.constraints.NotNull;

  28. /**

  29. * PageParam <br/>

  30. * 描述 : PageParam <br/>

  31. * 作者 : qianmoQ <br/>

  32. * 版本 : 1.0 <br/>

  33. * 创建时间 : 2018-09-23 下午7:40 <br/>

  34. * 联系作者 : <a href="mailTo:shichengoooo@163.com">qianmoQ</a>

  35. */

  36. @Data

  37. @ToString

  38. @NoArgsConstructor

  39. @AllArgsConstructor

  40. public class PageParam {

  41. @NotNull(message = "每页数据显示数量不能为空")

  42. @Min(value = 5)

  43. @Max(value = 100)

  44. private Integer size; // 每页数量

  45. @NotNull(message = "当前页显示数量不能为空")

  46. @Min(value = 1)

  47. @Max(value = Integer.MAX_VALUE)

  48. private Integer page; // 当前页数

  49. private Boolean flag = true;

  50. }

  • @RequestParam调用方式
  1. @GetMapping(value = "list")

  2. public CommonResponseModel findAll(@Validated PageParam param) {

  3. ...

  4. }

这样的话可以使我们的校验定制化更加简单。

本文分享自微信公众号 - Spring中文网(china-spring-all)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。

评论

暂无评论