Java 从HttpServletRequest提取上下文路径和其他URL信息
我正在本地主机端口8080上运行我的应用程序。基本url是: 现在从Java 从HttpServletRequest提取上下文路径和其他URL信息,java,url,servlets,Java,Url,Servlets,我正在本地主机端口8080上运行我的应用程序。基本url是: 现在从HttpServletRequest如何提取该部分 目前我正在这样做: String schema = request.getScheme(); String serverName = request.getServerName(); int serverPort = request.getServerPort(); String contextPath = request.getContextPath(); String pa
HttpServletRequest
如何提取该部分
目前我正在这样做:
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);
这里的request是HttpServletRequest
的实例
这个程序对吗
有没有其他方法来获取信息
如果我托管我的应用程序并说URL是。。。那么上述程序代码是否有效
我发现的另一个方法是:
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应用程序,其中需要指定
的src,这两种方法都可以,但我更喜欢第一种。没有比这更直接的了,尽管如果您解释了为什么需要这个值,可能会有。谢谢。我已经更新了我的答案来解释这个场景。你能告诉我为什么喜欢第一个吗?我更喜欢第一个,因为第二个将在根上下文中中断,其中上下文路径是零长度字符串。考虑到您正在做的事情,您可能可以进行一些优化,以避免多次执行相同的操作,但在Servlet API中没有任何有用的东西。