web工程中URL地址的推荐写法

  在JavaWeb开发中,只要是写URL地址,那么建议最好以"/"开头,也就是使用绝对路径的方式,那么这个"/"到底代表什么呢?可以用如下的方式来记忆"/":如果"/"是给服务器用的,则代表当前的web工程,如果"/"是给浏览器用的,则代表webapps目录。

"/"代表当前web工程的常见应用场景

①.ServletContext.getRealPath(String path)获取资源的绝对路径

/**
* 1.ServletContext.getRealPath("/download/1.JPG")是用来获取服务器上的某个资源,
* 那么这个"/"就是给服务器用的,"/"此时代表的就是web工程
 * ServletContext.getRealPath("/download/1.JPG")表示的就是读取web工程下的download文件夹中的1.JPG这个资源
* 只要明白了"/"代表的具体含义,就可以很快写出要访问的web资源的绝对路径
*/
this.getServletContext().getRealPath("/download/1.JPG");

②.在服务器端forward到其他页面

this.getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);

③.使用include指令或者<jsp:include>标签引入页面

<jsp:include page="/jspfragments/demo.jsp" />
<%@include file="/jspfragments/head.jspf" %>

"/"代表webapps目录的常见应用场景

 

①.使用sendRedirect实现请求重定向

response.sendRedirect(request.getContextPath()+"/index.jsp");

②.使用超链接跳转

 <a href="${pageContext.request.contextPath}/index.jsp">跳转到首页</a>

③.js脚本和css样式文件的引用

<%--使用绝对路径的方式引用js脚本--%>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/index.js"></script>
<%--${pageContext.request.contextPath}与request.getContextPath()写法是得到的效果是一样的--%>
<script type="text/javascript" src="<%=request.getContextPath()%>/js/login.js"></script>
<%--使用绝对路径的方式引用css样式--%>
<link rel="stylesheet" href="${pageContext.request.contextPath}/css/index.css" type="text/css"/>

不以"/"开头的相对路径

  客户端中的url以浏览器中的url或者<base href>为基准,所以被转发的jsp页面,如果没有<base>标签,相对路径可能会被改变!

<a href="index.jsp">首页</a>
如果浏览器地址为localhost:8080/web/login.jsp,则跳转至localhost:8080/web/index.jsp 
如果浏览器地址为localhost:8080/web/servlet/login.action,则跳转到localhost:8080/web/servlet/index.jsp ×

  服务端中的url以当前servlet的路径为基准,不担心被转发。

 

posted on 2015-08-27 09:51  cbwleft  阅读(144)  评论(0)    收藏  举报