成人国产在线小视频_日韩寡妇人妻调教在线播放_色成人www永久在线观看_2018国产精品久久_亚洲欧美高清在线30p_亚洲少妇综合一区_黄色在线播放国产_亚洲另类技巧小说校园_国产主播xx日韩_a级毛片在线免费

資訊專欄INFORMATION COLUMN

記錄_使用JSR303規(guī)范進(jìn)行數(shù)據(jù)校驗(yàn)

187J3X1 / 2138人閱讀

摘要:時(shí)間年月日星期三說(shuō)明使用規(guī)范校驗(yàn)接口請(qǐng)求參數(shù)源碼第一章理論簡(jiǎn)介背景介紹如今互聯(lián)網(wǎng)項(xiàng)目都采用接口形式進(jìn)行開(kāi)發(fā)。該規(guī)范定義了一個(gè)元數(shù)據(jù)模型,默認(rèn)的元數(shù)據(jù)來(lái)源是注解。

時(shí)間:2017年11月08日星期三
說(shuō)明:使用JSR303規(guī)范校驗(yàn)http接口請(qǐng)求參數(shù)
源碼:https://github.com/zccodere/s...

第一章:理論簡(jiǎn)介 1-1 背景介紹

如今互聯(lián)網(wǎng)項(xiàng)目都采用HTTP接口形式進(jìn)行開(kāi)發(fā)。無(wú)論是Web調(diào)用還是智能設(shè)備APP調(diào)用,只要約定好參數(shù)形式和規(guī)則就能夠協(xié)同開(kāi)發(fā)。返回值用得最多的就是JSON形式。服務(wù)端除了保證正常的業(yè)務(wù)功能,還要經(jīng)常對(duì)傳進(jìn)來(lái)的參數(shù)進(jìn)行驗(yàn)證,例如某些參數(shù)不能為空,字符串必須含有可見(jiàn)字符,數(shù)值必須大于0等這樣的要求。

1-2 基礎(chǔ)理論

什么是JSR303規(guī)范

首先JSR 303是Java的標(biāo)準(zhǔn)規(guī)范。
根據(jù)官方文檔的描述:在一個(gè)應(yīng)用的不同層面(例如呈現(xiàn)層到持久層),
驗(yàn)證數(shù)據(jù)是一個(gè)是反復(fù)共同的任務(wù)。
許多時(shí)候相同的驗(yàn)證要在每一個(gè)獨(dú)立的驗(yàn)證框架中出現(xiàn)很多次。
為了提升開(kāi)發(fā)效率,阻止重復(fù)造輪子,于是形成了這樣一套規(guī)范。
該規(guī)范定義了一個(gè)元數(shù)據(jù)模型,默認(rèn)的元數(shù)據(jù)來(lái)源是注解(annotation)。

什么是AOP

是一種編程范式,不是編程語(yǔ)言
解決特定問(wèn)題,不能解決所有問(wèn)題
是OOP的補(bǔ)充,不是替代

JSR303定義的校驗(yàn)類型

空檢查

@Null       驗(yàn)證對(duì)象是否為null
@NotNull    驗(yàn)證對(duì)象是否不為null, 無(wú)法查檢長(zhǎng)度為0的字符串
@NotBlank   檢查約束字符串是不是Null還有被Trim的長(zhǎng)度是否大于0
@NotEmpty   檢查約束元素是否為NULL或者是EMPTY.

Booelan檢查

@AssertTrue     驗(yàn)證 Boolean 對(duì)象是否為 true  
@AssertFalse    驗(yàn)證 Boolean 對(duì)象是否為 false  

長(zhǎng)度檢查

@Size(min=, max=) 驗(yàn)證對(duì)象(Array,Collection,Map,String)長(zhǎng)度是否在給定的范圍之內(nèi)  
@Length(min=, max=) Validates that the annotated string is between min and max included.

日期檢查

@Past       驗(yàn)證 Date 和 Calendar 對(duì)象是否在當(dāng)前時(shí)間之前  
@Future     驗(yàn)證 Date 和 Calendar 對(duì)象是否在當(dāng)前時(shí)間之后  
@Pattern    驗(yàn)證 String 對(duì)象是否符合正則表達(dá)式的規(guī)則

