惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

G
GRAHAM CLULEY
V
V2EX
WordPress大学
WordPress大学
博客园 - Franky
Last Week in AI
Last Week in AI
博客园 - 司徒正美
有赞技术团队
有赞技术团队
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
博客园 - 【当耐特】
V
Visual Studio Blog
C
CERT Recently Published Vulnerability Notes
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Jina AI
Jina AI
Attack and Defense Labs
Attack and Defense Labs
腾讯CDC
The Hacker News
The Hacker News
Hugging Face - Blog
Hugging Face - Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
J
Java Code Geeks
人人都是产品经理
人人都是产品经理
阮一峰的网络日志
阮一峰的网络日志
T
Tailwind CSS Blog
S
SegmentFault 最新的问题
大猫的无限游戏
大猫的无限游戏
小众软件
小众软件
A
Arctic Wolf
量子位
博客园 - 聂微东
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
N
News and Events Feed by Topic
雷峰网
雷峰网
博客园_首页
Google Online Security Blog
Google Online Security Blog
Spread Privacy
Spread Privacy
罗磊的独立博客
H
Hacker News: Front Page
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
月光博客
月光博客
TaoSecurity Blog
TaoSecurity Blog
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
博客园 - 三生石上(FineUI控件)
宝玉的分享
宝玉的分享
IT之家
IT之家
The Cloudflare Blog
爱范儿
爱范儿
博客园 - 叶小钗
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Apple Machine Learning Research
Apple Machine Learning Research
酷 壳 – CoolShell
酷 壳 – CoolShell

博客园 - 一路前行

RestTemplate之GET和POST调用和异步回调 ConditionalOnProperty fastjson序列化乱序问题 IE中的console.log spring boot 中添加mongodb支持 javacript onclick事件中传递对象参数 Java Lambda 表达式 对 Map 对象排序 比较两个list对象是否相同 ubuntu redis 自启动配置文件(关机有密码) spring中订阅redis键值过期消息通知 网站架构之性能优化(转) Json转Java Bean java @ResponseBody返回值中去掉NULL字段 合并两个java bean对象非空属性(泛型) spring mvc 删除返回字符串中值为null的字段 ubuntu下postgreSQL安装配置 十大Intellij IDEA快捷键(转) C#封装好的Win32API IntelliJ Idea 常用快捷键列表
spring mvc 4 校验
一路前行 · 2016-07-25 · via 博客园 - 一路前行

一、controller中添加:

@Resource
GatewayValidator gatewayValidator;
@RequestMapping(value = "/gateway/signup", method = RequestMethod.POST)
public ApiResponse signup(@Valid Gateway gateway, BindingResult result) {
    ApiResponse rspResult = new ApiResponse();
    gatewayValidator.validate(gateway, result);
    if(result.hasErrors()){
        rspResult.setCode(ApiCode.PARMAS_ERROR);
        rspResult.setMessage(BaseUtils.GetValidErrorMessage(result));
    }
    else {
        //do something
    }
    return rspResult;
}

二、model中添加(简单的校验可以直接卸载model类中):

package smarthome.api.models;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.time.DateUtils;
import org.hibernate.validator.constraints.NotEmpty;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class Gateway extends BaseClass implements Serializable {
    
    /**
     * None
     */
    protected String vendorCode;
    /**
     * None
     */
    protected String productCode;
    /**
     * None
     */
    @NotEmpty(message = "序列号不能为空")
    protected String serialNumber;

    public Gateway() {
    }
    
    public String getVendorCode() {
        return vendorCode;
    }
    public void setVendorCode(String vendorCode) {
        this.vendorCode = vendorCode == null ? null : vendorCode.trim();
    }

    public String getProductCode() {
        return productCode;
    }
    public void setProductCode(String productCode) {
        this.productCode = productCode == null ? null : productCode.trim();
    }

    public String getSerialNumber() {
        return serialNumber;
    }
    public void setSerialNumber(String serialNumber) {
        this.serialNumber = serialNumber == null ? null : serialNumber.trim();
    }
}

三、简单的校验

package smarthome.api.validators;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import javax.annotation.Resource;
import java.util.List;

@Component
public class GatewayValidator implements Validator {
    public boolean supports(Class clazz) {
        return Gateway.class.equals(clazz);
    }
    public void validate(Object target, Errors errors) {
        Gateway gateway = (Gateway) target;
        if(gateway.getGatewayId() == null && StringUtils.isEmpty(gateway.getSerialNumber())){
            errors.rejectValue("gatewayId", null, "网关编号和序列号不能同时为空");
            errors.rejectValue("serialNumber", null, "网关编号和序列号不能同时为空");
        }
    }
}

四、嵌套的校验

1、父类(gateway)中添加校验

package smarthome.api.validators;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import javax.annotation.Resource;
import java.util.List;


@Component
public class GatewayValidator implements Validator {
    @Resource
    private ModuleValidator moduleValidator;
    public boolean supports(Class clazz) {
        return Gateway.class.equals(clazz);
    }
    public void validate(Object target, Errors errors) {
        Gateway gateway = (Gateway) target;
        if(gateway.getGatewayId() == null && StringUtils.isEmpty(gateway.getSerialNumber())){
            errors.rejectValue("gatewayId", null, "网关编号和序列号不能同时为空");
            errors.rejectValue("serialNumber", null, "网关编号和序列号不能同时为空");
        }
        for(Module module : (List<Module>)gateway.getModuleList()){
            ValidationUtils.invokeValidator(moduleValidator, module, errors);
        }
    }
}

2、子类(module)中的校验

package smarthome.api.validators;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import javax.annotation.Resource;

@Component
public class ModuleValidator implements Validator {
    @Resource
    private IModuleService moduleService;
    public boolean supports(Class clazz) {
        return Module.class.equals(clazz);
    }
    public void validate(Object target, Errors errors) {
        Module module = (Module) target;
        if (StringUtils.isEmpty(module.getSerialNumber())) {
            errors.rejectValue("serialNumber", null, "模块序号不能为空");
        }
        else {
            if(moduleService.getFirst(module.getSerialNumber()) != null){
                errors.rejectValue("serialNumber", null, "模块序列号已经存在");
            }
        }
    }
}