路径

前端路径问题

相对路径

背景:图片存在项目/sataic/img文件夹下面
三种情况

  1. 当html文件与static文件夹同级,直接src="satic/img/logo.png"
  2. 当html不与static文件夹同级,则需要用../来抵消当前url的后缀,再拼接src="satic/img/logo.png"
  3. WEB-INF文件夹下的html文件要引用img里的图片:首先得通过请求转发才能进如html文件,通过servlet的getRequestDispatcher("WEB-INF/views/view1.html"),此时客户端地址栏实际上是localhost:8080/web03/servlet,然后再通过拼接,不需要../

绝对路径

  • 寻找方式就是在基准路径(http://localhost:8080)后面拼接src属性值(/web03/static/img/logo.png),得到的正是目标资源访问的正确路径

绝对路径情况1:web/index.html中引入web/static/img/logo.png

绝对路径情况2:web/a/b/c/test.html中引入web/static/img/logo.png

绝对路径情况3:web/WEB-INF/views/view1.html中引入web/static/img/logo.png

不论html文件在哪,ser始终都是<img src="/web03/static/img/logo.png">

base标签的使用

base标签定义页面相对路径公共前缀

  • base 标签定义在head标签中,用于定义相对路径的公共前缀
  • base 标签定义的公共前缀只在相对路径上有效,绝对路径中无效
  • 如果相对路径开头有 ./ 或者../修饰,则base标签对该路径同样无效

index.html 和a/b/c/test.html 以及view1Servlet 中的路径处理

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!--定义相对路径的公共前缀,将相对路径转化成了绝对路径-->
    <base href="/web03_war_exploded/">
</head>
<body>
    <img src="static/img/logo.png">
</body>
</html>

重定向中的路径问题

目标,由某个文件夹下的servletA重定向到另一个文件夹下的html

@WebServlet("/x/y/z/servletA")
public class ServletA extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        
    }
}

相对路径

绝对路径

  • ServletA重定向的路径 : /web03/a/b/c/test.html
  • 寻找方式就是在基准路径(http://localhost:8080)后面拼接(/web03/a/b/c/test.html),得到( http://localhost:8080/web03/a/b/c/test.html)正是目标资源访问的正确路径
  • 绝对路径中需要填写项目上下文路径,但是上下文路径是变换的
    • 可以通过 ServletContext的getContextPath()获取上下文路径
    • 可以将项目上下文路径定义为 / 缺省路径,那么路径中直接以/开头即可
//绝对路径中,要写项目上下文路径
//resp.sendRedirect("/web03/a/b/c/test.html");
// 通过ServletContext对象动态获取项目上下文路径
//resp.sendRedirect(getServletContext().getContextPath()+"/a/b/c/test.html");
// 缺省项目上下文路径时,直接以/开头即可
resp.sendRedirect("/a/b/c/test.html");

请求转发中的路径问题

相对路径写法

绝对路径写法

  • 请求转发只能转发到项目内部的资源,其绝对路径无需添加项目上下文路径
  • 请求转发绝对路径的基准路径相当于http://localhost:8080/web03(前端喝重定向的基准都是/8080)
  • 在项目上下文路径为缺省值时,也无需改变,直接以/开头即可
@WebServlet("/x/y/servletB")
public class ServletB extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        RequestDispatcher requestDispatcher = req.getRequestDispatcher("/a/b/c/test.html");
        requestDispatcher.forward(req,resp);
    }
}

目标资源内相对路径处理

posted @ 2024-02-25 22:56  不会des  阅读(97)  评论(0)    收藏  举报