數(shù)值檢查,建議使用在Stirng,Integer類型,不建議使用在int類型上,因?yàn)楸韱沃禐椤啊睍r(shí)無(wú)法轉(zhuǎn)換為int,但可以轉(zhuǎn)換為Stirng為"",Integer為null

@Min            驗(yàn)證 Number 和 String 對(duì)象是否大等于指定的值  
@Max            驗(yàn)證 Number 和 String 對(duì)象是否小等于指定的值  
@DecimalMax 被標(biāo)注的值必須不大于約束中指定的最大值. 這個(gè)約束的參數(shù)是一個(gè)通過(guò)BigDecimal定義的最大值的字符串表示.小數(shù)存在精度
@DecimalMin 被標(biāo)注的值必須不小于約束中指定的最小值. 這個(gè)約束的參數(shù)是一個(gè)通過(guò)BigDecimal定義的最小值的字符串表示.小數(shù)存在精度
@Digits     驗(yàn)證 Number 和 String 的構(gòu)成是否合法  
@Digits(integer=,fraction=) 驗(yàn)證字符串是否是符合指定格式的數(shù)字,interger指定整數(shù)精度,fraction指定小數(shù)精度。
@Range(min=, max=) 檢查數(shù)字是否介于min和max之間.
@Range(min=10000,max=50000,message="range.bean.wage")

private BigDecimal wage;

@Valid 遞歸的對(duì)關(guān)聯(lián)對(duì)象進(jìn)行校驗(yàn), 如果關(guān)聯(lián)對(duì)象是個(gè)集合或者數(shù)組,那么對(duì)其中的元素進(jìn)行遞歸校驗(yàn),如果是一個(gè)map,則對(duì)其中的值部分進(jìn)行校驗(yàn).(是否進(jìn)行遞歸驗(yàn)證)
@CreditCardNumber信用卡驗(yàn)證
@Email  驗(yàn)證是否是郵件地址,如果為null,不進(jìn)行驗(yàn)證,算通過(guò)驗(yàn)證。
@ScriptAssert(lang= ,script=, alias=)
@URL(protocol=,host=, port=,regexp=, flags=)

相關(guān)jar包

validation-api-1.0.0.GA.jar:接口規(guī)范
hibernate-validator-4.2.0.Final.jar是對(duì)上述接口的實(shí)現(xiàn)

Gradle坐標(biāo)

compile ("javax.validation:validation-api:1.1.0.Final")
compile ("org.hibernate:hibernate-validator:5.4.1.Final")
第二章:簡(jiǎn)單實(shí)戰(zhàn) 2-1 基于SpringMVC

工程創(chuàng)建

創(chuàng)建名為valid-mvc的gradle工程build.gradle如下

apply plugin: "war"
apply plugin: "java"
apply plugin: "eclipse"

[compileJava, javadoc, compileTestJava]*.options*.encoding = "UTF-8"

ext {
    springVersion = "4.3.8.RELEASE"
}  

repositories {
    mavenLocal()
    maven{ url "http://maven.aliyun.com/nexus/content/groups/public" }
    mavenCentral()
}

dependencies {

    // Spring框架
    compile ("org.springframework:spring-core:${springVersion}")
    compile ("org.springframework:spring-beans:${springVersion}")
    compile ("org.springframework:spring-context:${springVersion}")
    compile ("org.springframework:spring-web:${springVersion}")
    compile ("org.springframework:spring-webmvc:${springVersion}")
    compile ("org.springframework:spring-aop:${springVersion}")    
    compile ("org.springframework:spring-aspects:${springVersion}")    
    
    compile ("javax.servlet:javax.servlet-api:3.0.1")
    compile ("com.alibaba:fastjson:1.2.20")
    
    // JSR303數(shù)據(jù)校驗(yàn)
    compile ("javax.validation:validation-api:1.1.0.Final")
    compile ("org.hibernate:hibernate-validator:5.4.1.Final")
}

代碼編寫(xiě)

1.編寫(xiě)WebInitializer類

package com.zccoder.valid.mvc.config;

import java.util.EnumSet;

import javax.servlet.DispatcherType;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration.Dynamic;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;

/**
 * @Title apc-rest程序啟動(dòng)類
 * @Description 當(dāng)web容器啟動(dòng)項(xiàng)目的時(shí)候執(zhí)行
 * @author zc
 * @version 1.0 2017-11-08
 */
public class WebInitializer implements  WebApplicationInitializer  {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
      
