Rebuilding a URL without a query string parameter

2019-08-09 16:54发布

Let's say I have a page which lists things and has various filters for that list in a sidebar. As an example, consider this page on ebuyer.com, which looks like this:

Screenshot of filter on ebuyer.com

Those filters on the left are controlled by query string parameters, and the link to remove one of those filters contains the URL of the current page but without that one query string parameter in it.

Is there a way in JSP of easily constructing that "remove" link? I.e., is there a quick way to reproduce the current URL, but with a single query string parameter removed, or do I have to manually rebuild the URL by reading the query string parameters, adding them to the base URL, and skipping the one that I want to leave out?

My current plan is to make something like the following method available as a custom EL function:

    public String removeQueryStringParameter(
            HttpServletRequest request, 
            String paramName, 
            String paramValue) throws UnsupportedEncodingException {

        StringBuilder url = new StringBuilder(request.getRequestURI());

        boolean first = true;
        for (Map.Entry<String, String[]> param : request.getParameterMap().entrySet()) {
            String key = param.getKey();
            String encodedKey = URLEncoder.encode(key, "UTF-8");

            for (String value : param.getValue()) {
                if (key.equals(paramName) && value.equals(paramValue)) {
                    continue;
                }
                if (first) {
                    url.append('?');
                    first = false;
                } else {
                    url.append('&');
                }
                url.append(encodedKey);
                url.append('=');
                url.append(URLEncoder.encode(value, "UTF-8"));
            }

        }
        return url.toString();
    }

But is there a better way?

1条回答
Ridiculous、
2楼-- · 2019-08-09 17:10

The better way is to use UrlEncodedQueryString.

UrlEncodedQueryString can be used to set, append or remove parameters from a query string:

 URI uri = new URI("/forum/article.jsp?id=2&para=4");
 UrlEncodedQueryString queryString = UrlEncodedQueryString.parse(uri);
 queryString.set("id", 3);
 queryString.remove("para");
 System.out.println(queryString);
查看更多
登录 后发表回答