相对路径和绝对路径
创建一个web项目,在webroot的目录下新建两个界面
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <!-- /doMain.jsp 前台路径: 如果带 / 它的参照路径是 http://localhost:8080/ tomcat服务器的根路径 doMain.jsp 前台路径: 如果不带 / 它的参照路径是http://localhost:8080/UrlTest/ web项目的根路径 --> <a href="doMain.jsp">跳转</a> </body> </html>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<body> <h1>这是处理界面....</h1> </body>
在webroot下面新创建一个jsp文件夹,之后再jsp文件夹下面创建两个界面
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<body> <%-- 这个TestServlet没有增加/ 默认的参照路径是 项目根目录 --%> <a action="TestServlet">跳转</a> </body>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<body> <h1>这是jsp文件夹下面处理界面....</h1> </body>
创建对应的servlet
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class TestServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); // doPost() } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("进入了servlet......"); /** * /jsp/doMain.jsp 后台路径 加 / 参照路径就是项目的根目录 * request.getRequestDispatcher("/jsp/doMain.jsp").forward(request, * response); */ /** * 重定向 比较特殊! 因为是客户端的行为,至少两次访问服务器,再第二次访问服务器的时候,就是前台路径了, * 这个时候 不能加 / */ response.sendRedirect("/jsp/doMain.jsp"); } }
======================解决路径叠加的问题======================
在webroot下面创建两个界面
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<body> <a href="test/MyServlet">跳转</a> </body>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<body> <%-- 这样会出现问题 <a href="test/MyServlet">跳转</a> --%> <a href="${pageContext.request.contextPath}/test/MyServlet">跳转</a> </body>
一定要修改web.xml中MyServlet的url为 test/MyServlet
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class MyServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); // doPost() } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.getRequestDispatcher("/2.jsp").forward(request, response); } }
作者:Rick__想太多先森
出处:http://www.cnblogs.com/xtdxs/
注意:本文仅代表个人理解和看法哟!和本人所在公司和团体无任何关系!