        // 新建WebApplication,注冊(cè)配置類,并將其和當(dāng)前servletContext關(guān)聯(lián)。
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.register(SpringConfig.class);
        context.setServletContext(servletContext);
        
        // 注冊(cè)SpringMvc的DispatcherServlet。
        Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(context));
        servlet.addMapping("/");
        servlet.setLoadOnStartup(1);
        
        // 注冊(cè)SpringMVC的字符過(guò)濾器
        FilterRegistration.Dynamic encodingFilter = servletContext.addFilter("encoding", new CharacterEncodingFilter());
        EnumSet dispatcherTypes = EnumSet.allOf(DispatcherType.class);
        dispatcherTypes.add(DispatcherType.REQUEST);
        dispatcherTypes.add(DispatcherType.FORWARD);
        encodingFilter.addMappingForUrlPatterns(dispatcherTypes, true, "/*");
        encodingFilter.setInitParameter("encoding", "utf-8");
    }
}

2.編寫(xiě)SpringConfig類

package com.zccoder.valid.mvc.config;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;

/**
 * @Title spring配置文件類
 * @Description 配置spring的自動(dòng)掃描
 * @author zc
 * @version 1.0 2017-11-08
 */
@Configuration
@EnableWebMvc
@EnableAspectJAutoProxy
@ComponentScan("com.zccoder.valid.mvc")
public class SpringConfig extends WebMvcConfigurerAdapter{
    
    /**
     * 配置FASTJSON
     */
    @Bean
    public FastJsonHttpMessageConverter fastJsonHttpMessageConverters() {
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();

        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(SerializerFeature.QuoteFieldNames);
        fastJsonConfig.setCharset(Charset.forName("UTF-8"));
        fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");

        List supportedMediaTypes = new ArrayList();
        supportedMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);

        fastConverter.setSupportedMediaTypes(supportedMediaTypes);
        fastConverter.setFastJsonConfig(fastJsonConfig);
        return fastConverter;
    }
    
    /**
     * 配置JSON解析器
     */
    @Override
    public void configureMessageConverters(List> converters) {
        super.configureMessageConverters(converters);
        converters.add(this.fastJsonHttpMessageConverters());
    }
    
}

3.編寫(xiě)ValidAdvisor類

package com.zccoder.valid.mvc.config;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

import javax.validation.Valid;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import com.zccoder.valid.mvc.constants.EnRespStatus;
import com.zccoder.valid.mvc.vo.RspBaseVO;

/**
 * @Title JSR303數(shù)據(jù)校驗(yàn)切面
 * @Description 當(dāng)校驗(yàn)不通過(guò)時(shí),自動(dòng)處理校驗(yàn)結(jié)果,停止當(dāng)前請(qǐng)求,并響應(yīng)錯(cuò)誤提示
 * @author zc
 * @version 1.0 2017-11-08
 */
@Aspect
@Component
public class ValidAdvisor {

    // 通過(guò)@Pointcut注解聲明切點(diǎn)。
    @Pointcut("@annotation(org.springframework.web.bind.annotation.PostMapping)")
    public void annotationPointCut() {
    };
    
    @Around("annotationPointCut()")
    public Object doTest(ProceedingJoinPoint pjp) throws Throwable{
        
        // 獲取方法簽名
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
        Object[] args = pjp.getArgs();
        
        // 實(shí)例化方法返回值類型
        @SuppressWarnings("rawtypes")
        Class retuenClazz = signature.getReturnType();
        Object retuenObject = retuenClazz.newInstance();
        if(!(retuenObject instanceof RspBaseVO)){
            throw new RuntimeException("方法"+method.getName()+"返回值類型非法");
        }
        RspBaseVO rspVO = (RspBaseVO)retuenObject;
        
        // 遍歷被攔截的方法上所有注解
        Annotation[][] annotations = method.getParameterAnnotations();  
        for(int i = 0; i < annotations.length; i++){  
            if(!hasValidAnnotation(annotations[i])){  
                continue;  
            }
            if(!(i < annotations.length-1 && args[i+1] instanceof BindingResult)){  
                //驗(yàn)證對(duì)象后面沒(méi)有跟bindingResult,事實(shí)上如果沒(méi)有應(yīng)該到不了這一步  
                continue; 
            }
            BindingResult result = (BindingResult) args[i+1];  
            if(result.hasErrors()){
                FieldError fieldError = result.getFieldError();
                rspVO.setEnRespStatus(EnRespStatus.PARAM_INVALID);
                rspVO.setRespDesc(fieldError.getField() + fieldError.getDefaultMessage());
                return rspVO;
            }
        }
        
        return pjp.proceed();
    }
    
