吐槽:在自定义类中(如:javabean),无法获取项目根目录路径,反正我试过的没有 ServletContext获取项目根目录路径:import javax.servlet.ServletContext; 1.前端jsp中获取 application.getRealPath("/"); 2.后端Servlet中获取 ServletContext application = this.getServletContext();//获得ServletContext对象 out.println( application.getRealPath("/") ); 结果:D:\apache-tomcat-9.0.63\webapps\liboke\ 获取项目根目录路径: request.getRealPath("/"); 或 request.getSession().getServletContext().getRealPath("/"); 结果:D:\apache-tomcat-9.0.63\webapps\liboke\ 注:用request最方便 获取浏览器地址路径: //浏览器地址:http://localhost/liboke/index request.getRequestURL(); //结果:http://localhost/liboke/index request.getRequestURI(); //结果:liboke/index request.getContextPath(); //结果:/liboke request.getServletPath(); //结果:/index 备注: 1.其它一些信息可以查看内置对象request的方法 2.前端jsp中直接使用request 3.后端需要在Servlet类中 doPost、doGet 方法里使用