Java 使用getResource方法时如何获取webApp位置?

Java 使用getResource方法时如何获取webApp位置?,java,jakarta-ee,servlets,web-applications,getresource,Java,Jakarta Ee,Servlets,Web Applications,Getresource,在我的servlet中: protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { new Action(); } 在我的动作课上: Action(){ System.out.println("--> " + this.getClass().getResource("/").toString());

在我的servlet中:

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 new Action();
}
在我的动作课上:

Action(){
    System.out.println("--> " + this.getClass().getResource("/").toString());
}
我对结果进行了分析,该位置:

-->
文件:/C:/Users/saad/Desktop/apache-tomcat-7.0.37/wtpwebapps/Serveur/WEB-INF/classes/

但我想访问我的webApp的根目录,如下所示:
文件:/C:/Users/saad/Desktop/apache-tomcat-7.0.37/wtpwebapps/Serveur/

我坚持认为Action类不是从HttpServlet继承的,所以我不能使用ServletContext.getResource(“”)


如何执行此操作?

您可以使用方法获取web资源的实际文件系统路径

并修改
操作
,将请求或servlet上下文作为参数:

public Action(ServletContext ctx) {
    System.out.println("--> " + ctx.getRealPath("/"));
}

Action类没有从HttpServlet继承的问题,因此我无法执行ServletContext.getRealPath()或ServletContext.getResource()+1。完全符合OP的要求。Oops,或者是+1在我的例子中,当我运行Action类时,我想在这个位置创建一个ZIP文件:/WebApp/accounts/我不建议像那样将文件存储在WebApp文件夹中(如果它在webapplication本身内部?)。只有当web应用程序被分解时,它才能工作,并且在重新回复时它可能被覆盖。最好将它们完全存储在您的应用程序服务器之外的某个位置,并通过servlet/init参数或某个位置的属性来配置位置。如果您无法修改
Action
类以获取作为参数的请求(我看不出有什么好的理由不…),我们将,您已经有了类文件夹的路径。你应该能够从中计算出你的路径。不过,如果是为了在web应用程序中存储文件,正如您在我的回答中所建议的那样,我建议您不要这样想。您需要这些信息的具体目的是什么?请不要说你需要这个来写文件。
public Action(ServletContext ctx) {
    System.out.println("--> " + ctx.getRealPath("/"));
}