开发者

Output reformatted text within a file included in a JSP

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 开发者_StackOverflow中文版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, user@domain.com.

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.


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