【问题标题】:How can i get the webApp location when using getResource method?使用 getResource 方法时如何获取 webApp 位置?
【发布时间】:2013-04-12 02:28:50
【问题描述】:

在我的 servlet 中:

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 new Action();
}

在我的动作类中:

Action(){
    System.out.println("--> " + this.getClass().getResource("/").toString());
}

我有结果,这个位置:

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

但我想像这样访问我的 webApp 的根目录: file:/C:/Users/saad/Desktop/apache-tomcat-7.0.37/wtpwebapps/Serveur/

我坚持 Action 类不继承自 HttpServlet,所以我不能使用 ServletContext.getResource("") 。

我该怎么做?

【问题讨论】:

  • 如果您无法修改您的 Action 类以将请求作为参数获取(我看不出有什么好的理由不...),那么您已经有了您的类文件夹的路径。您应该能够从中计算出您的路径。虽然,如果它是用于在 Web 应用程序中存储文件,正如您在我的回答中所建议的那样,我建议您另作考虑。
  • 您究竟需要这些信息做什么?请不要说你需要这个来写入文件。

标签: java jakarta-ee servlets web-applications getresource


【解决方案1】:

您可以使用ServletContext.getRealPath()方法获取Web资源的实际文件系统路径。

ServletContext ctx = request.getServletContext();
String path = ctx.getRealPath("/");

并修改您的 Action 以将请求或 servlet 上下文作为参数:

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

【讨论】:

  • Action类没有继承HttpServlet的问题,所以无法执行ServletContext.getRealPath()或ServletContext.getResource()
  • +1。准确地给出了OP的要求。哎呀,或者是))但无论如何+1
  • 就我而言,当我运行 Action 类时,我想在此位置创建一个 ZIP 文件:/WebApp/accounts/
  • 我不建议像这样将文件存储在 webapp 文件夹中(如果它在 web 应用程序本身内部?)。它只有在 web 应用程序被分解时才有效,并且它可以在重新部署时被覆盖。最好将它们完全存储在应用程序服务器之外的某个地方,并通过 servlet/init 参数或某个地方的属性使位置可配置。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-10-24
  • 1970-01-01
  • 2011-02-05
  • 1970-01-01
  • 2013-11-05
相关资源
最近更新 更多