Java HttpServletRequest 完成 URL
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2222238/
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
HttpServletRequest to complete URL
提问by flybywire
I have an HttpServletRequest
object.
我有一个HttpServletRequest
对象。
How do I get the complete and exact URL that caused this call to arrive at my servlet?
如何获取导致此调用到达我的 servlet 的完整且准确的 URL?
Or at least as accurately as possible, as there are perhaps things that can be regenerated (the order of the parameters, perhaps).
或者至少尽可能准确,因为也许有些东西可以重新生成(也许是参数的顺序)。
采纳答案by Bozho
The HttpServletRequest
has the following methods:
将HttpServletRequest
有以下几种方法:
getRequestURL()
- returns the part of the full URL before query string separator character?
getQueryString()
- returns the part of the full URL after query string separator character?
getRequestURL()
- 返回查询字符串分隔符之前的完整 URL 部分?
getQueryString()
- 在查询字符串分隔符之后返回完整 URL 的部分?
So, to get the full URL, just do:
因此,要获取完整的 URL,只需执行以下操作:
public static String getFullURL(HttpServletRequest request) {
StringBuilder requestURL = new StringBuilder(request.getRequestURL().toString());
String queryString = request.getQueryString();
if (queryString == null) {
return requestURL.toString();
} else {
return requestURL.append('?').append(queryString).toString();
}
}
回答by Michael Borgwardt
Combining the results of getRequestURL()
and getQueryString()
should get you the desired result.
相结合的结果getRequestURL()
,并getQueryString()
应该得到你想要的结果。
回答by Vinko Vrsalovic
HttpUtil being deprecated, this is the correct method
HttpUtil 被弃用,这是正确的方法
StringBuffer url = req.getRequestURL();
String queryString = req.getQueryString();
if (queryString != null) {
url.append('?');
url.append(queryString);
}
String requestURL = url.toString();
回答by Teja Kantamneni
// http://hostname.com/mywebapp/servlet/MyServlet/a/b;c=123?d=789
public static String getUrl(HttpServletRequest req) {
String reqUrl = req.getRequestURL().toString();
String queryString = req.getQueryString(); // d=789
if (queryString != null) {
reqUrl += "?"+queryString;
}
return reqUrl;
}
回答by Mat B.
I use this method:
我用这个方法:
public static String getURL(HttpServletRequest req) {
String scheme = req.getScheme(); // http
String serverName = req.getServerName(); // hostname.com
int serverPort = req.getServerPort(); // 80
String contextPath = req.getContextPath(); // /mywebapp
String servletPath = req.getServletPath(); // /servlet/MyServlet
String pathInfo = req.getPathInfo(); // /a/b;c=123
String queryString = req.getQueryString(); // d=789
// Reconstruct original requesting URL
StringBuilder url = new StringBuilder();
url.append(scheme).append("://").append(serverName);
if (serverPort != 80 && serverPort != 443) {
url.append(":").append(serverPort);
}
url.append(contextPath).append(servletPath);
if (pathInfo != null) {
url.append(pathInfo);
}
if (queryString != null) {
url.append("?").append(queryString);
}
return url.toString();
}
回答by abishkar bhattarai
You can use filter .
您可以使用过滤器。
@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException {
HttpServletRequest test1= (HttpServletRequest) arg0;
test1.getRequestURL()); it gives http://localhost:8081/applicationName/menu/index.action
test1.getRequestURI()); it gives applicationName/menu/index.action
String pathname = test1.getServletPath()); it gives //menu/index.action
if(pathname.equals("//menu/index.action")){
arg2.doFilter(arg0, arg1); // call to urs servlet or frameowrk managed controller method
// in resposne
HttpServletResponse httpResp = (HttpServletResponse) arg1;
RequestDispatcher rd = arg0.getRequestDispatcher("another.jsp");
rd.forward(arg0, arg1);
}
donot forget to put <dispatcher>FORWARD</dispatcher>
in filter mapping in web.xml
不要忘记<dispatcher>FORWARD</dispatcher>
在 web.xml 中放入 过滤器映射
回答by Kishor Prakash
Use the following methods on HttpServletRequest object
在 HttpServletRequest 对象上使用以下方法
java.lang.String getRequestURI()-Returns the part of this request's URL from the protocol name up to the query string in the first line of the HTTP request.
java.lang.String getRequestURI()- 返回此请求的 URL 部分,从协议名称到 HTTP 请求第一行中的查询字符串。
java.lang.StringBuffer getRequestURL()-Reconstructs the URL the client used to make the request.
java.lang.StringBuffer getRequestURL() -重建客户端用来发出请求的 URL。
java.lang.String getQueryString()-Returns the query string that is contained in the request URL after the path.
java.lang.String getQueryString()- 返回包含在请求 URL 中路径后的查询字符串。
回答by Peter Szanto
In a Spring project you can use
在 Spring 项目中,您可以使用
UriComponentsBuilder.fromHttpRequest(new ServletServerHttpRequest(request)).build().toUriString()
回答by ziesemer
Somewhat late to the party, but I included this in my MarkUtils-Web libraryin WebUtils- Checkstyle-approved and JUnit-tested:
有点迟到了,但我在这包含MarkUtils的Web库在WebUtils- Checkstyle的认可和JUnit测试:
import javax.servlet.http.HttpServletRequest;
public class GetRequestUrl{
/**
* <p>A faster replacement for {@link HttpServletRequest#getRequestURL()}
* (returns a {@link String} instead of a {@link StringBuffer} - and internally uses a {@link StringBuilder})
* that also includes the {@linkplain HttpServletRequest#getQueryString() query string}.</p>
* <p><a href="https://gist.github.com/ziesemer/700376d8da8c60585438"
* >https://gist.github.com/ziesemer/700376d8da8c60585438</a></p>
* @author Mark A. Ziesemer
* <a href="http://www.ziesemer.com."><www.ziesemer.com></a>
*/
public String getRequestUrl(final HttpServletRequest req){
final String scheme = req.getScheme();
final int port = req.getServerPort();
final StringBuilder url = new StringBuilder(256);
url.append(scheme);
url.append("://");
url.append(req.getServerName());
if(!(("http".equals(scheme) && (port == 0 || port == 80))
|| ("https".equals(scheme) && port == 443))){
url.append(':');
url.append(port);
}
url.append(req.getRequestURI());
final String qs = req.getQueryString();
if(qs != null){
url.append('?');
url.append(qs);
}
final String result = url.toString();
return result;
}
}
Probably the fastest and most robust answer here so far behind Mat Banik's - but even his doesn't account for potential non-standard port configurations with HTTP/HTTPS.
可能是迄今为止最快和最可靠的答案,落后于 Mat Banik 的 - 但即使是他的也没有考虑使用 HTTP/HTTPS 的潜在非标准端口配置。
See also:
也可以看看:
回答by Johannes Stadler
You can write a simple one liner with a ternary and if you make use of the builder pattern of the StringBuffer from .getRequestURL()
:
您可以使用三元编写一个简单的单行代码,并且如果您使用来自.getRequestURL()
以下内容的 StringBuffer 的构建器模式:
private String getUrlWithQueryParms(final HttpServletRequest request) {
return request.getQueryString() == null ? request.getRequestURL().toString() :
request.getRequestURL().append("?").append(request.getQueryString()).toString();
}
But that is just syntactic sugar.
但这只是语法糖。