【问题标题】:Remove one parameter from the query string without using regex从查询字符串中删除一个参数而不使用正则表达式
【发布时间】:2019-08-06 09:06:27
【问题描述】:

所以我有一个网址是

String url = request.getRequestURL()+"?"+request.getQueryString();

有一个参数 Custom="true",我想在将其存储到 url 之前将其删除。 有没有任何有效的方法可以做到这一点,而不使用正则表达式。

Example - 

 http://myhost:8080/people?lastname=Fox&age=30&Custom=true&verified=yes

 request.getQueryString();  // "lastname=Fox&age=30&Custom=true&verified=yes"

Desired o/p - lastname=Fox&age=30&verified=yes

【问题讨论】:

  • 请提供queryString的示例值
  • request.getQueryString().replace("Custom=true&", "") 可能是?

标签: java spring string servlets request


【解决方案1】:

只需将Custom=true 替换为空字符串

query = query.replace("Custom=true&",""); 

【讨论】:

  • 我猜你没看懂这个问题,request.getQueryString() 已经在 ? 之后返回了字符串。从生成的字符串 lastname=Fox&age=30&Custom=true&verified=yes" ,我想删除 Custom=true
  • 它也会替换 otherCustom=true&
  • 参数是唯一的,因此不会成为问题。
【解决方案2】:

如果你想替换完全匹配,下面的代码可以工作。

String url = "http://myhost:8080/people?lastname=Fox&age=30&Custom=true&verified=yes";
    String newUrl = "";
    String[] splits = url.split("&");
    for(String split : splits) {
        if(!"Custom=true".equals(split)) {
            newUrl = newUrl+"&"+split;
        }
    }

【讨论】:

  • 如果“自定义”是查询字符串中的唯一参数,则此方法不起作用
【解决方案3】:

这是一个依赖于 Java 8 Streaming API 的解决方案:

    StringBuffer requestUrl = request.getRequestURL();
    String queryString = request.getQueryString();

    String[] queryStringParts = queryString.split("&");

    String newQueryString = Stream.of(queryStringParts)
            .filter(p -> !p.equals("Custom=true"))
            .collect(Collectors.joining("&"));

    String newUrl = StringUtils.hasText(newQueryString) ?
            requestUrl.append("?").append(newQueryString).toString() :
            requestUrl.toString();

请求 url 和查询字符串最初是分开的(如问题中所述)这一事实实际上也有帮助。

【讨论】:

    猜你喜欢
    • 2010-12-22
    • 2014-05-21
    • 2012-02-26
    • 2015-12-31
    • 2012-02-29
    • 1970-01-01
    • 2012-02-06
    • 1970-01-01
    相关资源
    最近更新 更多