Skip navigation




Get Real Path from ServletContext


Discussion
Sometimes your web application will generate some file into your physisical disk, such as *.pdf, *.xls, *.txt, …
according to your business requirement. So your application has to know the real path to generate the requested
files. If you hard code the real path in some configuration file to do this, OK, no problem. But sometimes maybe
you have no right to know the real path where your web application is residing. Such as if you rent a sharing host
of another host renting company. And the administrator won’t tell you the real path information.
On another hand, if you hard code the real path, it will not be a good choice when imigrating your web application
I think. You have to change your configuration file each time when you change a running server.
So, here is the problem, how to do?
Thank God, the J2EE support you ServletContext, and we can fix this up.
ServletContext supports us a method called getRealPath(String path). If a virtual path as the path parameter, the return
value is the real path for the given virtual path.

Here is the example:

The web application residing real path: C:\jakarta-tomcat-5.0.28\webapps\dispatchEx\
The dispatchEx is the web application. The application will generate a pdf file everytime when the user clicks
the link in the web page. And the file will be generate under the real path of this web application.

Solution

public class GeneratePdfAction extends Action {
  public ActionForward execute(ApplicationMapping mapping, ActionForm form,
          HttpServletRequest request, HttpServletResponse response) throws Exception {
    String dir = 
        getServlet().getServletContext().getRealPath("/");
    //dir=C:\jakarta-tomcat-5.0.28\
            webapps\dispatchEx\ while debuging
    generatePdf(dir);
    return mapping.findforward("success");

  }
  private void generatePdf(String dir) {
    String filename = dir + 
      DateFormatUtils.format(System.currentTimeMillis(), 
                                           "yyyyMMddHHmm") +
          RandomStringUtils.random(4, true, false) + ".pdf";
    this.pdfGenerator.generatePdf(filename);
  }
  public PdfGenerator getPdfGenerator() {
    return this.pdfGenerator
  }
  public void setPdfGenerator(PdfGenerator pdfGenerator) {
    this.pdfGenerator = pdfGenerator;
  }
}

Leave a comment