在 Java 中使用请求参数构造 URL

发布于 2024-11-18 23:16:09 字数 632 浏览 6 评论 0原文

我有一个通过 URL 访问的 servlet,并且该 URL 中有一些请求参数。现在我需要将用户重定向到不同的页面(从 servlet),而且还附加从请求中获取的请求参数。 这就是我正在做的

    StringBuffer sb=new StringBuffer("/test.jsp");
    sb.append( "?" );
    Enumeration en = request.getParameterNames();
    while( en.hasMoreElements() ){
        String paramName = (String) en.nextElement();
        sb.append( paramName );
        sb.append( "=" );
        sb.append(request.getParameter( paramName ));
        sb.append("&");
    }
           String constructedURLWithParams=sb.toString();

但问题是,有一个“&”它将添加到构造的 URL 的末尾。我不想再次进行一些字符串操作并删除尾随的“&”。您能建议一个更好的方法来做到这一点吗?

I've a servlet which is accessed through a URL and that URL has some request parameters in it. Now I need to redirect the user to a different page (from servlet), but also append the request parameters that I got from the request.
This is what I'm doing

    StringBuffer sb=new StringBuffer("/test.jsp");
    sb.append( "?" );
    Enumeration en = request.getParameterNames();
    while( en.hasMoreElements() ){
        String paramName = (String) en.nextElement();
        sb.append( paramName );
        sb.append( "=" );
        sb.append(request.getParameter( paramName ));
        sb.append("&");
    }
           String constructedURLWithParams=sb.toString();

But the problem is, there is a "&" which will be added towards the end of the constructed URL. I don't want to again do some string operation and remove the trailing "&". Can you please suggest a better way to do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

自控 2024-11-25 23:16:09

这是一个常见的场景。我将稍微简化一下以说明一些解决方案:


选项 #1 - 通过更改 StringBuffer 长度来删除最后一个字符:

StringBuffer sb = new StringBuffer();
Enumeration en = ...
while (en.hasMoreElements())
    sb.append(en.nextElement());
    sb.append(",");
}
if (sb.length() > 0) {
    sb.setLength(sb.length() - 1);
}
System.err.println(sb.toString());

选项 #2 - 如果缓冲区非空,则添加分隔符

StringBuffer sb = new StringBuffer();
Enumeration en = ...
while (en.hasMoreElements())
    if (sb.length() > 0) {
        sb.append(",");
    }
    sb.append(en.nextElement());
}
System.err.println(sb.toString());

选项 #3 - 如果存在则添加分隔符是更多元素...

StringBuffer sb = new StringBuffer();
Enumeration en = ...
while (en.hasMoreElements())
    sb.append(en.nextElement());
    if (en.hasMoreElements()) {
        sb.append(",");
    }
}
System.err.println(sb.toString());

选项 #4 - 如果这不是第一次循环,则添加分隔符...

StringBuffer sb = new StringBuffer();
Enumeration en = ...
boolean first = true;
while (en.hasMoreElements())
    if (first) {
        first = false;
    } else {
        sb.append(",");
    }
    sb.append(en.nextElement());
}
System.err.println(sb.toString());

哪个最好取决于您正在执行的操作的精确细节以及性能的重要性。


最后我应该指出,在组装一般 URL 和查询字符串时,您需要更加小心。例如,您需要正确转义参数名称和值中非“未保留”(根据 URL 规范)的任何字符。如果您不小心,您可能最终会得到一个向您的网站注入 XSS 攻击的向量。

This is a common scenario. I'm going to simplify it a bit to illustrate some solutions:


Option #1 - remove the last character by changing the StringBuffer length:

StringBuffer sb = new StringBuffer();
Enumeration en = ...
while (en.hasMoreElements())
    sb.append(en.nextElement());
    sb.append(",");
}
if (sb.length() > 0) {
    sb.setLength(sb.length() - 1);
}
System.err.println(sb.toString());

Option #2 - add the separator if the buffer is non empty

StringBuffer sb = new StringBuffer();
Enumeration en = ...
while (en.hasMoreElements())
    if (sb.length() > 0) {
        sb.append(",");
    }
    sb.append(en.nextElement());
}
System.err.println(sb.toString());

Option #3 - add the separator if there are more elements ...

StringBuffer sb = new StringBuffer();
Enumeration en = ...
while (en.hasMoreElements())
    sb.append(en.nextElement());
    if (en.hasMoreElements()) {
        sb.append(",");
    }
}
System.err.println(sb.toString());

Option #4 - add the separator if this is not the first time round the loop ...

StringBuffer sb = new StringBuffer();
Enumeration en = ...
boolean first = true;
while (en.hasMoreElements())
    if (first) {
        first = false;
    } else {
        sb.append(",");
    }
    sb.append(en.nextElement());
}
System.err.println(sb.toString());

Which is best depends on the precise details of what you are doing, and how important performance is.


I should finally note that you need to be a bit more careful when assembling URLs in general and query strings. For instance, you need to properly escape any characters that are not "unreserved" (according to the URL specification) in the parameter names and values. If you are careless, you might end up with a vector for injection of XSS attacks into your website.

゛清羽墨安 2024-11-25 23:16:09

请参阅这个问题如何轻松地从某种集合中构建字符串:在 Java 中用分隔符连接值列表的最优雅的方法是什么?

另外,您的代码有一个错误:您必须转义这些值,因为两者paramName及请求参数中可以包含&等非法字符。为此,请使用 URLEncoder.encode(value, "UTF-8")

See this question how to easily build a String from some kind of collection: What's the most elegant way to concatenate a list of values with delimiter in Java?

Also your code has a bug: You have to escape the values since both paramName and the request parameters can contain & and other illegal characters. Use URLEncoder.encode(value, "UTF-8") for that.

夏末染殇 2024-11-25 23:16:09

只需附加 "?" + request.getQueryString() (如果参数在 URL 中传递 - 查询字符串包含所有获取参数)

如果不是,那么您的方法似乎没问题。只要有

if (en.hasMoreElements()) sb.append("&");

Simply append "?" + request.getQueryString() (if the parameters are passed in the URL - the query string contains all the get parameters)

If they aren't, then your approach seems fine. Just have

if (en.hasMoreElements()) sb.append("&");
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文