    /**
     * 校驗(yàn)是否有@Valid注解
     */
    private boolean hasValidAnnotation(Annotation[] annotations){  
        if(annotations == null){  
            return false;  
        }  
        for(Annotation annotation : annotations){  
            if(annotation instanceof Valid){  
                return true;  
            }  
        }
        return false;  
    }
}

4.編寫(xiě)EnRespStatus類

package com.zccoder.valid.mvc.constants;

public enum EnRespStatus {
    
    SUCCESS("0000","成功"),
    
    PARAM_INVALID("1000","缺少必傳參數(shù)")
    ;
    
    private String respCode;
    
    private String respDesc;
    
    private EnRespStatus(String respCode,String respDesc){
        this.respCode = respCode;
        this.respDesc = respDesc;
    }

    public String getRespCode() {
        return respCode;
    }

    public String getRespDesc() {
        return respDesc;
    }
}

5.編寫(xiě)ReqBaseVO類

package com.zccoder.valid.mvc.vo;

import java.io.Serializable;

public class ReqBaseVO implements Serializable{
    
    private static final long serialVersionUID = 7023512707419434863L;

    private String transId;
    
    private String systemCall;
    
    @Override
    public String toString() {
        return "ReqBaseVO [transId=" + transId + ", systemCall=" + systemCall + "]";
    }

    public String getTransId() {
        return transId;
    }

    public void setTransId(String transId) {
        this.transId = transId;
    }

    public String getSystemCall() {
        return systemCall;
    }

    public void setSystemCall(String systemCall) {
        this.systemCall = systemCall;
    }

}

6.編寫(xiě)RspBaseVO類

package com.zccoder.valid.mvc.vo;

import java.io.Serializable;

import com.zccoder.valid.mvc.constants.EnRespStatus;

public class RspBaseVO implements Serializable{
    
    private static final long serialVersionUID = 7023512707419434863L;

    private String respCode;
    
    private String respDesc;

    @Override
    public String toString() {
        return "RspBaseVO [respCode=" + respCode + ", respDesc=" + respDesc + "]";
    }
    
    public void setEnRespStatus(EnRespStatus enRespStatus){
        this.respCode = enRespStatus.getRespCode();
        this.respDesc = enRespStatus.getRespDesc();
    }
    
    public String getRespCode() {
        return respCode;
    }

    public void setRespCode(String respCode) {
        this.respCode = respCode;
    }

    public String getRespDesc() {
        return respDesc;
    }

    public void setRespDesc(String respDesc) {
        this.respDesc = respDesc;
    }
    
    
    
}

7.編寫(xiě)StoreReqVO類

package com.zccoder.valid.mvc.vo;

import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.NotBlank;

public class StoreReqVO extends ReqBaseVO{

    private static final long serialVersionUID = -342969591273353836L;
    
    @Size(min=2,max=5)
    @NotBlank
    private String name;
    
    @NotBlank
    private String desc;

    @NotBlank
    private String code;
    
    @Override
    public String toString() {
        return "StoreVO [name=" + name + ", desc=" + desc + ", code=" + code + "]";
    }
    
    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getName() {
        return name;
    }

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

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }
    
    
}

8.編寫(xiě)StoreRspVO類

package com.zccoder.valid.mvc.vo;

public class StoreRspVO extends RspBaseVO{

    private static final long serialVersionUID = -342969591273353836L;
    
    private String id;

    @Override
    public String toString() {
        return "StoreRspVO [id=" + id + "]";
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }
    
    
    
}

9.編寫(xiě)StoreRest類

package com.zccoder.valid.mvc.rest;

import javax.validation.Valid;

import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.zccoder.valid.mvc.constants.EnRespStatus;
import com.zccoder.valid.mvc.vo.StoreReqVO;
import com.zccoder.valid.mvc.vo.StoreRspVO;

@RestController
@RequestMapping("/store")
public class StoreRest {
    
