一、代码实现
public class WebUtils {
/**
* 获取web应用的根路径(url访问地址,如http://localhost:8090/mywebapp)
* @return
*/
public static String getWebappRootUrl() {
HttpServletRequest request = ServletActionContext.getRequest();
String scheme = request.getScheme();
String serverName = request.getServerName();
int serverPort = request.getServerPort();
String contextPath = request.getContextPath();
// root根路径
String webappRootUrl = scheme + "://" + serverName + ":" + serverPort + contextPath;
return webappRootUrl;
}
}
二、代码测试
public String test() {
String webappRootUrl = WebUtils.getWebappRootUrl();
System.out.println();
}
假设用户通过请求http://www.test.cn:8090/mywebapp/test进入到上面的test方法,可以看到控制台打印出
http://www.test.cn:8090/mywebapp
三、参考链接
https://blog.csdn.net/wangcunhuazi/article/details/40627611
https://stackoverflow.com/questions/2204870/how-to-get-domain-url-and-application-name