Java Web 常用实例

tomcat Java web 常用的实例

 

1,根据相对路径获取绝对路径

String realPath2 = WebServletUtil.getRealPath(request, path);

 第二个参数举例:"stub/appstore/queryProductPackage"

 

2,获取web服务器的根路径

/***
	 * @param request
	 * @return : http://10.1.253.44:81/tv_mobile
	 */
	public static String getServletUrl(HttpServletRequest request) {
		return request.getRequestURL().toString().replaceAll("(https?://[^/]+)/.*$", "$1") + request.getContextPath();
	}

该方法返回:http://10.1.253.44:81/tv_mobile 

注意:最后面没有斜杠

应用:

private static void setServletUrl(HttpServletRequest request, String path, ReadAndWriteResult readAndWriteResult) {
		String serverUrl = getServletUrl(request);//http://10.1.253.44:81/tv_mobile
		readAndWriteResult.setUrl(serverUrl + Constant2.Slash + path.replaceAll(".json$", SystemHWUtil.EMPTY));
	}

 

 

 

你可能感兴趣的:(获取绝对路径,获取web根url)