tags:

views:

29

answers:

1

I have a few HTML files that I'd like to include via tags in my webapp.

Within some of the files, I have pseudo-dynamic code - specially formatted bits of text that, at runtime, I'd like to be resolved to their respective bits of data in a MySQL table.

For instance, the HTML file might include a line that says:

Welcome, [username].

I want this resolved to (via a logged-in user's data):

Welcome, [email protected].

This would be simple to do in a JSP file, but requirements dictate that the files will be created by people who know basic HTML, but not JSP. Simple text-tags like this should be easy enough for me to explain to them, however.

I have the code set up to do resolutions like that for strings, but can anyone think of a way to do it across files? I don't actually need to modify the file on disk - just load the content, modify it, and output it w/in the containing JSP file.

I've been playing around with trying to load the files into strings via the apache readFileToString, but I can't figure out how to load files from a specific folder within the webapp's content directory without hardcoding it in and having to worry about it breaking if I deploy to a different system in the future.

+1  A: 

but I can't figure out how to load files from a specific folder within the webapp's content directory without hardcoding it in and having to worry about it breaking if I deploy to a different system in the future.

If those files are located in the webcontent, use ServletContext#getRealPath() to convert a relative web path to an absolute disk file system path. This works if the WAR is exploded in the appserver (most does it by default, only Weblogic doesn't do that by default, but this is configureable IIRC). Inside servlets you can obtain the ServletContext by the inherited getServletContext() method.

String relativeWebappURL = "/html/file.html";
String absoluteFilePath = getServletContext().getRealPath(relativeWebappURL);
File file = new File(absoluteFilePath);
// ...

Alternatively, you can put it in the classpath of the webapplication and make use of ClassLoader#getResource():

String relativeClasspathURL = "/html/file.html";
URL absoluteClasspathURL = Thread.currentThread().getContextClassLoader().getResource(relativeClasspathURL);
File file = new File(absoluteClasspathURL.toURI());
// ...

As to the complete picture, I question if you have ever considered an existing templating framework like Freemarker or Velocity to ease all the job?

BalusC
I have considered using Freemarker or Velocity, but as the only devloper on the project it was getting too time-consuming for me to get up to speed with them, and there are only a couple of places in the app where it really made sense for me to use it.
javanix
Thanks very much, by the way, getRealPath() did exactly what I needed it to.
javanix
You're welcome.
BalusC