Java web 中几个常用的获取项目路径的方法

来源:互联网 发布:水电安装 知乎 编辑:程序博客网 时间:2024/06/03 21:02

request.getContextPath()

<%=request.getContextPath()%>是为了解决相对路径的问题,可返回站点的根路径,即项目名称。
如果context中没有配置path属性,所以你的工程文件就是在根目录下,相当于path=”“,request.getContextPath()获得的值也就为空;

request.getScheme()
返回的协议名称,默认是http

request.getServerName()
返回的是你浏览器中显示的主机名,你自己试一下就知道了

request.getServerPort()
获取服务器端口号

<%String path = request.getContextPath();// 获得项目完全路径(假设你的项目叫MyApp,那么获得到的地址就是http://localhost:8080/MyApp/):String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%>