简体   繁体   English

如何在模型验证 Spring Boot 中返回 400 状态

[英]How to return 400 status in model validation spring boot

I want to test my StudentDTO :我想测试我的StudentDTO

@Entity
@ToString
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class StudentDTO {
@Id
private int studentId;
@NotNull
@Size(min=2,max=30,message = "Name should consist of 2 to 30 symbols!")
private String studentName;
@NotNull
@Size(min = 2, max = 30,message = "Surname should consist of 2 to 30 symbols!")
private String studentSurname;
@NotNull
@Min(value = 10,message = "Student age should be more than 10!")
private int studentAge;
@NotNull
@Min(value = 1900,message = "Entry year should be more than 1900!")
@Max(value=2021,message = "Entry year should be less than 2021!")
private int entryYear;
@NotNull
@Min(value = 2020,message = "Graduate year should be not less than 2020!")
private int graduateYear;
@NotNull
@Size(min = 3,message = "Faculty name should consist of minimum 3 symbols!")
private String facultyName;
@NotNull
@Size(min = 4,message = "Group name should consist of 4 symbols!")
@Size(max = 4)
private String groupName;
}

Method for testing in StudentController :StudentController进行测试的方法:

@PostMapping("successStudentAddition")
public String addStudent(@ModelAttribute("student") @Valid StudentDTO studentDTO, Errors errors, Model model) {

    if (errors.hasErrors()) {
        model.addAttribute(STUDENT_MODEL, studentDTO);
        return "/studentViews/addStudent";
    }

    Student student = new Student(studentDTO.getStudentId(), studentDTO.getStudentName(), studentDTO.getStudentSurname(),
            studentDTO.getStudentAge(), studentDTO.getEntryYear(), studentDTO.getGraduateYear(), studentDTO.getFacultyName(),
            groupService.getGroupIdByName(studentDTO.getGroupName()));
    studentService.addStudent(student);
    return "/studentViews/successStudentAddition";
}

I am trying to test in this way :我正在尝试以这种方式进行测试:

@ExtendWith(SpringExtension.class)
@WebMvcTest(controllers = StudentController.class)
class StudentControllerTest {
@Autowired
private MockMvc mvc;

@Autowired
private ObjectMapper objectMapper;

@MockBean
private StudentController studentController;

@Test
void whenInputIsInvalid_thenReturnsStatus400() throws Exception {
    StudentDTO studentDTO = new StudentDTO();
    studentDTO.setStudentId(0);
    studentDTO.setStudentName("Sasha");
    studentDTO.setStudentSurname("Georginia");
    studentDTO.setStudentAge(0);
    studentDTO.setEntryYear(5);
    studentDTO.setGraduateYear(1);
    studentDTO.setFacultyName("facop");
    studentDTO.setGroupName("BIKS");

    mvc.perform(post("/studentViews/successStudentAddition")
            .accept(MediaType.TEXT_HTML))
            .andExpect(status().isBadRequest())
            .andExpect(model().attribute("student", studentDTO))
            .andDo(print());
}
}

In my test I got 200 error, but I need to get 400 error with determined error above on the field from my StudentDTO .在我的测试中,我得到了 200 错误,但我需要得到 400 错误,并在我的StudentDTO字段上确定上述错误。

eg if I pass studentAge = 5 , I should to get 400 error and the message : Student age should be more than 10!例如,如果我通过studentAge = 5 ,我应该得到 400 错误和消息: Student age should be more than 10! like in the StudentDTO .就像在StudentDTO

I often turn to spring's org.springframework.http.ResponseEntity class .我经常求助于 spring 的org.springframework.http.ResponseEntity

@PostMapping("successStudentAddition")
public ResponseEntity<String> addStudent(@ModelAttribute("student") @Valid StudentDTO studentDTO, Errors errors, Model model) {

    if (errors.hasErrors()) {
        model.addAttribute(STUDENT_MODEL, studentDTO);
        return new ResponseEntity<String>("/studentViews/addStudent", HttpStatus.BAD_REQUEST);
    }

    Student student = new Student(studentDTO.getStudentId(), studentDTO.getStudentName(), studentDTO.getStudentSurname(),
            studentDTO.getStudentAge(), studentDTO.getEntryYear(), studentDTO.getGraduateYear(), studentDTO.getFacultyName(),
            groupService.getGroupIdByName(studentDTO.getGroupName()));
    studentService.addStudent(student);
    return new ResponseEntity<String>("/studentViews/successStudentAddition", HttpStatus.Ok);
}

When you have such a condition, Spring will throw MethodArgumentNotValidException .当您遇到这样的情况时,Spring 将抛出MethodArgumentNotValidException To handle these exceptions you can write a class with @ControllerAdvice .要处理这些异常,您可以使用@ControllerAdvice编写一个类。

@ControllerAdvice
public class ErrorHandler {
     

    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    public ResponseEntity<Error> invalidArgumentExceptionHandler(MethodArgumentNotValidException ex) {
// Instead of "/studentViews/successStudentAddition" you can return to some generic error page.
            return new ResponseEntity<String>("/studentViews/successStudentAddition", HttpStatus.BAD_REQUEST);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Spring MVC验证状态400 - Spring MVC validation status 400 spring 启动 jpa 应用程序,crudRepo 错误(类型=错误请求,状态=400)。 object 验证失败 - spring boot jpa app, crudRepo Error (type=Bad Request, status=400). Validation failed for object 如何在 Spring Boot 中返回模型中不存在的字段? - How to return fields in Spring Boot that is not present in the model? 如何从Spring MVC控制器返回错误状态和验证错误? - How to return error status and validation errors from this Spring MVC controller? 如何在 Spring Boot 中为枚举类型返回正确的验证错误? - How to return a proper validation error for enum types in Spring Boot? Spring Boot 如何返回我自己的验证约束错误消息 - Spring Boot how to return my own validation constraint error messages 如何在 Spring Boot 中使用 Enum 类返回验证消息? - How to return validation message using Enum class in spring boot? Spring Boot-Rest Service-获取随机HTTP状态400 - Spring boot - Rest Service - Getting random HTTP status 400 Java Spring:如何处理HTTP Status 400? - Java Spring: How to handle HTTP Status 400? 如何在 Spring Boot @ResponseBody 中返回 404 响应状态 - 方法返回类型是 Response? - How to return 404 response status in Spring Boot @ResponseBody - method return type is Response?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM