Servert context的常用方法
getInitparameter(String Name) 根据名称范围全局配置参数
getContextpath() 获取应用的虚拟目录
getRealpath()根据虚拟目录获取绝对路径
获取路径根据位置不同也可以用字节码的方式以下就列举根据虚拟目录获取绝对路径的代码有不同的方式可以参考,自己写的仅供参考
public class ServitContext1 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String path = this.getClass().getClassLoader().getResource("a.txt").getPath();
System.out.println(path);
ServletContext servletContext = getServletContext();
String realPath3 = servletContext.getRealPath("/WEB-INF/classes/a.txt");
System.out.println(realPath3);
System.out.println("---------------------------------------");
String path1 = this.getClass().getResource("b.txt").getPath();
System.out.println(path1);
String realPath = servletContext.getRealPath("WEB-INF/classes/com.wo.code/b.txt");
System.out.println(realPath);
System.out.println("--------------------------------------------------");
String realPath1 = servletContext.getRealPath("c.txt");
System.out.println(realPath1);
System.out.println("-----------------------------------------");
String realPath2 = servletContext.getRealPath("/WEB-INF/d.txt");
System.out.println(realPath2);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}