Spring 的验证机制

有时验证规则并不是那么简单,比如一些业务逻辑的验证。

例如,假设需要验证购买商品的总价格,那么就应该是:总价格=单价×数量,这时固有的验证就不能用了。

为了更灵活的提供验证机制,Spring 提供了自己的验证机制。

示例

1. 模型类

User.java

public class User {
    String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

2. 自定义验证器

UserValidator.java

import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

public class UserValidator implements Validator {
    @Override
    public boolean supports(Class<?> clazz) {
        return clazz.equals(User.class);
    }

    @Override
    public void validate(Object target, Errors errors) {
        if (target == null) {
            errors.rejectValue("", null, "用户不能为空");
            return;
        }
        User user = (User) target;
        if (user.getName() == null || "".equals(user.getName())) {            
            // 增加错误,可以进入控制器方法             
            errors.rejectValue("name", null, "用户名不能为空");        
        }
    }
}

3. 绑定验证器、测试

UserController.java

import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
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.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/user")
public class UserController {
    @InitBinder
    public void initBinder(WebDataBinder binder) { // 绑定验证器
        binder.addValidators(new UserValidator());
    }

    @GetMapping("/validator")
    @ResponseBody
    public String validator(@ModelAttribute("user") @Valid User user, BindingResult result) {
        Map<String, Object> map = new HashMap<>();
        map.put("name", user.getName());
        if (result.hasErrors()) {
            List<ObjectError> oes = result.getAllErrors();
            for (ObjectError oe : oes) {
                // 判定是否字段错误
                if (oe instanceof FieldError) { // 字段错误
                    FieldError fe = (FieldError) oe;
                    map.put(fe.getField(), fe.getDefaultMessage());
                } else {
                    map.put(oe.getObjectName(), oe.getDefaultMessage());
                }
            }
        }
        return map.toString();
    }
}

访问 http://localhost:8080/user/validator?name2=test

结果:

{name=用户名不能为空}

猜你喜欢

转载自blog.csdn.net/weixin_33972649/article/details/87088456