在 JSP 中包含的文件中输出重新格式化的文本
我有一些 HTML 文件,我想通过标签将它们包含在我的 web 应用程序中。
在某些文件中,我有伪动态代码 - 特殊格式的文本位,在运行时,我希望将其解析为 MySQL 表中各自的数据位。
例如,HTML 文件可能包含一行内容:
Welcome, [username].
我希望将其解析为(通过登录用户的数据):
Welcome, [email protected].
这在 JSP 文件中很容易实现,但要求规定这些文件将由人们创建他们了解基本的 HTML,但不了解 JSP。然而,像这样的简单文本标签应该很容易让我向他们解释。
我已经设置了代码来对字符串进行类似的解析,但是有人能想到一种跨文件执行此操作的方法吗?我实际上不需要修改磁盘上的文件 - 只需加载内容,修改它,然后将其输出到包含的 JSP 文件中。
我一直在尝试通过 apache readFileToString
将文件加载到字符串中,但我无法弄清楚如何从 webapp 内容目录中的特定文件夹加载文件而不将其硬编码在如果我将来部署到不同的系统,则必须担心它会损坏。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果这些文件位于 Web 内容中,请使用
ServletContext#getRealPath()
将相对 Web 路径转换为绝对磁盘文件系统路径。如果 WAR 在应用程序服务器中爆炸(大多数默认情况下这样做,只有 Weblogic 默认情况下不这样做,但这是可配置的 IIRC),则此方法有效。在 servlet 内部,您可以通过继承的getServletContext()
方法。或者,您可以将其放在 Web 应用程序的类路径中并使用
ClassLoader#getResource()
:至于完整的情况,我怀疑您是否曾经考虑过像 < a href="http://freemarker.sourceforge.net/" rel="nofollow noreferrer">Freemarker 或 速度来简化所有工作?
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 theServletContext
by the inheritedgetServletContext()
method.Alternatively, you can put it in the classpath of the webapplication and make use of
ClassLoader#getResource()
: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?