关于web工程中java类如何获取webapp路径下的文件

来源:互联网 发布:病假条淘宝暗语大全 编辑:程序博客网 时间:2024/05/18 02:50

1.需要创建一个servlet继承ServletContextListener监听器

2.web.xml配置监听器,

<listener>
<listener-class>com.stee.configurationmanagement.init.TestWebPath</listener-class>
</listener>

3.如果需要servlet在web容器启动的时候就实例化,可以配置<load-on-startup>1</load-on-startup>,大于0.

4.监听器在servlet实例化的时候会调用contextInitialized(ServletContextEvent servletContextEvent)方法,然后在这个方法中使用这个方法的参数即可获取webapp路径

String webRootPath = servletContextEvent.getServletContext()        .getRealPath("/"); System.out.println(webRootPath);if (webRootPath == null) {    try {        webRootPath = servletContextEvent.getServletContext()                .getResource("/").getFile();        System.out.println(webRootPath);    } catch (MalformedURLException e) {        LoggerUtil.logger.info(("获取WEBROOT失败!"));    }}

0 0