JSP和servlet之间的相对路径和绝对路径

来源:互联网 发布:play for java 编辑:程序博客网 时间:2024/05/29 15:20

1. JSP页面跳转到Servlet

<body>
<h1>servlet路径跳转</h1>
<hr>
<!-- 使用相对路径访问HelloServlet -->
<!-- /servlet/HelloServlet 这里/表示服务器更目录 localhost/servlet/HelloServlet -->
<a href="servlet/HelloServlet">相对路径访问HelloServlet</a>
<hr>

<!-- 使用绝对路径访问HelloServlet 可以使用 String path=request.getContextPath(); path表示项目根目录-->
<a href="<%=path %>/servlet/HelloServlet">绝对路径访问HelloServlet</a><br>

<!-- 表单中action的url写法与超链接相同 -->

<hr>
<a href="servlet/TestServlet">访问TestServlet,跳转到test.jsp</a>
</body>


2. Servlet跳转到JSP页面

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //请求重定向, 当前路径ServletPathDirection/servlet/
        //response.sendRedirect(request.getContextPath() + "/test.jsp");//可以
        response.sendRedirect("../test.jsp");//这样也可以的
        //response.sendRedirect("/test.jsp");//不可以, 此时斜线/表示服务器更目录
    
        //服务器内部转发 此时斜线/表示项目更目录
        //request.getRequestDispatcher("/test.jsp").forward(request, response);//可以
        //request.getRequestDispatcher("../test.jsp").forward(request, response);//可以
        //下面不可以 HTTP Status 404 - /ServletPathDirection/ServletPathDirection/test.jsp
        //request.getRequestDispatcher(request.getContextPath() +"/test.jsp").forward(request, response);//不可以
    }
0 0
原创粉丝点击