重建没有查询字符串参数的URL [英] Rebuilding a URL without a query string parameter

查看:136
本文介绍了重建没有查询字符串参数的URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我有一个页面,其中列出了所有内容,并在边栏中为该列表提供了各种过滤器.例如,考虑

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:

左侧的那些过滤器由查询字符串参数控制,删除这些过滤器之一的链接包含当前页面的URL,但其中没有该查询字符串参数.

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.

JSP中是否有一种方法可以轻松地构建删除"链接?即,有一种快速方法来重现当前URL,但是要删除一个查询字符串参数,还是我必须通过读取查询字符串参数,将其添加到基本URL中,然后跳过一个查询字符串参数来手动重建URL.我想离开吗?

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?

我目前的计划是使类似以下方法的东西可用作自定义EL函数:

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

但是有更好的方法吗?

推荐答案

更好的方法是使用 UrlEncodedQueryString .

The better way is to use UrlEncodedQueryString.

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

这篇关于重建没有查询字符串参数的URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