簡體   English   中英

@Valid @RequestBody無法驗證輸入錯誤的傳入Json

[英]@Valid @RequestBody failed to validate incoming Json with wrong input

我想驗證傳入的RequestBody。我的控制器API是

@RequestMapping(value = {
        POSRequest.REQUEST_SEPARATOR + Request.UPDATE_URL,
        method = RequestMethod.PUT,
        produces = MediaType.APPLICATION_JSON_VALUE)
@ApiOperation(value = "Update .”,
        response = SuccessResponseDTO.class, ,
        produces = "application/json", httpMethod = "PUT")
@ApiResponses(value = {
        @ApiResponse(code = 200, message = "OK",response = SuccessResponseDTO.class),
        @ApiResponse(code = 401, message = "Unauthorized",response =ErrorResponseDTO.class),
        @ApiResponse(code = 403, message = "Forbidden",response = ErrorResponseDTO.class),
        @ApiResponse(code = 404, message = "Not Found",response = ErrorResponseDTO.class)
})
public @ResponseBody
SuccessResponseDTO update(HttpServletRequest request,
                             @ApiParam(required = true, type = "String", value = " ") @RequestParam(value = “id”, required = true) String id,
                             @ApiParam(required = true, type = "String", value = "  ") @RequestParam(value = "documentNumber", required = true) String documentNumber,
                             @ApiParam(required = true, type = "String", value = " ") @RequestParam(value = “Sid”, required = true) String sid,
                             @ApiParam(required = true, type = "UpdateDTO", value = "Update payload json ")  @Valid @RequestBody UpdateDTO pdatePayload) throws IOException {
    authorizeRequest(request, anId);
    UpdateDTO posDTO = UpdatePayload;
    UpdateAction<UpdateDTO> action = new UpdateAction(Constants.ACTION_UPDATE, DTO, principal);
    action.addAdditionalParams(Constants.KEY_INPUT_DOC_NUMBER, documentNumber);
    action.addAdditionalParams(Constants.KEY_INPUT_SUPPLIER_AN_ID, sid);
    Gson gson = new Gson();
    action.addAdditionalParams(Constants.CONTENT, gson.toJson(DTO));
    return updateService.update(action);
}

我在@RequestBody使用注解@Valid ,希望它可以驗證輸入JSON。 用戶發送非映射屬性的輸入JSON無效, API只是忽略了非映射字段而沒有任何錯誤。

例如, UpdateDTO包含用於字符串名稱,字符串狀態的settergetter

用戶請求中包含無效字段,

{
"name":"my update",
"invalid_field":"abc"
}

轉換為UpdateDTO且非映射字段將被忽略。 我希望它會因輸入無效而出錯。

你能給我建議嗎? 我該如何運作? 請讓我知道是否需要任何輸入

我包括以下Maven依賴項,

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-core</artifactId>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.8.0</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.8.0</version>
    </dependency>
</dependencies>

您誤解了@Valid的用法。 所述@Valid注釋用於驗證與像約束豆@NotNull@Size@Min等具體根據JSR 380規范 例如,如果要對UpdateDTO類的name字段進行驗證,以使name永遠不能為null,則可以在name字段上使用@NotNull ,然后在控制器方法中的UpdateDTO對象上使用@Valid 這將確保無論何時發出請求而不傳遞name字段,驗證都將失敗,並且將相應地引發異常。

對於要在請求中發送未知字段時引發異常的用例,由於您使用的是使用Jackson進行序列化/反序列化的spring-boot,因此您只需要提供一個配置即可在遇到未知的屬性。 可以通過以下屬性啟用它:

spring.jackson.deserialization.FAIL_ON_UNKNOWN_PROPERTIES=true

或通過如下定義@Bean

@Bean
public ObjectMapper objectMapper() {
    return Jackson2ObjectMapperBuilder
            .json()
            .featuresToEnable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
            .build();
}

在控制器類的頂部使用@Validated注解,並將其添加到控制器類中

 /**
 * Exception handler for ConstraintViolationException.
 * @param exception ConstraintViolationException
 * @return error message
 */
@ExceptionHandler(ConstraintViolationException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public @ResponseBody String annotationExceptionHandler(ConstraintViolationException exception) {
    return exception.getMessage();
}

它處理用戶的無效輸入。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM