关于jsp页面写pageContext.request.contextPath和request.getContextPath()等路径问题

版权声明:本文为博主原创文章,转载请附上博文链接 https://blog.csdn.net/weixin_40807247/article/details/89224859

我们在写jsp页面的时候,经常见到下面几个关于路径的写法:

${pageContext.request.contextPath}

属于EL表达式的写法

<%=request.getContextPath()%>

属于jsp的写法
作用都是取出部署的应用程序名,比如说一个地址http//:localhost:8080/hotel/login.jsp,如果我们需要用EL表达式写就是${pageContext.request.contextPath}/hotel/login.jsp,也可以写成<%=request.getContextPath()%>/hotel/login.jsp,这样都是没与问题的。
通常情况下,我们所写项目考虑到维护性,采用MVC思想,针对JSP主要是视图层代码,其他的代码最好不出现在其中
因此,我们习惯在项目jsp中采用EL表达式。

在运行我们发现了<%=request.getContextPath()%>和${pageContext.request.contextPath}获取的结果都是项目名(上下文),
如果我们想要获取项目的绝对路径和端口号我们有什么办法呢?
一般页面顶部都写:

    <%
    String basePath =request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    /%>

这个语句是用来拼装当前网页的相对路径的,
request.getSchema() 可以返回当前页面使用的协议,就是上面例子中的“https”。
request.getServerName() 可以返回当前页面所在的服务器的名字,就是上面例子中的“localhost"。
request.getServerPort() 可以返回当前页面所在的服务器使用的端口,就是80。
request.getContextPath() 可以返回当前页面所在的应用的名字,就是上面例子中的demo1。
这四个拼装起来的 basePath ,就是当前应用的跟路径了,
组合起来就是:https://localhost:80/demo1/

猜你喜欢

转载自blog.csdn.net/weixin_40807247/article/details/89224859