请检查下面的示例并帮助我。
我需要验证产品名称、描述、尺寸和价格,如果没有传递任何值需要得到带有实体中提供的消息的错误响应。
实体:
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
@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);
}
}
在邮递员中传递的 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"
]
}
在第一个示例中,您真的使用:"description": ,
和"size":
作为描述和大小输入值吗?您应该无法执行此请求,因为它构成了格式错误的 JSON 语法。我怀疑您应该在 Postman 中收到一个400 Bad Request
状态代码,因此请检查您收到的返回状态代码。
还要检查如果改用此输入会发生什么情况:
{
"productName": "aa",
"description": "",
"price": "200.00" ,
"size": ""
}
此输入应提供预期看到的错误消息。
我怀疑由于 400 状态代码,第一个请求示例根本没有得到处理,这意味着它甚至永远不会到达后端,因此没有消息。
此外,而不是使用@RequestMapping(value = "/saveProduct" ,method =RequestMethod.POST, produces = "application/json")
,
试试这个:
@PostMapping({"/saveProduct"})
它是上述内容的速记版本,使代码更具可读性。
尝试在控制器上方添加@Validated。 就像一个更现代的 Post 映射编写方法的示例:
public interface EmployeeController {
ResponseEntity<Employee> register(@Valid Employee employee);
}
@RestController
@RequestMapping("/employee")
@Validated
public class EmployeeControllerImpl implements EmployeeController {
@PostMapping(path = "/register",
consumes = "application/json",
produces = "application/json"
)
@Override
public ResponseEntity<Employee> register(@RequestBody Employee employee) {
Employee registeredEmployee = service.register(employee);
return ResponseEntity.status(201).body(registeredEmployee);
}
}