共計 747 個字符,預計需要花費 2 分鐘才能閱讀完成。
在 Java 中,可以使用 HttpServletRequest 對象來獲取當前請求的 URL 以及服務器根路徑。可以按照以下步驟來獲取:
- 在處理請求的方法中,添加 HttpServletRequest 對象作為參數。
public void handleRequest(HttpServletRequest request, HttpServletResponse response) {// 處理請求的代碼
}
- 使用 HttpServletRequest 對象的方法來獲取請求的 URL 和服務器根路徑。
String requestUrl = request.getRequestURL().toString();
String requestUri = request.getRequestURI();
String contextPath = request.getContextPath();
String serverPath = requestUrl.substring(0, requestUrl.indexOf(contextPath) + contextPath.length());
在上述代碼中,request.getRequestURL().toString()
可以獲取當前請求的完整 URL,request.getRequestURI()
可以獲取當前請求的 URI(不包括服務器根路徑),request.getContextPath()
可以獲取服務器根路徑。
注意:通過 request.getRequestURL().toString()
獲取的 URL 是包含協議、主機和端口號的完整 URL,如果只想獲取相對路徑,可以使用 request.getRequestURI()
和request.getContextPath()
來拼接。
丸趣 TV 網 – 提供最優質的資源集合!
正文完