    @PostMapping("/create")
    public StoreRspVO create(@Valid StoreReqVO reqVO,BindingResult result){
        StoreRspVO rspVO = new StoreRspVO();
        
        System.out.println("注冊(cè)成功:"+String.valueOf(reqVO.toString()));
        
        rspVO.setId(String.valueOf(System.currentTimeMillis()));
        rspVO.setEnRespStatus(EnRespStatus.SUCCESS);
        
        return rspVO;
    }
}

進(jìn)行驗(yàn)證

啟動(dòng)項(xiàng)目,并使用Postman測(cè)試效果如下

2-2 基于SpringBoot

工程創(chuàng)建

創(chuàng)建名為valid-boot的gradle工程build.gradle如下

// 使用SpringBoot插件
buildscript {
    ext {
        springBootVersion = "1.5.7.RELEASE"
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

apply plugin: "java"
apply plugin: "eclipse"
apply plugin: "org.springframework.boot"

repositories {
    mavenLocal()
    maven{ url "http://maven.aliyun.com/nexus/content/groups/public" }
    mavenCentral()
}

dependencies {

    compile("org.springframework.boot:spring-boot-starter-web")
    compile("org.springframework.boot:spring-boot-starter-aop")
    
    testCompile("org.springframework.boot:spring-boot-starter-test")
}

代碼編寫(xiě)

1.編寫(xiě)ValidBootStart類

package com.zccoder.valid.boot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ValidBootStart {

    public static void main(String[] args) {
        SpringApplication.run(ValidBootStart.class, args);
    }
}

2.編寫(xiě)ValidAdvisor類

package com.zccoder.valid.boot.aspect;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

import javax.validation.Valid;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import com.zccoder.valid.boot.vo.EnRespStatus;
import com.zccoder.valid.boot.vo.RspBaseVO;

/**
 * @Title JSR303數(shù)據(jù)校驗(yàn)切面
 * @Description 當(dāng)校驗(yàn)不通過(guò)時(shí),自動(dòng)處理校驗(yàn)結(jié)果,停止當(dāng)前請(qǐng)求,并響應(yīng)錯(cuò)誤提示
 * @author zc
 * @version 1.0 2017-11-08
 */
@Aspect
@Component
public class ValidAdvisor {

    // 通過(guò)@Pointcut注解聲明切點(diǎn)。
    @Pointcut("@annotation(org.springframework.web.bind.annotation.PostMapping)")
    public void annotationPointCut() {
    };
    
    @Around("annotationPointCut()")
    public Object doTest(ProceedingJoinPoint pjp) throws Throwable{
        
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
        
        @SuppressWarnings("rawtypes")
        Class retuenClazz = signature.getReturnType();
        Object retuenObject = retuenClazz.newInstance();
        
        if(!(retuenObject instanceof RspBaseVO)){
            throw new RuntimeException("方法"+method.getName()+"返回值類型非法");
        }
        
        RspBaseVO rspVO = (RspBaseVO)retuenObject;
        
        Object[] args = pjp.getArgs();
        
        Annotation[][] annotations = method.getParameterAnnotations();  
        for(int i = 0; i < annotations.length; i++){  
            if(!hasValidAnnotation(annotations[i])){  
                continue;  
            }  
            if(!(i < annotations.length-1 && args[i+1] instanceof BindingResult)){  
                //驗(yàn)證對(duì)象后面沒(méi)有跟bindingResult,事實(shí)上如果沒(méi)有應(yīng)該到不了這一步  
                continue; 
            }
            BindingResult result = (BindingResult) args[i+1];  
            if(result.hasErrors()){
                FieldError fieldError = result.getFieldError();
                rspVO.setEnRespStatus(EnRespStatus.PARAM_INVALID);
                rspVO.setRespDesc(fieldError.getField() + fieldError.getDefaultMessage());
                return rspVO;  
            }
        }
        return pjp.proceed();
    }
    
    /**
     * 校驗(yàn)是否有@Valid注解
     */
    private boolean hasValidAnnotation(Annotation[] annotations){  
        if(annotations == null){  
            return false;  
        }  
        for(Annotation annotation : annotations){  
            if(annotation instanceof Valid){  
                return true;  
            }  
        }  
        return false;  
    }
    
}

3.編寫(xiě)EnRespStatus類

package com.zccoder.valid.boot.vo;

public enum EnRespStatus {
    
    SUCCESS("0000","成功"),
    
    PARAM_INVALID("1000","缺少必傳參數(shù)")
    ;
    
    private String respCode;
    
    private String respDesc;
    
    private EnRespStatus(String respCode,String respDesc){
        this.respCode = respCode;
        this.respDesc = respDesc;
    }

    public String getRespCode() {
        return respCode;
    }

    public String getRespDesc() {
        return respDesc;
    }
}

4.編寫(xiě)ReqBaseVO類

package com.zccoder.valid.boot.vo;

import java.io.Serializable;

public class ReqBaseVO implements Serializable{
    
    private static final long serialVersionUID = 7023512707419434863L;

    private String transId;
    
    private String systemCall;
    
    @Override
    public String toString() {
        return "ReqBaseVO [transId=" + transId + ", systemCall=" + systemCall + "]";
    }

    public String getTransId() {
        return transId;
    }

    public void setTransId(String transId) {
        this.transId = transId;
    }

    public String getSystemCall() {
        return systemCall;
    }

    public void setSystemCall(String systemCall) {
        this.systemCall = systemCall;
    }

}

5.編寫(xiě)RspBaseVO類

package com.zccoder.valid.boot.vo;

import java.io.Serializable;

public class RspBaseVO implements Serializable{
    
    private static final long serialVersionUID = 7023512707419434863L;

    private String respCode;
    
    private String respDesc;

    @Override
    public String toString() {
        return "RspBaseVO [respCode=" + respCode + ", respDesc=" + respDesc + "]";
    }
    
    public void setEnRespStatus(EnRespStatus enRespStatus){
        this.respCode = enRespStatus.getRespCode();
        this.respDesc = enRespStatus.getRespDesc();
    }
    
    public String getRespCode() {
        return respCode;
    }

    public void setRespCode(String respCode) {
        this.respCode = respCode;
    }

    public String getRespDesc() {
        return respDesc;
    }

    public void setRespDesc(String respDesc) {
        this.respDesc = respDesc;
    }
    
    
    
}

6.編寫(xiě)StoreReqVO類

package com.zccoder.valid.boot.vo;

import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.NotBlank;

public class StoreReqVO extends ReqBaseVO{

    private static final long serialVersionUID = -342969591273353836L;
    
    @Size(min=2,max=5)
    @NotBlank
    private String name;
    
    @NotBlank
    private String desc;

    @NotBlank
    private String code;
    
    @Override
    public String toString() {
        return "StoreVO [name=" + name + ", desc=" + desc + ", code=" + code + "]";
    }
    
    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getName() {
        return name;
    }

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

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }
    
    
}

7.編寫(xiě)StoreRspVO類

package com.zccoder.valid.boot.vo;

public class StoreRspVO extends RspBaseVO{

    private static final long serialVersionUID = -342969591273353836L;
    
    private String id;

    @Override
    public String toString() {
        return "StoreRspVO [id=" + id + "]";
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }
    
    
    
}

8.編寫(xiě)StoreRest類

package com.zccoder.valid.boot.rest;

import javax.validation.Valid;

import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.zccoder.valid.boot.vo.EnRespStatus;
import com.zccoder.valid.boot.vo.StoreReqVO;
import com.zccoder.valid.boot.vo.StoreRspVO;

@RestController
@RequestMapping("/store")
public class StoreRest {
    
    @PostMapping("/create")
    public StoreRspVO create(@Valid StoreReqVO reqVO,BindingResult result){
        StoreRspVO rspVO = new StoreRspVO();
        
        System.out.println("注冊(cè)成功:"+String.valueOf(reqVO.toString()));
        
        rspVO.setId(String.valueOf(System.currentTimeMillis()));
        rspVO.setEnRespStatus(EnRespStatus.SUCCESS);
        
        return rspVO;
    }
}

進(jìn)行驗(yàn)證

啟動(dòng)項(xiàng)目,并使用Postman測(cè)試效果如下

參考資料
http://blog.csdn.net/chaijunk...
http://www.cnblogs.com/yangzh...

文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請(qǐng)注明本文地址:http://systransis.cn/yun/67982.html

相關(guān)文章

  • 使用jsr303規(guī)范驗(yàn)證數(shù)據(jù)

    摘要:我們有時(shí)需要對(duì)前端傳過(guò)來(lái)的數(shù)據(jù)做校驗(yàn),就可以使用。他可以使我們不用在每個(gè)編寫(xiě)校驗(yàn)代碼,可以達(dá)到解耦的功能。本文環(huán)境為,框架使用。 我們有時(shí)需要對(duì)前端傳過(guò)來(lái)的數(shù)據(jù)做校驗(yàn),就可以使用spring validation。他可以使我們不用在每個(gè)Controller編寫(xiě)校驗(yàn)代碼,可以達(dá)到解耦的功能。本文環(huán)境為jdk8,框架使用springboot 2.1.0.RELEASE。1.添加依賴 ...

    Pandaaa 評(píng)論0 收藏0
  • 使用spring validation 作為數(shù)據(jù)校驗(yàn)

    摘要:本文主要介紹在中自動(dòng)校驗(yàn)的機(jī)制。引入依賴我們使用構(gòu)建應(yīng)用來(lái)進(jìn)行演示。在中校驗(yàn)數(shù)據(jù)值得注意的地方參數(shù)前需要加上注解,表明需要對(duì)其進(jìn)行校驗(yàn),而校驗(yàn)的信息會(huì)存放到其后的中。層改寫(xiě)方法限定需要進(jìn)行校驗(yàn),而方法則不做限制。 簡(jiǎn)介 JSR303/JSR-349,hibernate validation,spring validation之間的關(guān)系。JSR303是一項(xiàng)標(biāo)準(zhǔn),JSR-349是其的升級(jí)版...

    huangjinnan 評(píng)論0 收藏0
  • SpringBoot 實(shí)戰(zhàn) (十五) | 服務(wù)端參數(shù)校驗(yàn)之一

    摘要:前言估計(jì)很多朋友都認(rèn)為參數(shù)校驗(yàn)是客戶端的職責(zé),不關(guān)服務(wù)端的事。輕則導(dǎo)致服務(wù)器宕機(jī),重則泄露數(shù)據(jù)。所以,這時(shí)就需要設(shè)置第二道關(guān)卡,服務(wù)端驗(yàn)證了。老項(xiàng)目的服務(wù)端校驗(yàn)不能為空不能為空看以上代碼,就一個(gè)的校驗(yàn)就如此麻煩。 前言 估計(jì)很多朋友都認(rèn)為參數(shù)校驗(yàn)是客戶端的職責(zé),不關(guān)服務(wù)端的事。其實(shí)這是錯(cuò)誤的,學(xué)過(guò) Web 安全的都知道,客戶端的驗(yàn)證只是第一道關(guān)卡。它的參數(shù)驗(yàn)證并不是安全的,一旦被有心人...

    QiShare 評(píng)論0 收藏0
  • JSR-303 參數(shù)校驗(yàn)

    摘要:參數(shù)校驗(yàn)代碼見(jiàn)常規(guī)使用請(qǐng)求參數(shù)加上符合校驗(yàn)注解包括基本類型和自定義類。校驗(yàn)注解是在方法入?yún)⑸?,則需要在該方法所在的類上添加注解,在入?yún)⑶盎蚴窃诜椒ㄉ咸砑訂⒂眯r?yàn)注解都不生效。校驗(yàn)注解使用在方法入?yún)⑸蠒r(shí),拋出的是異常。 JSR-303 參數(shù)校驗(yàn) 代碼見(jiàn)validator-demo 1、常規(guī)使用 1.1、請(qǐng)求參數(shù)加上符合JSR-303校驗(yàn)注解(包括基本類型和自定義類)。如果請(qǐng)求參數(shù)是自定...

    VishKozus 評(píng)論0 收藏0
  • Spring Boot - 表單校驗(yàn)JSR303&Hibernate Validator)

    摘要:初步使用主要使用注解的方式對(duì)進(jìn)行校驗(yàn),第一個(gè)例子在需要校驗(yàn)的字段上指定約束條件然后在中可以這樣調(diào)用,加上注解即可。如果校驗(yàn)失敗,默認(rèn)會(huì)返回框架的出錯(cuò)信息。指定到的分組名會(huì)全部進(jìn)行校驗(yàn),不指定的不校驗(yàn)。 Spring Boot - 表單校驗(yàn)(JSR303&Hibernate Validator) 回顧 Spring Boot - 初識(shí) Hello World Spring Boot -...

    tinyq 評(píng)論0 收藏0

發(fā)表評(píng)論

0條評(píng)論

187J3X1

|高級(jí)講師

TA的文章

閱讀更多
最新活動(dòng)
閱讀需要支付1元查看
<