Skip to content

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

@Laurent45

Description

@Laurent45

public String saveMessage(@Valid @ModelAttribute("contact") Contact contact, Errors errors){

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;
    }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions