[Java] Self-made by Spring

2 minute read

background

Make a note of the validation method other than adding annotations to the Form (double check, etc.). This time use Spring Validator instead of Bean Validation.

Method

SessionForm


public class SessionForm {

    private CheckForm checkForm;
    // variable for error output
    private String error1;

    private String error2;
    //Setter etc. omitted

CheckValidation


@Component
                             // interface implementation
public class CheckValidation implements Validator {
    //Inject if using helper for Check
    @Autowired
    Helper helper;

    @Override
    public boolean supports(Class<?> clazz) {
        //Enter the Form you want to check (class with session attribute)
        //isAssignableFrom is all inherited classes
        return SessionForm.class.isAssignableFrom(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {
        // once create the target class
        SessionForm form = (SessionForm) target;
        Nested elements can also be used by setting //form.checkForm.~
        if (conditional expression) {
                errors.rejectValue(
                       // Variable specified in the form
                       "error1",
                       //Null if the message is not defined in another file
                        null,
                       "The message you want to output");
            }

        // do another check
        if (conditional expression) {
                errors.rejectValue(
                        "error2",
                         null,
                        "The message you want to output");
                }
}
          

Controller


@Controller
@SessionAttributes(names = "sessionForm")
public class ExampleController {
    //For Key setting
    private static final String FORM_NAME = "sessionForm";

    //Inject your own validation class
    @Autowired
    CheckValidation checkValidation;

    //Add to WebDataBinder
    @InitBinder("sessionForm")
    public void initBinder(WebDataBinder binder) {
        binder.addValidators(checkValidation);
    }
    
    // The modeato attached to the method will add a place to the model before calling
    @ModelAttribute(value = "sessionForm")
    public SessionForm sessionForm() {
        return new SessionForm();
    }

//a
@RequestMapping(path="path put in redirect", method=RequestMethod.GET)
    public String putInformation(@ModelAttribute(FORM_NAME) SessionForm session, BindingResult result,ModelMap model) {

        String key = BindingResult.MODEL_KEY_PREFIX + FORM_NAME;
        // If there is an error in the model on redirect
        if(model.containsKey("errors")) {
            //Store the error in map format in the form set to Key
            model.addAttribute(key, model.get("errors"));
            model.addAttribute("sessionForm" ,session);
            return "JSP, etc. you want to transition";
        }
        // others omitted
}

//b
@RequestMapping(path="input confirmation screen etc.", method=RequestMethod.POST)
    public String confirmInfomation(@Validated SessionForm session, BindingResult result, Model model, RedirectAttributes ra) throws Exception {

            if(result.hasErrors()) {
            ra.addFlashAttribute("errors", result);
            // redirect to the input screen
            return "redirect:/{to the path of the controller you want to call}";
        }
        // others omitted
}

JSP


<form:errors path="error1" />
<form:errors path="error2" />

Note

・First, create a variable for error in the full form. ・The validator class stores information in that variable.

  • By adding a validator to WebDataBinder in the controller, the added validator is called after calling BeanValidation and self-made check is performed. Don’t forget Autowired.
  • If there is an error in BindingResult, redirect it while holding the information (check in the part before transition to the input confirmation screen). The method flow is a→b→a.
  • Branch depending on whether there is an error in the redirect destination method, and if there is, store the error information in the model and share it with the JSP.
  • Use errors of form tag in JSP and match the path and session form variables to output an error message.

Summary

This time I created it through trial and error, so I think there is a better way to do it, but I made a note because it worked. I was able to compare it with the information (date etc.) brought from the DB in the validator class, so I thought that the validator has a high degree of freedom. If I implemented a validator other than Spring, I thought I would write a condition using a filter.