【问题标题】:Rest Search Parameters Validation休息搜索参数验证
【发布时间】:2017-03-16 03:51:58
【问题描述】:

我有一个休息端点,它将具有以下 3 个参数的 url 视为有效: regno, hostid, 位置 雷尼奥, domid, 位置 regno,提供者

除了这些组合之外的任何东西都是无效的。 我有一个验证器方法来检查这个

if (!StringUtils.isEmpty(criteria.getRegno())) {
if ((!StringUtils.isEmpty(criteria.getHostid()) || !StringUtils.isEmpty(criteria.getDomId())) && !StringUtils.isEmpty(criteria.getLocation())) {
criteria.setSearchType(GET_HOST_SEARCH_TYPE);
} else if (!StringUtils.isEmpty(criteria.getProvider()) && (StringUtils.isEmpty(criteria.getLocation()) && StringUtils.isEmpty(criteria.getHostid) && StringUtils.isEmpty(criteria.getDomId()))) {
criteria.setSearchType(GET_PROVIDER_SEARCH_TYPE);
} else {
throw new BadRequestException("Either Provider, Location, Hostid or domid is missing");
}
} else {
throw new BadRequestException("Regno is missing");
}

我不喜欢我使用大量 if else 语句的事实。如果有更好的可读方式,请随时提供帮助。

【问题讨论】:

  • 给出一个带参数的有效完整url字符串示例
  • localhost/search?location=india&regno=12532&hostid=gdy-101

标签: java algorithm if-statement hashmap truthtable


【解决方案1】:

您可以尝试以下方法,它将大大减少 if else 的需求..

    public String detectSearchType(String url) throws BadRequestException{
        final String condition1 = "(?=.*location)(?=.*(?:hostid|domid))";
        final String condition2 = "(?=.*provider)(?!.*hostid)(?!.*domid)(?!.*location)";

        if(!url.contains("regno="))
            throw new BadRequestException("Regno is missing");
        else if(Pattern.compile(condition1).matcher(url).find())
            return "GET_HOST_SEARCH_TYPE";
        else if(Pattern.compile(condition2).matcher(url).find())
            return "GET_PROVIDER_SEARCH_TYPE";
        else 
            throw new BadRequestException("Either Provider, Location, Hostid or domid is missing");

    }

您需要将 url 字符串传递给此方法。例如:

detectSearchType("localhost/search?location=india&regno=12532&hostid=gdy-101");
detectSearchType("localhost/search?location=india&regno=12532&domid=gdy-101");
detectSearchType("localhost/search?regno=12532&provider=mrt");
detectSearchType("localhost/search?regno=12532&provider=mrt&host=abul");
detectSearchType("localhost/abc?regno=1&hostid=2");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-11
    • 1970-01-01
    • 2023-03-24
    • 2013-03-27
    • 2012-12-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多