Rebuilding a URL without a query string parameter

让人想犯罪 __ 提交于 2019-12-11 10:42:49

问题


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:

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:


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);


来源:https://stackoverflow.com/questions/35021262/rebuilding-a-url-without-a-query-string-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!