且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Java程序(J2EE + JSTL)中获取服务器文件夹的路径

更新时间:2023-09-19 14:01:58

您可以要求servlet上下文相对于实际路径进行转换:

You can ask servlet context to translate relative to real path:

context.getRealPath("/");

如果java类是servlet,你可能会做类似

If you java class is servlet, you can probably do something like

getServletConfig().getServletContext();

否则,jsp页面是一个servlet,所以你可以从那里传递它。

otherwise, jsp page is a servlet, so you can pass it from there.

最后,您可以在启动应用程序时选择一次:

Finally, you can pick it up once when you start your app:

public class AppStartup implements ServletContextListener {

    public void contextDestroyed(ServletContextEvent event) {
    }

    public void contextInitialized(ServletContextEvent event) {
        ServletContext context = event.getServletContext();
        // remember it in some static class for future use
    }
}

说完这一切之后,***是创建一个具有servlet上下文,解析路径,并使用已解析的文件路径调用类的servlet,最后将请求转发到jsp页面以显示结果。

Having said all this, it's probably better to make a servlet that has his servlet context, resolve path, and call your class with resolved path to a file, then finally forward request to a jsp page to display results.