请检查下面的例子,并帮助我在它。
我需要验证产品名称,描述,尺寸和价格,如果没有传递任何值需要得到一个错误的响应,在实体提供的消息。
实体。
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);
}
}
JSON在Postman中传递。
{
"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语法。我怀疑你应该得到一个 400 Bad Request
状态码,所以请检查你收到的返回状态码。
同时检查如果你使用这个输入会发生什么。
{
"productName": "aa",
"description": "",
"price": "200.00" ,
"size": ""
}
这个输入应该会给你你期望看到的错误信息。
我怀疑第一个请求的例子由于状态码是400,所以根本没有得到处理,这意味着它根本没有到达后端,因此没有消息。
另外,与其使用 @RequestMapping(value = "/saveProduct" ,method =RequestMethod.POST, produces = "application/json")
,
试试这个。
@PostMapping({"/saveProduct"})
这是上面的速记版,让代码更易读。
尝试在controller上面添加@Validated.像例子中的Post mapping更现代的写法。
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);
}
}