String path = request.getContextPath()
WEB路径:
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"
很多朋友都想知道java如何获取请求域名?下面就一起来了解一下吧~
1、获取协议名和域名。
request.getScheme() //得到协议名 例如:http request.getServerName() //得到域名 localhost
2、获取全路径。
request.getRequestURL() //得到http://localhost:8888/CRM/loginController/login
3、获取请求所有参数 //map类型。
request.getParameterMap()
4、获取项目名
request.getContextPath() // /CRM
5、获取请求方法
request.getServletPath() // /loginController/login
/** * 获取当前访问URL (含协议、域名、端口号[忽略80端口]、项目名) * @param request * @return: String */ public static String getServerUrl(HttpServletRequest request) { // 访问协议 String agreement = request.getScheme() // 访问域名 String serverName = request.getServerName() // 访问端口号 int port = request.getServerPort() // 访问项目名 String contextPath = request.getContextPath() String url = "%s://%s%s%s" String portStr = "" if (port != 80) { portStr += ":" + port } return String.format(url, agreement, serverName, portStr, contextPath) }
getClass().getResource() 方法获得相对路径( 此方法在jar包中无效。返回的内容最后包含/)
例如 项目在/D:/workspace/MainStream/Test
在javaProject中,getClass().getResource("/").getFile().toString() 返回:/D:/workspace/MainStream/Test/bin/
public String getCurrentPath(){//取得根目录路径
String rootPath=getClass().getResource("/").getFile().toString()
//当前目录路径
String currentPath1=getClass().getResource(".").getFile().toString()
String currentPath2=getClass().getResource("").getFile().toString()
//当前目录的上级目录路径
String parentPath=getClass().getResource("../").getFile().toString()
return rootPath
}
参考资料:http://blog.csdn.net/hpf911/article/details/5852127