Java如何获取Web应用程序的真实路径?

此代码可帮助您获取在服务器上部署Web应用程序的物理路径。这可能很有用,因此您可以在服务器上读取或写入文件。但是请注意,此方法仅在以爆炸方式部署Web应用程序时才有效,如果以某种war格式部署,则该getRealPath()方法只需return即可null。

package org.nhooo.example.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class GetWebApplicationPathServlet extends HttpServlet {

    public GetWebApplicationPathServlet() {
        super();
    }

    protected void doGet(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {

        String path = getServletContext().getRealPath("/");
        PrintWriter writer = res.getWriter();
        writer.println("Application path: " + path);
    }
}