spring icon indicating copy to clipboard operation
spring copied to clipboard

Handling Contact Form Submission with Validation and HTTP Status Codes in Spring Boot

Open Laurent45 opened this issue 5 months ago • 0 comments

https://github.com/eazybytes/spring/blob/766c0f350677ff48a4895720193d9261e22aa668/example_24/src/main/java/com/eazybytes/eazyschool/controller/ContactController.java#L46

Hi, To better align with HTTP response status codes, we can return a ModelAndView object instead of a String, allowing us to explicitly set the HTTP status code to 400 BAD_REQUEST.

    @RequestMapping(value = "/saveMsg",method = POST)
    public ModelAndView saveMessage(@Valid @ModelAttribute("contact") Contact contact, Errors errors){
        ModelAndView modelAndView = new ModelAndView();
        
        if (errors.hasErrors()){
            log.error("Contact form validation failed due to : " + errors.toString());
            modelAndView.setStatus(HttpStatus.BAD_REQUEST);
            modelAndView.setViewName("contact.html");
        } else {
            contactService.saveMessageDetails(contact);
            modelAndView.setStatus(HttpStatus.OK);
            modelAndView.setViewName("redirect:/contact");
        }

        return modelAndView;
    }

Laurent45 avatar Aug 26 '25 10:08 Laurent45