java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to 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 com.javacoderanch.example.servlet;

import java.io.IOException;
import java.io.PrintWriter;

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() {
	super();
    }

    protected void doGet(HttpServletRequest request,
	    HttpServletResponse response) throws ServletException, IOException {

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

    protected void doPost(HttpServletRequest request,
	    HttpServletResponse response) throws ServletException, IOException {
    }
}