web项目中的真实路径与虚拟路径

在web项目中的真实路径和 虚拟路径

在这里插入图片描述

真实路径

项目在服务器上真实存在的路径。

方法:String getRealPath(String path)

context的获取方式:

  1. 通过request对象获取
    request.getServletContext();
  2. 通过HttpServlet获取
    this.getServletContext();
 String b = context.getRealPath("/访问资源名称");
 //web目录下资源访问
    
  
 String c = context.getRealPath("/WEB-INF/资源名称");
 //WEB-INF目录下的资源访问
     
  
 String a = context.getRealPath("/WEB-INF/classes/资源名称");
 //src目录下的资源访问
  

虚拟目录

就是浏览器上的路径

 String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";

结果:在这里插入图片描述
① request.getScheme()可以返回当前页面使用的协议;默认返回http,SSL时返回https;
② request.getServerName()可以返回当前页面所在的服务器的名字;

③ request.getServerPort()可以返回当前页面所在的服务器使用的端口,就是项目在服务器上发布的 端口,或者在本地tomcat容器运行时发布的端口,我用的是8080;
④ request.getContextPath()可以返回当前页面所在的应用的名字即项目名称;

发布了42 篇原创文章 · 获赞 142 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_43688587/article/details/105285523
今日推荐