Apr 15

Sometimes you need the path of a file in your web application, for example if you need to open a file for reading. You could hard code where your web application is deployed but that will break if you ever move where your application is deployed.

Luckily the ServletContext class provides a getRealPath() method to determine the path of any file contained within your web application.

public class ImageServlet extends HttpServlet
{
   public void doGet(HttpServletRequest req,
      HttpServletResponse resp) throws IOException
   {
    	ServletContext application = getServletContext();
    	
    	// Get the absolute path to file that lives in this application
  
        String filepath = application.getRealPath("WEB-INF/images/a.gif");
        File file = new File(filepath);
        FileInputStream in = new FileInputStream(file);


written by objects \\ tags: , , , ,

Sep 29

The default data store is stored as an attribute in the application context.

// Get application context

ServletContext application=servlet.getServletContext();

// lookup data source

DataSource datasource = 
   (DataSource) application.getAttribute(Global.DATA_SOURCE_KEY);

written by objects \\ tags: , ,