为什么@Valid注释会导致ServletException:循环视图路径?

时间:2019-07-20 10:03:05

标签: spring-boot validation controller-advice

我有一个简单的表格来注册新用户。我想对我的API进行验证,以验证表单中的数据是否有效。我用@Valid注释了控制器,以让spring为我做评估,但是我没有使用HTTP状态代码抛出消息,而是得到

javax.servlet.ServletException: Circular view path [register]: would dispatch back to the current handler URL [/register] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)

这里的控制器

@RestController
@Slf4j
public class LoginController {

    @Autowired
    UserService userService;

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public ResponseEntity registerNewUser(@Valid @RequestBody UserDto u) {
        userService.registerNewUser(u);
        return ResponseEntity.status(HttpStatus.OK).body("success");
    }

}

我的UserDto类:

@Data
@Builder
public class UserDto {

    private String name;

    @NotBlank(message = "Surname shouldn't be empty")
    private String surname;

    private String email;
    private String password;

}
@ControllerAdvice
public class ApiExceptionHandler {

    @ExceptionHandler(value = {
            ApiException.class
    })
    public ResponseEntity<Object> handleApiException(ApiException a) {
        return new ResponseEntity<>(a.getMessage(),a.getHttpStatus());
    }


    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Map<String, String> handleValidationExceptions(MethodArgumentNotValidException ex) {
        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getAllErrors().forEach((error) -> {
            String fieldName = ((FieldError) error).getField();
            String errorMessage = error.getDefaultMessage();
            errors.put(fieldName, errorMessage);
        });
        return errors;
    }
}

0 个答案:

没有答案