这几天在公司些项目的时候,发现项目中包含了request.getSchema(),request.getServerName(),request.getServerPort(),request.getContextPath()这几种方法,刚开始并不理解这几种方法在路径上的使用,经过网上的查询终于明白了他们的使用方式,因此在这里做个总结。
request.getSchema()可以返回当前页面使用的协议,http 或是 https;
request.getServerName()可以返回当前页面所在的服务器的名字;
request.getServerPort()可以返回当前页面所在的服务器使用的端口,就是80;
request.getContextPath()可以返回当前页面所在的应用的名字;
在程序中常用的写法为:
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
作为jsp页面中地址跳转的通用部分而存在,好处是在不同页面系统会给basepath赋予不同的地址名称,省去了在每个页面都要重新写地址的麻烦。