【发布时间】:2020-05-23 08:02:06
【问题描述】:
请检查下面的示例并帮助我。
我需要验证 productName、Description、Size 和 price,如果没有传递任何值,则需要通过实体中提供的消息获得错误响应。
实体:
Entity
@Table(name="products")
public class Products implements Serializable{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
int productID;
@NotNull(message="Name cannot be missing or empty")
@Size(min=3, message="Name should have atleast 3 characters")
String productName;
@NotEmpty(message = "Please provide a description")
String description;
@NotNull(message = "Please provide a price")
@Digits(integer = 10 /*precision*/, fraction = 2 /*scale*/)
float price;
@NotNull(message = "Size must not be empty")
char size;
}
控制者:
@RequestMapping(value = "/saveProduct" ,method =RequestMethod.POST, produces = "application/json")
public ResponseEntity<Object> saveProductController(@Valid @RequestBody Products prod) throws ProdDetailsNotFound, ProductAlreadyPresentException {
System.out.println("Save");
return new ResponseEntity<Object>(prodServ.saveProductService(prod), HttpStatus.CREATED);
}
ControllerAdvice:
@ControllerAdvice
@RestController
public class GlobalControllerAdvice extends ResponseEntityExceptionHandler{
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
HttpHeaders headers,
HttpStatus status, WebRequest request) {
Map<String, Object> body = new LinkedHashMap<>();
body.put("timestamp", new Date());
body.put("status", status.value());
//Get all errors
List<String> errors = ex.getBindingResult()
.getFieldErrors()
.stream()
.map(x -> x.getDefaultMessage())
.collect(Collectors.toList());
body.put("errors", errors);
return new ResponseEntity<>(body, headers, status);
}
}
在 Postman 中传递的 JSON:
{
"productName":"aa",
"description": ,
"price":"200.00" ,
"size":
}
没有给出错误响应。
当我在下面尝试时
{
"productName":"aa",
"description": "asdasd",
"price":"200.00" ,
"size": "L"
}
我得到了:
{
"timestamp": "2020-05-23T07:51:30.905+00:00",
"status": 400,
"errors": [
"Name should have atleast 3 characters"
]
}
【问题讨论】:
标签: hibernate spring-boot hibernate-validator