[JAVA] Self-made Validation with Spring

background

Make a note of the validation method other than annotating the Form (double check, etc.). This time we will 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 when using helper for Check
    @Autowired
    Helper helper;

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

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

        //Do another check
        if (Conditional expression) {
                errors.rejectValue(
                        "error2", 
                         null, 
                        "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;

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

//a
@RequestMapping(path="The path you put in the 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 when redirecting
        if(model.containsKey("errors")) {
            //Error storage in map format in the form set in 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 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 variables for errors on the full form. -Information is stored in the variable in the validator class. -By adding a validator to WebDataBinder with the controller, the validator added after calling Bean Validation is called and the self-made check is performed. Don't forget Autowired. -If there is an error in BindingResult, redirect while retaining that information (check the part before transitioning to the input confirmation screen, etc.). The method flow is in the order of a → b → a. -Branch depending on the presence or absence of 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, match the path and the variable of the session form, and output the error message.

Summary

This time, I created it through trial and error, so I think there is a better way, 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 had a high degree of freedom. If you want to implement a validator other than Spring, I thought you should write a condition using a filter or something.

Recommended Posts

Self-made Validation with Spring
Get validation results with Spring Boot
Form class validation test with Spring Boot
JSON validation with JSON schema
[Java] Article to add validation with Spring Boot 2.3.1.
Spring with Kotorin ―― 1. SPRING INITIALIZR
Download with Spring Boot
Generate barcode with Spring Boot
Spring validation and error code
Hello World with Spring Boot
Java Config with Spring MVC
Process validation messages with Decorator
Spring with Kotorin --8 Repository layer
Get started with Spring boot
Hello World with Spring Boot!
Spring with Kotorin --6 Asynchronous processing
Run LIFF with Spring Boot
SNS login with Spring Boot
Spring with Kotorin ―― 7. Service layer
Login function with Spring Security
Using Mapper with Java (Spring)
Spring Boot starting with Docker
Hello World with Spring Boot
Set cookies with Spring Boot
Use Spring JDBC with Spring Boot
Add module with Spring Boot
Getting Started with Spring Boot
Link API with Spring + Vue.js
Create microservices with Spring Boot
Spring single item validation test
Send email with spring boot
Spring Boot validation message changes
Use Basic Authentication with Spring Boot
Spring with Kotorin --4 REST API design
Implemented authentication function with Spring Security ②
gRPC on Spring Boot with grpc-spring-boot-starter
Hot deploy with Spring Boot development
Spring Boot programming with VS Code
Until "Hello World" with Spring Boot
Inquiry application creation with Spring Boot
Implemented authentication function with Spring Security ①
Implement file download with Spring MVC
Oauth2 authentication with Spring Cloud Gateway
Add Bean Validation with Micronaut (Java)
Easy input check with Bean Validation!
(Intellij) Hello World with Spring Boot
Google Cloud Platform with Spring Boot 2.0.0
Check date correlation with Spring Boot
I tried GraphQL with Spring Boot
[Java] LINE integration with Spring Boot
[Spring] Autowired multiple beans. (With bonus)
Beginning with Spring Boot 0. Use Spring CLI
I tried Flyway with Spring Boot
Authentication / authorization with Spring Security & Thymeleaf
Test Spring framework controller with Junit
About error when implementing spring validation
Message cooperation started with Spring Boot
Spring Boot gradle build with Docker
Processing at application startup with Spring Boot
OR search with Spring Data Jpa Specification
Hello World with Eclipse + Spring Boot + Maven