1. 程式人生 > >獲取web應用完整的專案地址(是http地址,不是磁碟路徑)

獲取web應用完整的專案地址(是http地址,不是磁碟路徑)

一、程式碼實現

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

三、參考連結