本文功能是在SpringBoot2.X之旅,开篇 hello world(Web Project)基础框架之上实现的
一、添加lombok依赖
1、pom.xml添加lombok依赖包,使@Slf4j、@Data注解生效(如果idea没有按装lombok插件,请先安装插件)
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.1.3.RELEASE
com.cobra
webdemo
0.0.1-SNAPSHOT
webdemo
Demo project for Spring Boot
1.8
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
org.projectlombok
lombok
org.springframework.boot
spring-boot-maven-plugin
2、鼠标右键,重新加载依赖:
二、Coding:
1、在controller包下新建包form、新建类UserForm
package com.cobra.webdemo.controller.form;
import lombok.Data;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
/**
* @Author: Baron
* @Description:
* @Date: Created in 2019/3/6 23:18
*/
@Data
public class UserForm {
@NotBlank(message = "名字不能不填!")
private String username;
@NotBlank(message = "密码不能不填!")
private String password;
@NotBlank(message = "昵称不能不填!")
private String nickname;
@NotNull(message = "年龄不能为空!")
@Min(value = 0, message = "年龄不能小了0!")
@Max(value = 150, message = "年龄不能大于200岁!")
private Integer age;
}
2、在controller包下新建类
package com.cobra.webdemo.controller;
import com.cobra.webdemo.controller.form.UserForm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
import java.util.List;
/**
* @Author: Baron
* @Description:
* @Date: Created in 2019/3/6 23:27
*/
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
@PostMapping("/register")
public String register(@Valid UserForm userForm, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
List errors = bindingResult.getAllErrors();
String error = "";
for (ObjectError str:errors) {
error += str.getDefaultMessage();
}
log.error(error);
return error;
}
log.info("参数校验通过!");
return "参数校验通过!";
}
}
三、测试打开postman,发送post请求:
四、小结
1、@Valid注解入参
@Notnull参数不为null
@NotEmpty参数不为null、不为""
@NotBlank参数不为null、不为""、不为" "
@Min最小值
@Max最大值
属性的校验不要忘了加message的值,
例:@NotNull(message = "年龄不能为空!")、
@Min(value = 0, message = "年龄不能小了0!")
五、补充:参数获取
@PathVariable,一般用于Restful风格的请求(localhost:8090/user/book/789456ef)
@RequestParam,一般用于传统的带参url请求(localhost:8090/user/book/?id=789456ef)
@GetMapping("/book/{id}")
public String getBook(@PathVariable("id") String id) {
return null;
}
@GetMapping("/book")
public String getOneBook(@RequestParam("id") String id) {
return null;
}