gpt4 book ai didi

java - 其余搜索参数验证

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:14:45 26 4
gpt4 key购买 nike

我有一个 rest 端点,它将具有以下 3 个参数的 url 视为有效:regno、hostid、位置regno, domid, 位置regno, 供应商

除这些组合之外的任何组合均无效。我有一个 validator 方法来检查这个

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 语句这一事实。如果有更好的可读性方法,请随时提供帮助。

最佳答案

您可以尝试以下方法,它将大大减少 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");

关于java - 其余搜索参数验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42824995/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com