相对路径的获取拼接

对于相对路径的拼接,今天好好整理了一下,主要如下:

对于当前网页的相对路径主要的拼接如下:
<%
String path=request.getContextPath();
String basePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+pat h+"/";
%>
比如页面内部有个完整的链接: http://localhost:8082/myblog/aaaa/login.action
其中http://server/是服务器的基本路径,myblog是当前应用程序的名字,我的根目录是http://localhost:8082/myblog/

总结:
request.getSchema()可以返回当前页面使用的协议,就是上面路径的"http";
request.getServerName()可以返回当前页面所在的服务器的名字,就是上面例子的“localhost”;
request.getServerPort()可以返回当前页面所在的服务器使用的端口号,就是8082;
request.getContextPath()可以返回当前页面所在的应用的名字,就是上面例子中的"myblog";
这四个拼接起来,就是当前应用的根路径了。
注意事项:
request.getProtocol();
获取客户端向服务端传送数据所依据的协议名称。
request.getScheme()
可以返回当前页面使用的协议,http或者https
以上是路径前端的拼接,在java后端的拼接

/**
     * 取web应用的绝对路径,带端口和根目录 格式为:http://10.97.69.205:8080/app/
     * 
     * @param request
     * @return
     */
    public static String getWebRoot(HttpServletRequest request) {
        StringBuffer sbRoot = new StringBuffer(50);
        String protocol = request.getProtocol();//表示的是‘http’
        int port = request.getServerPort();//表示的是ip、或者是localhost
        String serverName = request.getServerName();//获取对应的项目的名称
        sbRoot.append(serverName);
        if(protocol.toLowerCase().startsWith("https")){
            sbRoot.insert(0, "https://");
            if(port != 443){
                sbRoot.append(":").append(port);
            }
        }else if(protocol.toLowerCase().startsWith("http")){
            sbRoot.insert(0, "http://");
            if(port != 80){
                sbRoot.append(":").append(port);
            }
        }

        String strContextPath = request.getContextPath();
        if (strContextPath != null && !strContextPath.equals("/")){
            sbRoot.append(strContextPath);
        }

        sbRoot.append("/");
        return sbRoot.toString();
    }



前台






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值