Servlet 获取文件目录
在web项目中,经常会用到配置文件。加载配置文件时就要需要目录
- 通过Request获取虚拟目录
@WebServlet("/failServlet")
public class FailServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String path = req.getContextPath();
//如果项目发布的虚拟目录是/day12
//则 path = "/day12"
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req,resp);
}
}
- 通过 ServletContext对象 获取文件真实路径
- 先说ServletContext对象的获取方式:
- 通过request对象获取
request.getServletContext();
- 通过HttpServlet获取
this.getServletContext();
- 通过Filter中的init的config获取
config.getServletContext();
、
- 通过request对象获取
- ServletContext对象的功能
- 获取MIME类型:
- 共享数据:(这也是域对象
- 获取文件的真实(服务器)路径 `getRealPath(“文件路径”)
文件位置 | 文件名 | 目录描述 |
---|---|---|
src | a.txt | “WEB-INF/classes/a.txt” |
web | b.txt | “/b.txt” |
web/WEB-INF | c.txt | “WEB-INF/c.txt” |
@WebServlet("/servletContextDemo5")
public class ServletContextDemo5 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
/**
* ServletContext第3个功能:
* 3. 获取文件的真实(服务器)路径
* 1. 方法:String getRealPath(String path)
*/
ServletContext context1 = this.getServletContext();
//获取文件的服务器路径
//1-web目录下的资源访问 "/"+文件名
String b_path = context1.getRealPath("/b.txt");
System.out.println(b_path);
//2-WEB-INF下的资源访问
String c_path = context1.getRealPath("WEB-INF/c.txt");
System.out.println(c_path);
//3-src目录下的资源访问
String a_path = context1.getRealPath("WEB-INF/classes/a.txt");
System.out.println(a_path);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req,resp);
}
}