使用spring @Validated进行验证

新手上路,请多包涵

使用spring @Validated进行验证,并将错误信息返回到页面,代码:

1、定义了model

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


2、自定义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、前端:thymeleaf

<html>
    <head>
    </head>
    <body>
        
        <br /><hr />
        
        <form action="#" 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、后端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、前端提交后,一致后包异常,异常的结果是ImmutableListMultimap类也进行了UserValidate的验证过程,请问为什么呢

阅读 4k
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题