获取URL到webapp上下文(基本URL) [英] getting URL to a webapp context (the base URL)

查看:132
本文介绍了获取URL到webapp上下文(基本URL)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时您需要在servlet / JSP /基于 HttpServletRequest 的内容中构建Web应用程序上下文的完整URL。
http://server.name:8080/context/ 之类的东西。 Servlet API没有一种方法可以实现这一点。

Sometimes you need to construct a full URL to your web app context inside a servlet/JSP/whatever based on HttpServletRequest. Something like http://server.name:8080/context/. Servlet API doesn't have a single method to achieve this.

直接的方法是将所有URL组件附加到 StringBuffer ,例如

The straightforward approach is to append all URL components to a StringBuffer, like

ctxUrl = sb.append(req.getScheme()).append("://")
.append(req.getgetServerName()).append(":")
.append(req.getServerPort()) etc

我想知道这个替代方案是否有任何问题(速度提高了10倍):

I wonder if there's anything wrong with this alternative (which is 10 times faster):

ctxUrl = req.getRequestURL();
ctxUrl = ctxUrl.substring(0, ctxUrl.lastIndexOf("/")));

以上两种方法总是会产生相同的结果吗?

Will two above methods always produce the same result?

推荐答案

它被称为基本网址(您可以在HTML中使用的网址< base> 标签)。你可以按如下方式获得它:

It's called the "base URL" (the one you could use in HTML <base> tag). You can obtain it as follows:

StringBuffer url = req.getRequestURL();
String uri = req.getRequestURI();
String ctx = req.getContextPath();
String base = url.substring(0, url.length() - uri.length() + ctx.length()) + "/";

您的 ctxUrl.substring(0,ctxUrl.lastIndexOf(/) )); 方法将在具有多个文件夹的URL上失败,例如 http://server.name:8080/context/folder1/folder2/folder3

Your ctxUrl.substring(0, ctxUrl.lastIndexOf("/"))); approach will fail on URLs with multiple folders like http://server.name:8080/context/folder1/folder2/folder3.

  • How to use relative paths without including the context root name? (for a JSP answer)
  • How get the base URL? (for a JSF answer)

这篇关于获取URL到webapp上下文(基本URL)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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