-1

I have a unique problem to solve. I need to dynamically create HTML based reports using a standard template. The contents of the report are created by a Java program so it makes sense to create a new class which uses JSP* to make a static HTML output file.

Here is the gist:

MyObject me = new MyObject();
me.process();

MyJSP jsp = new MyJSP(me);
File output = jsp.renderFrom("templateFile.jsp");

And output is a static, self contained HTML file which I can open in IE/Firefox and see the report.

What pattern/framework should I follow to allow me to best accomplish this?

Some notes: This is actually not a webapp. I am creating HTML based reports, but this won't be used as a webapp. I would also rather not use String.format(".. giant template string .. ", args) as this is very clumsy. I would much rather have a template file like this:

<html>
<head><title>First JSP</title></head>
<body>
  <%
    double num = Math.random();
    if (num > 0.95) {
  %>
      <h2>You'll have a luck day!</h2><p>(<%= num %>)</p>
  <%
    } else {
  %>
      <h2>Well, life goes on ... </h2><p>(<%= num %>)</p>
  <%
    }
  %>
  <a href="<%= request.getRequestURI() %>"><h3>Try Again</h3></a>
</body>
</html>

Where the "dynamic" aspects of the template can use MyObject properties, etc.

Lastly, I plan to use Java 7 for this due to some issues I am having with Java 8. If there is some better way to do this in Java 8, let me know...

*After some negative comments against JSP, perhaps JSP is not the right option. Some other library is fine too, as long as it works with Java.

E.S.
  • 2,733
  • 6
  • 36
  • 71
  • 2
    It's a bad idea to write Java inside your JSP. http://stackoverflow.com/q/3177733/139010 – Matt Ball Sep 01 '16 at 23:49
  • 3
    JSP is for writing *dynamic* HTML files. A *static* HTML file has no dynamic content. – Andreas Sep 01 '16 at 23:51
  • Can you recommend an alternative than, some other library besides JSP. In the end, I still need to develop static HTML reports... rather not use `String.format(...)` – E.S. Sep 01 '16 at 23:52
  • Okay I took out the JSP specific part of the question. Would be great if the down votes got undone so the question doesn't get filtered out. – E.S. Sep 01 '16 at 23:57
  • I'm not sure ripping jsp out of a servlet container will be that easy, but then I never tried it so I could be wrong. [Freemarker](http://freemarker.org/) is probably easier. – fvu Sep 01 '16 at 23:57

1 Answers1

2

Use a template engine for this! I would recommend Freemarker, Velocity or StringTemplate. Just google it. Any of these engines will cover your needs.

Jürgen
  • 418
  • 3
  • 7