spring mvc校验

阅读更多

 

spring  mvc校验

 

1,引入jar

 

javax.validation

validation-api

org.hibernate

hibernate-validator

 

2,配置

 

xml:

 

       

       

       

   

   

       

       

   

   

       

   

 

 

ValidationMessages:

notEmpty.message={field}\u4E0D\u80FD\u4E3A\u7A7A

phone.message=\u624B\u673A\u53F7\u4E0D\u6B63\u786E

number.message={field}\u5FC5\u987B\u4E3A\u7EAF\u6570\u5B57

json.message={field}\u4E0D\u662FJson\u5B57\u7B26\u4E32\u7C7B\u578B

jsonArray.message={field}\u4E0D\u662FJsonArray\u5B57\u7B26\u4E32\u7C7B\u578B

 

 

 

3,使用

 

 

 

  @RequestMapping("apply")

    @ResponseBody

    public ApiResponse insureApply(@Valid @RequestBody InsureApplyRequest insureApplyRequest, Errors errors) throws Exception {

        //验证参数

        checkError(errors);----spring入参的一级校验

Class insureCheckBean = factoryBank.getInsureCheckBean(insureApplyRequest.getBankType());

  Object object = JSONObject.parseObject(insureApplyRequest.getInsureInfo(), insureCheckBean);

   String checkResult = BeanUtils.checkBean(object);----里面的json转化成实体之后的二级校验

}

 

 

////可以放在base control

    /**

     * 校验请求参数

     * @param errors

     * @throws ParamException

     */

    public void checkError(Errors errors) throws ParamException {

        if(errors.hasErrors()){

            List fieldErrors = errors.getFieldErrors();

            StringBuffer buffer = new StringBuffer();

            for(FieldError fieldError:fieldErrors){

               //String field = fieldError.getField();

                String message = fieldError.getDefaultMessage();

                buffer.append(message).append("; ");

            }

            throw new ParamException(CodeEnum.CODE_0002.getMsg()+"{"+buffer.toString()+"}");

        }

    }

 

 

 

 

 

 

 

 

 

 

 

 

 

自定义校验(一般用于二级校验)

 

 

1,实体中用相关的注解--可以自定义也可以用框架的(此时没有用springmvc本身校验)

 

    变化大的字段不必常规建立一个表涵盖所有字段,只要用一个字段存储json即可,用的时候根据类型转化   这一个字段所在实体可以spring入参的时候校验

    里面的那个字段转化成实体后就不能在入参的时候校验,可以自定义工具类,结合注解(校验的时候可以spring valid和自定义根据注解自己用工具类校验结合---分层校验)

 

 

 

 

package com.houbank.bank.util.base;

 

import com.alibaba.fastjson.JSONArray;

import com.alibaba.fastjson.JSONObject;

import com.houbank.bank.util.base.tst.APIFlowRequest;

import com.houbank.bank.util.base.tst.InsuredGuRelatedParty;

import com.houbank.bank.util.component.annotation.IsJsonArray;

import org.apache.commons.lang3.StringUtils;

import org.hibernate.validator.constraints.NotEmpty;

 

import javax.validation.Valid;

import java.lang.reflect.Field;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

 

/**

 * Created by zhangzhile on 2017/11/10.

 */

public class BeanUtils {

 

 

    /**

     * 检查bean中的必要参数

     *

     * @param object

     * @return

     * @throws Exception

     */

    public static String checkBean(Object object) throws Exception {

        Class cls = object.getClass();

        StringBuilder stringBuilder = new StringBuilder();

        for (; cls != Object.class; cls = cls.getSuperclass()) {

            Field[] fieldes = cls.getDeclaredFields();

            for (Field field : fieldes) {

                field.setAccessible(true);

                NotEmpty annotation = field.getAnnotation(NotEmpty.class);

                IsJsonArray isJsonArray = field.getAnnotation(IsJsonArray.class);

 

                if (annotation != null

                        && StringUtils.isBlank((String) field.get(object))) {

                    stringBuilder.append(field.getName());

                    stringBuilder.append(";");

                }

                if (isJsonArray != null

                        && !JsonUtils.isJsonArrayString((String) field.get(object))) {

                    stringBuilder.append(field.getName());

                    stringBuilder.append(";");

                }

            }

        }

        return stringBuilder.toString();

    }

 

