在Java开发中路径是一个无法避免的问题,笔者在多次遇到这样的问题之后打算写一篇博客来总结一下。
b.jsp中的代码
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title></head><body> <h4>BBB Page</h4> <a href="c.jsp">To C Page</a></body></html>c.jsp中的代码
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title></head><body> <h4>CCC Page</h4> <a href="../a.jsp">To A Page</a></body></html>三个jsp中的代码很简单,就是超链接的路径写的是相对路径,不通过Servelt可以正常访问。但是通过Servlet,写一个TestServlet的代码如下:
package com.lsy.javaweb;import java.io.IOException;import java.util.Arrays;import java.util.List;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/** * Servlet implementation class TestServlet */@WebServlet("/testServlet")public class TestServlet extends HttpServlet { PRivate static final long serialVersionUID = 1L; /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //模拟从数据库中查询数据 List<String> cities = Arrays.asList("北京","上海","广州"); request.setAttribute("cities", cities); //通过转发方式响应 request.getRequestDispatcher("/path/b.jsp").forward(request, response); }}在测试中可以发现从a.jsp通过Servlet可以正常访问b.jsp,但是b.jsp则无法通过相对路径访问c.jsp,可以发现相对路径带来的问题。在通过Servlet访问b.jsp时网页的路径变为该项目下http://localhost:8080/session_Learn/testServlet,由b.jsp到c.jsp,jsp页面在path路径下,就出现了问题。 a.jsp->/Servlet -转发->b.jsp(有一个超链接:和b.jsp在同一路径下的c.jsp)->无法得到页面。
2)编写绝对路径可以避免上述问题 ①在javaweb中什么是“绝对路径”,即任何的路径都要加上contextPath. 相对于当前WEB应用的根路径的路径,以当前项目为例,Session_Learn/a.jsp,a.jsp是相对于当前web应用的,则称他是绝对路劲。Session_Learn其实是contextPath(当前web应用的上下文路径) http://localhost:8080/testServlet 这个就不是 ②如何完成编写: 1. 若/代表的是站点的根目录, 则在其前面加上contextPath就可以了。<a href="testServlet">To B page</a>
–><a href=<%=request.getContextPath()%>"testServlet">To B page</a>
3). JavaWeb中的/的特殊含义 ①.当前WEB应用的根路径,若/需交由Servlet容器来处理:http://localhost:8080/contextPath/testServlet 1. 请求转发时,request.getRequestDispatcher(“/path/b.jsp”).forward(request, response); 2. web.xml配置文件中映射Servlet访问路径: 3. 各种定制标签中的/
②.当前WEB站点的根路径http://localhost:8080/,若/交由浏览器解析 1. 超链接:<a href="testServlet">To B page</a>
2. 表达中的action:<form action="/login.jsp">
3. 请求重定向的时候:response.sendRedirect(“/a.jsp”)
新闻热点
疑难解答