一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

java中servlet得到完整的URL的例子

时间:2022-06-29 02:38:15 编辑:袖梨 来源:一聚教程网

servlet中通过HttpServletRequest 可以得到 URI的各个部分,自行组装得到完整的URL
servlet得到完整的URL方法

 代码如下 复制代码

// Example: http://myhost:8080/people?lastname=Fox&age=30

String uri = request.getScheme() + "://" +   // "http" + "://
             request.getServerName() +       // "myhost"
             ":" + request.getServerPort() + // ":" + "8080"
             request.getRequestURI() +       // "/people"
            (request.getQueryString() != null ? "?" +
             request.getQueryString() : ""); // "?" + "lastname=Fox&age=30"
.getScheme() will give you "https"if it was a https://domain request.
.getServerName() gives domain on http(s)://domain.
.getServerPort() will give you the port.

下面是可用代码片段:

 代码如下 复制代码

String uri = request.getScheme() + "://" +
             request.getServerName() +
             ("http".equals(request.getScheme()) && request.getServerPort() == 80 || "https".equals(request.getScheme()) && request.getServerPort() == 443 ? "" : ":" + request.getServerPort() ) +
             request.getRequestURI() +
            (request.getQueryString() != null ? "?" + request.getQueryString() : "");

热门栏目