在我的 servlet 中:
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
new Action();
}
在我的 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("") 。
我该怎么做?
最佳答案
您可以使用 ServletContext.getRealPath()
获取 Web 资源的实际文件系统路径。方法。
ServletContext ctx = request.getServletContext();
String path = ctx.getRealPath("/");
并修改您的 Action
以将请求或 servlet 上下文作为参数:
public Action(ServletContext ctx) {
System.out.println("--> " + ctx.getRealPath("/"));
}
关于java - 使用 getResource 方法时如何获取 webApp 位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16092024/