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

在Javaweb开发中,只要写URL地址,建议以“/”开头,也就是使用绝对路径的方式。

“/”:如果是给服务器的,代表当前的web工程。给浏览器的,代表webapps目录

代表web工程

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

2,在服务器端forward到其他页面

 /**
 * 2.forward
  * 客户端请求某个web资源,服务器跳转到另外一个web资源,这个forward也是给服务器用的,
 * 那么这个"/"就是给服务器用的,所以此时"/"代表的就是web工程
*/ this.getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);

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

<jsp:include page="/jspfragments/demo.jsp" />
<%@include file="/jspfragments/head.jspf" %> 代表的都是web工程

代表webapps目录

1,使用sendRedirect实现请求重定向
使用request.getContextPath()代替"/项目名称",推荐使用这种方式,灵活方便!
2,使用超链接跳转

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

3,Form表单提交

 <form action="/JavaWeb_HttpServletResponse_Study_20140615/servlet/CheckServlet" method="post">    
         <input type="submit" value="提交">
 </form>
改进:
 <form action="${pageContext.request.contextPath}/servlet/CheckServlet" method="post">
          <input type="submit" value="提交">
 </form>

${pageContext.request.contextPath}的效果等同于request.getContextPath(),两者获取到的都是"/项目名称"

4,js脚本和css样式文件的引用

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