如何解决日期参数中的Trust Bound Violation问题?
解决Timestamp类型参数的Trust Bound Violation问题
针对this.queryDate = params.getDate();引发的信任边界违规问题,由于参数是Timestamp类型,无法直接使用常规ESAPI字符串验证器,可通过以下方式进行验证和清理:
时间范围校验
根据业务场景限定合法的时间区间,过滤超出范围的非法值:Timestamp inputDate = params.getDate(); long currentTime = System.currentTimeMillis(); // 示例:允许当前时间往前30天至往后7天的日期 long minValidTime = currentTime - 30L * 24 * 60 * 60 * 1000; long maxValidTime = currentTime + 7L * 24 * 60 * 60 * 1000; if (inputDate == null || inputDate.getTime() < minValidTime || inputDate.getTime() > maxValidTime) { throw new IllegalArgumentException("查询日期超出合法范围"); } this.queryDate = inputDate;业务规则校验
结合业务逻辑做针对性校验,比如限制只能是工作日、特定周期日期等:Timestamp inputDate = params.getDate(); if (inputDate == null) { throw new NullPointerException("查询日期不能为空"); } Calendar cal = Calendar.getInstance(); cal.setTime(inputDate); int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK); // 示例:禁止周末作为查询日期 if (dayOfWeek == Calendar.SATURDAY || dayOfWeek == Calendar.SUNDAY) { throw new IllegalArgumentException("查询日期不能为周末"); } this.queryDate = inputDate;有效性与格式清洗
通过格式化转换的方式过滤非法构造的Timestamp对象,同时校验日期有效性:Timestamp inputDate = params.getDate(); if (inputDate == null) { throw new NullPointerException("查询日期不能为空"); } // 使用严格模式的日期格式化,避免非法日期 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); sdf.setLenient(false); try { // 先转成标准格式字符串,再转回Timestamp,完成清洗 String safeDateStr = sdf.format(inputDate); Timestamp safeTimestamp = new Timestamp(sdf.parse(safeDateStr).getTime()); this.queryDate = safeTimestamp; } catch (ParseException e) { throw new IllegalArgumentException("查询日期格式无效"); }基础非空校验
最基础的校验,避免空值流入会话变量:Timestamp inputDate = params.getDate(); if (inputDate == null) { throw new NullPointerException("查询日期不能为空"); } this.queryDate = inputDate;
内容的提问来源于stack exchange,提问作者Alice Smith
相关产品推荐
相关产品推荐

