Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a JSP template be used from within Java?

Tags:

java

jsp

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?

like image 386
jwl Avatar asked Sep 18 '13 16:09

jwl


2 Answers

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.

like image 188
Nathan Hughes Avatar answered Sep 30 '22 02:09

Nathan Hughes


There's no simple way to accomplish this using plain JSP. There are related Q/As in the site explaining how to do it:

  • What is the best way to create JSP layout template?
  • JSP tricks to make templating easier?

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.

like image 41
Luiggi Mendoza Avatar answered Sep 30 '22 03:09

Luiggi Mendoza