ServletContext读取web中的资源文件

     servletcontext类字面上的意思是servlet是上下文,但是实际上就是在一个web项目里面就只有一个servlet,所获取到的这个类的对象都是只有一个的;

     他的方法特别多,今天只介绍如何获取资源文件;

      1.原来老的方法有下面的用properties类来做:
       //1.创建属性
        Properties properties = new Properties();
        
        //2.指定载入的数据源
        InputStream is = new FileInputStream("src/config.properties");
        properties.load(is);
        
        //3.获取name属性的值
        String name = properties.getProperty("name");
        System.out.println("name="+name);

     2. 但是可以用下面的方法会更好ServletContext接口的getRealPath(Stringpath)方法返回的是资源文件在服务器文件系统上的真实路径(带有盘符)。

参数path代表资源文件的虚拟路径,它应该以正斜线(/)开始,“/“表示当前web应用的根目录,也可以不以“/“开始。

示例如下:

public class PathServlet extends HttpServlet{

    publicvoid doGet(HttpServletRequest request, HttpServletResponse response)

           throwsServletException, IOException {

//”/”表示web应用的根路径

        ServletContextservletContext=this.getServletContext();

        String path=servletContext.getRealPath("/");

       System.out.println(path);

       String indexPath=servletContext.getRealPath("/index.jsp");

       System.out.println(indexPath);

    }

}

3.也可以用set集合获取一大批的资源文件:

ServletContext servletcontext = this.getServletContext();
        Set<String> paths = (Set<String>) servletcontext.getResourceAsStream("/WEB-INF");
        System.out.println(paths);

猜你喜欢

转载自blog.csdn.net/rnzhiw/article/details/83343898