最近小编在研究关于springboot的一些东西,昨天在官网上看到个关于校验参数的框架,感觉不错,可以省略不少代码,来做个笔记~首先在pom中引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
然后搞一个实体类:
package com.robot.transformers.validateData;
import lombok.Data;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Size;
@Data
public class DataValidate {
@NotEmpty(message = "请填写用户名")
private String username;
@NotEmpty(message = "请填写密码")
@Size(min = 6, message = "密码长度最小为6位")
private String password;
}
鼓捣一个页面出来:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>表单</title>
</head>
<body>
<form method="get" action="login">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" value="提交">
</form>
</body>
</html>
测试一下:
package com.robot.transformers.controllers;
import com.robot.transformers.common.BaseResult;
import com.robot.transformers.validateData.DataValidate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Slf4j
@Controller
@RequestMapping("/validate")
public class TestValidateController {
@RequestMapping("/index")
public String index () {
return "testValidate/index";
}
@RequestMapping("login")
@ResponseBody
public BaseResult login (@Validated DataValidate dataValidate, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
for (ObjectError error : bindingResult.getAllErrors()) {
return BaseResult.error(false, error.getDefaultMessage());
}
}
return BaseResult.ok(true, "", "");
}
}
把项目运行起来进入页面输入错误信息,你会看到返回的错误的,前端收到信息做对应处理就可以
BaseResult是个返回值类型,这个可以不用粘我的,如果有想用的可以评论在下方~