Use spring @ Validated for verification

validate using spring @ Validated and return the error message to the page, code:

1. Model is defined

@Getter 
@Setter
public class User {
    
    private String userName;
    private String password;
    private String email;
    
}


2, Custom UserValidate

public class UserValidate implements Validator {

    @Override 
    public boolean supports(Class<?> arg0) {
        System.out.println("ee:"+arg0+","+User.class.isAssignableFrom(arg0));
        return User.class.isAssignableFrom(arg0);
    }

    @Override 
    public void validate(Object target, Errors errors) {
        //ValidationUtils.rejectIfEmpty(errors, "userName", "user.userName.required", "");
        //ValidationUtils.rejectIfEmpty(errors, "password", "user.password.required", "");
        //ValidationUtils.rejectIfEmpty(errors, "email", "user.email.required", "");
        User user = (User) target;
        int length = user.getUserName().length();
        if (length > 20) {
            errors.rejectValue("userName", "user.userName.too_long", "{20}");
        }
        length = user.getPassword().length();
        if (length < 6) {
            errors.rejectValue("password", "user.password.too_short", "{6}");
        } else if (length > 20) {
            errors.rejectValue("password", "user.password.too_long", "{20}");
        }
        int index = user.getEmail().indexOf("@");
        if (index == -1) {
            errors.rejectValue("email", "user.email.invalid_email", "");
        }
    }
}


3. Front end: thymeleaf

<html>
    <head>
    </head>
    <body>
        
        <br /><hr />
        
        <form action="-sharp" th:action="@{/addUser}"  method="POST">
            userName :<input type="text" name="userName"  /><br />
            password :<input type="text" name="password" /><br />
            email :<input type="text" name="email" /><br />
            :<div style="font-size:18px;"><span th:text="${result}"></span></div>
            <input type="submit" />
        </form>
        
    </body>
</html>

4, backend controller

import java.util.List;
import java.util.function.Consumer;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;

import com.example.demo.app.model.User;
import com.example.demo.app.validate.UserValidate;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ImmutableListMultimap.Builder;

@Controller
public class UserController {
    
    @GetMapping("/userInfo")
    public ModelAndView userInfo() {
        ModelAndView userView = new ModelAndView("user");
        return userView;
    }

    
    @PostMapping("/addUser")
    public String addBook(@Validated User user,BindingResult result, Model model) {
        
        if(result.hasErrors()){
            List<ObjectError> allErrors = result.getAllErrors();
            Builder<String, String> builder = ImmutableListMultimap.builder();
            allErrors.stream().forEach(new Consumer<ObjectError>() {

                @Override
                public void accept(ObjectError t) {
                    builder.put(t.getObjectName(), t.getDefaultMessage());
                }
            });
            
            ImmutableListMultimap<String, String> build = builder.build();
            model.addAttribute("result",build);
        }else {
            model.addAttribute("result","success");
        }
        return "user";
    }
    
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.addValidators(new UserValidate());
    }
    
}

5. After the front end is submitted, the consistent back package is abnormal. The result of the exception is that the ImmutableListMultimap class has also carried out the UserValidate verification process. Why

Mar.17,2021
Menu