SpringMVC 参数校验

概述

需要对Post请求的表单数据进行简单校验。

Maven 配置

  • Bean Validation API 1.1:
1
2
3
4
5
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
  • Hibernate Validator 5.0.1.Final:
1
2
3
4
5
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.0.1.Final</version>
</dependency>

Spring MVC

配置

在application-context.xml文件中加入下面一行:

1
<mvc:annotation-driven />
controller
  1. 在需要校验的model对象前面加上@Valid注解(javax.validation.Valid):
1
2
3
4
5
6
@RequestMapping(
value = "/v1/live/send/gift", method = RequestMethod.POST)
@Response
public WebResult requestSendGift(HttpServletRequest request, @Valid @ModelAttribute SendGiftForm sendGiftForm, BindingResult bindingResult) {
}
  1. 在controller方法里面加上参数判断:
1
2
3
if (bindingResult.hasErrors()) {
throw new IllegalArgumentException("request params must be not null.");
}
Validator Model

在需要校验的model字段前面加上注解(hibernate validator):

1
2
3
4
5
6
7
public class SendGiftForm {
@NotNull
private Long roomId;
@NotNull
private Long liveId;
}

参考链接:

Spring Form Validation

热评文章