出現了一些奇怪的問題,在業務模型中,我使用的地址串列不能為空或為空,但物件地址中的每個欄位也不能為空或為空。但是,當我發送其中一個欄位為空的請求時,該請求將傳遞到存盤庫,這不應該發生。服務器應該回傳一個內部服務器錯誤,而不是傳遞請求。
地址物件:
@Data
@NoArgsConstructor
public class Address {
@NotEmpty(message = "Street may not be empty")
@Size(min = 2, max = 256)
private String street;
@NotEmpty(message = "Number may not be empty")
@Size(min = 1, max = 5)
private String number;
@NotEmpty(message = "Postal code may not be empty")
@Field("postal_code")
@JsonProperty("postal_code")
@Size(min = 5, max = 6)
private String postalCode;
@NotEmpty(message = "City may not be empty")
@Size(min = 2, max = 256)
private String city;
@NotEmpty(message = "Province may not be empty")
@Size(min = 2, max = 256)
private String province;
@NotEmpty(message = "Country may not be empty")
@Size(min = 2, max = 256)
private String country;
}
包含地址串列的業務物件:
@Data
@NoArgsConstructor
@Document(collection = "businesses")
public class Business {
@Id
private String id;
@NotBlank
@Size(max = 64)
private String name;
@Field("created_at")
private Date createdAt;
@Field("updated_at")
private Date updatedAt;
private Boolean active;
@DBRef
private User owner;
private List<Address> addresses;
public Business(String name, User owner, List<Address> addresses, Date createdAt, Date updatedAt, Boolean active) {
this.name = name;
this.owner = owner;
this.addresses = addresses;
this.createdAt = createdAt;
this.updatedAt = updatedAt;
this.active = active;
}
public Business(String name, User owner, List<Address> addresses, Date updatedAt, Boolean active) {
this.name = name;
this.owner = owner;
this.addresses = addresses;
this.updatedAt = updatedAt;
this.active = active;
}
}
最后,服務:
@Override
public ResponseEntity<?> createBusiness(CreateBusinessRequest request, String token) throws RuntimeException {
Optional<User> user = userRepository.findByUsername(jwtUtils.getUserNameFromJwtToken(token.substring(7)));
if(businessRepository.existsByName(request.getName())) {
throw new ItemAlreadyExistsException("Business with " request.getName() " already exists!");
}
if(user.isEmpty()) {
throw new NotFoundException("User with " user.get().getUsername() " does not exist!");
}
if(request.getAddresses().isEmpty() || request.getAddresses() == null) {
throw new InvalidInputException("Address is empty!");
}
Business business = new Business(
request.getName(),
user.get(),
request.getAddresses(),
new Date(),
new Date(),
true
);
businessRepository.save(business);
return ResponseEntity.ok(business);
}
控制器:
@PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')")
@PostMapping("/create")
public ResponseEntity<?> createBusiness(@Valid @RequestBody CreateBusinessRequest request, @RequestHeader (name="Authorization") String token) {
return businessService.createBusiness(request, token);
}
要求:
{
"name": "Test business",
"addresses": [
{
"street": "",
"number": "100",
"postal_code": "84104",
"city": "Test city",
"province": "Test",
"country": "Slovakia"
}
]
}
我希望我正確解釋了我的問題。這個問題有什么解決辦法嗎?
提前致謝。
uj5u.com熱心網友回復:
我的猜測是您缺少一個關鍵依賴項:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
uj5u.com熱心網友回復:
根據這個問題,我建議將 @Valid 注釋(javax.validation.Valid)添加到 Business 類的addresses 屬性中。另請參閱此處的示例
編輯:添加注釋后,您可以使用 BindingResult 進行控制器驗證。一個例子是這樣的:
@PostMapping("/")
public String doSomething(@Valid @RequestBody SomeModel model, BindingResult bindingResult)
{
if (bindingResult.hasErrors())
{
// handle validation error
}
}
uj5u.com熱心網友回復:
要完全配置方法級別的安全性,您需要添加以下注釋/類:
@Configuration
@EnableGlobalMethodSecurity(
prePostEnabled = true,
securedEnabled = true,
jsr250Enabled = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
}
這將開啟對您的服務方法的驗證。如前所述,您可以將 BindingResult 添加到您的控制器中,并在需要時檢查控制器中的錯誤。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/354964.html