    /**

     * 检查bean中含有List的必要参数

     *

     * @param object

     * @return

     * @throws Exception

     */

    public static String checkBeans(Object object) throws Exception {

        Class cls = object.getClass();

        StringBuilder stringBuilder = new StringBuilder();

        for (; cls != Object.class; cls = cls.getSuperclass()) {

            Field[] fieldes = cls.getDeclaredFields();

            for (Field field : fieldes) {

                field.setAccessible(true);

                NotEmpty annotation = field.getAnnotation(NotEmpty.class);

                IsJsonArray isJsonArray = field.getAnnotation(IsJsonArray.class);

                Valid valid = field.getAnnotation(Valid.class);

 

                if (annotation != null

                        && StringUtils.isBlank((String) field.get(object))) {

                    stringBuilder.append(field.getName());

                    stringBuilder.append(";");

                }

                if (isJsonArray != null

                        && !JsonUtils.isJsonArrayString((String) field.get(object))) {

                    stringBuilder.append(field.getName());

                    stringBuilder.append(";");

                }

                if (valid != null

                        && !ArrayIsNotNull.isNull( (List)field.get(object))) {

                    List os=(List) field.get(object);

                   for(Object o :  os){

                       checkBean(stringBuilder,o);

                   }

                }else if(valid != null && ArrayIsNotNull.isNull( (List)field.get(object))){

                    stringBuilder.append(field.getName());

                    stringBuilder.append(";");

                }

            }

        }

        return stringBuilder.toString();

    }

 

 

    /**

     * 检查bean中的必要参数增加参数

     *

     * @param object

     * @return

     * @throws Exception

     */

    public static String checkBean(StringBuilder stringBuilder,Object object) throws Exception {

        Class cls = object.getClass();

        for (; cls != Object.class; cls = cls.getSuperclass()) {

            Field[] fieldes = cls.getDeclaredFields();

            for (Field field : fieldes) {

                field.setAccessible(true);

                NotEmpty annotation = field.getAnnotation(NotEmpty.class);

                IsJsonArray isJsonArray = field.getAnnotation(IsJsonArray.class);

 

                if (annotation != null

                        && StringUtils.isBlank((String) field.get(object))) {

                    stringBuilder.append(field.getName());

                    stringBuilder.append(";");

                }

                if (isJsonArray != null

                        && !JsonUtils.isJsonArrayString((String) field.get(object))) {

                    stringBuilder.append(field.getName());

                    stringBuilder.append(";");

                }

            }

        }

        return stringBuilder.toString();

    }

 

    public static void main(String[] args) throws Exception {

            APIFlowRequest aPIFlowRequest=new APIFlowRequest();

            aPIFlowRequest.setClientCode("111");

            aPIFlowRequest.setPolicySort("222");

List list=new ArrayList();

            InsuredGuRelatedParty ins=new InsuredGuRelatedParty();

            ins.setInsuredName("33");

            ins.setInsuredIdentity("55");

list.add(ins);

            aPIFlowRequest.setInsuredGuRelatedPartyDtoList(list);

            JSONArray.toJSON(list);

            String json = JSONObject.toJSONString(aPIFlowRequest);

Map map=new HashMap<>();

            checkBeans(aPIFlowRequest);

//map.put("", "");

//student.setMap(map);

//isNullAndThrowExp(new String[]{"age","nameString","isPeople","list","map"},student,student.getAge(),student.getNameString(),student.isPeople(),student.getList(),student.getMap());

}

}

 

 

 

 

 

 

  • 新建文件夹__2_.rar (8.4 KB)
  • 下载次数: 0

你可能感兴趣的:(校验)