前后台分离式开发后端判断参数类型

版权声明:转载标注 孙德超 -Q-2466536634 https://blog.csdn.net/weixin_44395185/article/details/89451559

前后台分离式开发后端判断参数类型

前后段分离式开的发时 后端定好所接收的数据类型
往往由前端进行数据格式的校验 但是也会有后端进行校验的时候
这样往往可以精确的定位给前端是哪里的数据出现的问题,以便前端展示给用户
使界面交互更加友好

这时有人会问 @RequestBody注解接收对象参数的时候,怎样才不会报400错误呢???
难道写个拦截器进行参数类型判断??

不用,我们可以使用@RequestBody(Map<String , Object>)的形式来接收参数 然后根据建来取出需要判断的数据

虽然麻烦带点 但是确实可以实现前后端分离式开发时 后端进行参数判断的需求!!

外附上      
参数判断类型的工具类

package com.boot.base.common.util;


import java.text.ParseException;
import java.text.SimpleDateFormat;

/**
 * 判断数据类型
 */
public class IsDataType {

    /**
     *
     * @param obj  需要判定的数据
     * @return     是否为规定格式的日期类型
     */
    private static boolean isValidDate(Object obj) {
        boolean convertSuccess = true;
        if (obj != null) {
            // 指定日期格式为四位年/两位月份/两位日期,注意yyyy/MM/dd区分大小写;
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                // 设置lenient为false.
                // 否则SimpleDateFormat会比较宽松地验证日期,比如2007/02/29会被接受,并转换成2007/03/01
                format.setLenient(false);
                format.parse(obj.toString());
            } catch (ParseException e) {
                // e.printStackTrace();
                // 如果throw java.text.ParseException或者NullPointerException,就说明格式不对
                convertSuccess = false;
            }
        } else {
            convertSuccess = false;
        }

        return convertSuccess;
    }

    /**
     *
     * @param obj  需要判断的数据
     * @param c    判定为的类型
     * @return      正误
     */
    private static Boolean isDataType(Object obj, Class c) {
        boolean convertSuccess ;
        if (obj != null) {
            if (obj.getClass().equals(c)) {
                convertSuccess = true;
            }else{
                convertSuccess = false;
            }
        } else {
            convertSuccess = false;
        }
        return convertSuccess;
    }


}

猜你喜欢

转载自blog.csdn.net/weixin_44395185/article/details/89451559