Spring MVC Controller, how to save BindingResult errors when emptying form values

I have a web form using Spring MVC Controller. The form is confirmed by Spring. When there are validation errors, Spring shows the same form pre-populated with the values ​​entered by the user, and validation errors.

For security reasons, I do not want the form to be pre-populated with the values ​​entered by the user, but I need to show validation errors.

How can i do this?

I achieved this behavior by looking at the source code of Spring MVC and seeing how BINDING_RESULT_KEY is created. Here is the source code.

However, this is a hack, and it may stop working with the new version of Spring MVC.

How can I achieve this correctly?

package com.nespresso.ecommerce.naw.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Errors;
import org.springframework.validation.ObjectError;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.validation.Valid;


@Controller
@RequestMapping("/my_form")
public class MyFormController extends FrontEndController {
    final String MY_FORM_OBJECT_NAME = "myForm";
    final String BINDING_RESULT_KEY = BindingResult.MODEL_KEY_PREFIX + "myForm";

    @RequestMapping(method = RequestMethod.POST)
    public String post(@Valid @ModelAttribute("myForm") MyForm myForm, Errors errors, Model model) {
        if (errors.hasErrors()) {
            emptyMyFormWhileKeepingFormErrors(model);
            return "my_form";
        }

        return "redirect:/confirmation";
    }

    @ModelAttribute("myForm")
    public MyForm myForm() {
        return new MyForm();
    }

    private void emptyMyFormWhileKeepingFormErrors(Model model) {
        BeanPropertyBindingResult bindingResult = (BeanPropertyBindingResult) model.asMap().get(BINDING_RESULT_KEY);
        if (bindingResult == null) {
            return;
        }
        MyForm emptyForm = myForm();

        // set the empty form, so the form is not pre-filled with the previous values.
        // However, this clears the validation errors also
        model.addAttribute(MY_FORM_OBJECT_NAME, emptyForm);

        // re-attach the validation errors, and empty the rejectedValue
        BeanPropertyBindingResult updatedBindingResult = new BeanPropertyBindingResult(emptyForm, MY_FORM_OBJECT_NAME);
        for (ObjectError oe : bindingResult.getAllErrors()) {
            if (!(oe instanceof FieldError)) {
                updatedBindingResult.addError(oe);
            } else {
                FieldError fieldError = (FieldError) oe;

                String rejectedValue = null;   // that the point, create a copy of the FieldError, emptying the rejectedValue;

                FieldError updatedFieldError = new FieldError(
                        MY_FORM_OBJECT_NAME,
                        fieldError.getField(),
                        rejectedValue,
                        fieldError.isBindingFailure(),
                        fieldError.getCodes(),
                        fieldError.getArguments(),
                        fieldError.getDefaultMessage());
                updatedBindingResult.addError(updatedFieldError);
            }
        }

        model.addAttribute(BINDING_RESULT_KEY, updatedBindingResult);
    }
}
+4
2

:

, ( ) org.springframework.beans.BeanUtils:

@RequestMapping(method = RequestMethod.POST)
public String post(@Valid @ModelAttribute("myForm") MyForm myForm, Errors errors, Model model) {
    if (errors.hasErrors()) {
        MyForm emptyForm = new MyForm();
        BeanUtils.copyProperties(emptyForm, myForm);
        return "my_form";
    }

    return "redirect:/confirmation";
}

, , .

- : , <input>, <form:input> spring , errors.

<form:input>, BindingResult , . reset :

@RequestMapping(value = "/form", method=RequestMethod.POST)
public String update(@Valid @ModelAttribute Form form, BindingResult result, Model model) {
    if (result.hasErrors()) {
        // uncomment line below to reset all fields - by default only offending ones are
        //form = new Form();
        BeanPropertyBindingResult result2 = new BeanPropertyBindingResult(form, result.getObjectName());
        for(ObjectError error: result.getGlobalErrors()) {
            result2.addError(error);
        }
        for (FieldError error: result.getFieldErrors()) {
            result2.addError(new FieldError(error.getObjectName(), error.getField(), null, error.isBindingFailure(), error.getCodes(), error.getArguments(), error.getDefaultMessage()));
        }
        model.addAllAttributes(result2.getModel());
        return "my_form";
    }

    return "redirect:/confirmation";
}
+9

, , - <form:*>. <input>.

:

<form:form modelAttribute="userForm" method="post">
    Username: <form:input path="username" /><br>

    <form:errors path="password" element="div" />
    Password: <input path="password" ><br>

    <input type="submit" value="Save" />
</form:form>

, .

+1

All Articles