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();
model.addAttribute(MY_FORM_OBJECT_NAME, emptyForm);
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;
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);
}
}