I'm pretty new to JSP. So far it seems that the flow of processing is very much Java runs first, then populates a JSP template.
I am wondering if there is a way from within Java to utilize a JSP template. What I mean is, imagine I had a simple "SimpleDiv.jsp" template on classpath like this:
<div id="${id}" class="${class}">
${content}
</div>
And then from within an arbitrary Java file (perhaps not even running on a servlet), I could do something like this:
private String getDivHtml( id, html ) {
Template simpleDiv = TemplateLoader.load("SimpleDiv.jsp");
simpleDiv.set("id", id);
simpleDiv.set("class", Whatever.CLASS_NAME);
simpleDiv.set("content", html);
return simpleDiv.toString();
}
This is a pretty simplistic example so don't get caught up on the details of that. Main question is -- can I pull in a JSP template in Java and cause it to generate HTML inline?
Freemarker and Velocity are very popular for generating content from templates, you might try one of them. Since JSPs are implemented as servlets (and the JSP spec defines them as webcomponents) they are tied to the servlet container.
There's no simple way to accomplish this using plain JSP. There are related Q/As in the site explaining how to do it:
Another option using plain JSP would be using external frameworks to accomplish the task like Apache Tiles and SiteMesh (mentioned here: JSP template implementation (Composite View Pattern)).
If you can, upgrade to Facelets, the current view technology since Java EE 6. This technology already provides built-in template system as explained here and here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With