1. @RequestParam 注解
- 将请求的查询参数绑定到控制器方法的参数上
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RequestParam {
@AliasFor("name")
String value() default "";
@AliasFor("value")
String name() default "";
boolean required() default true;
String defaultValue() default ValueConstants.DEFAULT_NONE;
}
name, value 属性:
指定要绑定的请求参数名
required 属性:required
默认为true, 若不传该参数,则会抛出异常
defaultValue 属性
当请求中没有提供相应参数时,使用此默认值
1.2 示例
/**
* RUL: http://localhost:8080/web/params?id=1001&code=AAA
*/
@RequestMapping("/params")
public String params(@RequestParam("id") String id, @RequestParam("code") String orderCode,
@RequestParam(value = "name", defaultValue = "Tinyspot") String name,
@RequestParam(value = "field", required = false) List fields) {
return "";
}
2. 参数校验
2.1 引入 Hibernate Validator 包
org.hibernate.validator hibernate-validatororg.hibernate hibernate-entitymanager

非空校验通常会自动启用,因为 Spring Boot 自动配置会扫描并注册 javax.validation.Validator 的实现
import javax.validation.Valid;
来自

2.2 示例
- 在实体类的属性上添加非空注解
@Data
public class UserDTO {
@NotBlank(message = "name不能为空")
private String name;
@NotNull(message = "age不能为null")
private Integer age;
}
- 在请求参数前加上 @Valid 注解进行校验
import javax.validation.Valid;
@RestController
@RequestMapping("/web")
public class ConcreteController {
@RequestMapping("/greeting")
public UserDTO greeting(UserDTO userDTO) {
greetService.greeting(new UserDTO("Tinyspot", 20), "local");
return new UserDTO("bob", 22);
}
@RequestMapping("/greeting2")
public UserDTO greeting2(@Valid @RequestBody UserDTO userDTO) {
return userDTO;
}
}
@Valid 是 Spring 支持的注解,它会触发对带有校验注解的对象进行验证
@NotNull 表示字段不能为 null
Index
姓名:
年龄:
2.3 参数校验异常捕获


Resolved [org.springframework.web.bind.MethodArgumentNotValidException: Validation failed for argument [0] in public com.example.concrete.common.domain.UserDTO com.example.concrete.starter.controller.ConcreteController.greeting2(com.example.concrete.common.domain.UserDTO):
[Field error in object 'userDTO' on field 'name': rejected value []; codes [NotBlank.userDTO.name,NotBlank.name,NotBlank.java.lang.String,NotBlank];
arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [userDTO.name,name]; arguments []; default message [name]]; default message [name不能为空]] ]
【信息由网络或者个人提供,如有涉及版权请联系COOY资源网邮箱处理】
© 版权声明
部分内容为互联网分享,若有侵权请联系站长删除。
THE END
暂无评论内容