使用 Java 中的请求参数构造 URL
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6622366/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Construct a URL with Request Parameters in Java
提问by Apps
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
我有一个通过 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();
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?
但问题是,在构造的 URL 末尾会添加一个“&”。我不想再做一些字符串操作并删除尾随的“&”。你能建议一个更好的方法来做到这一点吗?
采纳答案by Bozho
Simply append "?" + request.getQueryString()
(if the parameters are passed in the URL - the query string contains all the get parameters)
简单地追加"?" + request.getQueryString()
(如果参数在 URL 中传递 - 查询字符串包含所有获取参数)
If they aren't, then your approach seems fine. Just have
如果不是,那么您的方法似乎很好。只要有
if (en.hasMoreElements()) sb.append("&");
回答by Stephen C
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:
选项 #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());
Option #2 - add the separator if the buffer is non empty
选项 #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());
Option #3 - add the separator if there are more elements ...
选项 #3 - 如果有更多元素,请添加分隔符...
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 ...
选项 #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());
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.
最后我要指出的是,在组合一般 URL 和查询字符串时需要更加小心。例如,您需要正确地转义参数名称和值中不是“未保留”(根据 URL 规范)的任何字符。如果您粗心大意,最终可能会得到一个向量,用于将 XSS 攻击注入您的网站。
回答by Aaron Digulla
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?
请参阅此问题如何轻松地从某种集合构建字符串:在 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.
您的代码也有一个错误:您必须对值进行转义,因为paramName
请求参数和请求参数都可以包含&
其他非法字符。URLEncoder.encode(value, "UTF-8")
为此使用。