从 HttpServletRequest 中提取上下文路径和其他 URL 信息



我正在本地主机端口 8080 中运行我的应用程序。基本网址为:http://localhost:8080/EMSApplication/otherparts...

现在从HttpServletRequest如何提取部分 http://localhost:8080/EMSApplication?

目前我正在这样做:

String schema = request.getScheme();
String serverName = request.getServerName();
int serverPort = request.getServerPort();
String contextPath = request.getContextPath();
String path = schema + "://" + serverName + ":" + serverPort + contextPath;
System.out.println(path);

这里的请求是HttpServletRequest的实例。

这个程序对吗?

还有其他方法可以获取信息吗?

如果我托管我的应用程序并说 URL http://my.domain.com/EMSApplication/otherparts...那么上述程序代码会起作用吗?


我发现的另一种方式:

String requestUrl = request.getRequestURL().toString();
String contextPath = request.getContextPath();
String path = requestUrl.substring(0, requestUrl.indexOf(contextPath) + contextPath.length());

我需要这个的地方:

HttpServletRequest request = (HttpServletRequest) getRequest().getContainerRequest();
String requestUrl = request.getRequestURL().toString();
String contextPath = request.getContextPath();
String path = requestUrl.substring(0, requestUrl.indexOf(contextPath) + contextPath.length());          
submitLink.add(new WebMarkupContainer("submitImage").add(new AttributeModifier("src", path + "/ASSETS/css/images/login-btn.png")));

我正在开发一个 Wicket 应用程序,我需要在其中指定<img/>的 src。

无论哪种方式都很好,但我更喜欢第一种。没有比这更直接的想法了,尽管如果您解释为什么需要此值,可能会有。

最新更新