在servlet中获取请求URL [英] Getting request URL in a servlet

查看:105
本文介绍了在servlet中获取请求URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道以下两种在servlet中获取请求URL的方法之间的区别。

I want to know the difference between the below two methods of getting a request URL in servlet.

方法1:

String url = request.getRequestURL().toString();

方法2:

url = request.getScheme()
      + "://"
      + request.getServerName()
      + ":"
      + request.getServerPort()
      + request.getRequestURI();

上述两种方法是否有可能提供两个不同的网址?

Are there any chances that the above two methods will give two different URLs?

推荐答案

getRequestURL() 当该方案为时,该端口为80 http ,或当方案是 https 时为443。

The getRequestURL() omits the port when it is 80 while the scheme is http, or when it is 443 while the scheme is https.

所以,只需使用 getRequestURL()即可获得整个网址。但是,这不包括GET查询字符串。您可能希望按如下方式构造它:

So, just use getRequestURL() if all you want is obtaining the entire URL. This does however not include the GET query string. You may want to construct it as follows then:

StringBuffer requestURL = request.getRequestURL();
if (request.getQueryString() != null) {
    requestURL.append("?").append(request.getQueryString());
}
String completeURL = requestURL.toString();

这篇关于在servlet中获取请求URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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