How do I get my web application real path?

This code helps you to get the physical path where your web application is deployed on the server. It may be useful so you can for instance read or write file on the server. But please aware that this method will only work when your web application is deployed in an exploded way, if it was deployed in a war format the getRealPath() method just return null.

package org.kodejava.example.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class GetWebApplicationPathServlet extends HttpServlet {

    public GetWebApplicationPathServlet() {

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

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