03 January 2010

mysql and jtpl template engine tutorial

jtpl is a light-weight java template engine, which is good for small size application but becomes sludgy for data intensive apps. Following example shows how to use jtpl with mysql.

jtpl replaces everything which is put inside {} and it uses html comments as entry and exit points
< ! -- BEGIN: main -- >
{This will be replaced by jtpl}
{ThisToo}
< ! -- END: main -- >
this template file should be saved with the extension .jtpl
In your servlet you need to create a Template object which will take template file as input parameter.
Template tpl = new Template(new File("FULL_PATH\\home.jtpl"));
 next you need to assign the value to the template parameters like:
tpl.assign("ThisToo", "Assigned Value Here !"); 
in the end template is parsed using
tpl.parse("main"); 
If you have nested template regions in a template like this:

< ! -- BEGIN: main -- >
< ! -- BEGIN: header-- >
{Links}
< ! -- BEGIN: header-- >
< ! -- END: main -- >
Everything remains same except when you parse, you'll have to parse the inner region first, like:
tpl.parse("main.header"); 
then the outer (or main) region:
tpl.parse("main"); 
You can put as many regions you want inside a main region.
Using jtpl with mysql(or any other db) is simple as explained above. Here is a sample template file home.jtpl:
<!-- BEGIN: main1 -->
<html>
    <head>
        <title>{PTITLE}</title>       
    </head>
    <body>
            <div>               
                    <div>
                       <a class="a" href="/anylink1">{LINK1}</a>
                       <a class="a" href="/anylink2">{LINK2}</a>
                       <a class="a" href="/anylink3">{LINK3}</a>
                    </div>
            </div>
            <div>
                <div>
                    <div>
                        <!-- BEGIN: div -->
                            <div>
                                <a target="_blank" href ="{LINK}">{TITLE}</a>
                                <br><span>{CONTENT}</span>
                            </div>
                        <!-- END: div -->
                    </div>
                </div>
        </div>
    </body>
</html>
<!-- END: main1 --> 
and here is the Servlet:
import net.sf.jtpl.Template;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;

/**
 *
 * @author viksin
 */
public class sample extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        try {
            out.print(this.generatePage());
        } catch (Exception e) {
            e.printStackTrace(out);
        } finally {
            out.close();
        }
    }

    protected String generatePage() throws Exception {
        Template tpl = null;
        Connection conn = null;
        Statement st = null;
        ResultSet rs = null;
        String Content = "";
        TimeCalc tc = new TimeCalc();
        tpl = new Template(new File("FULL_PATH\\home.jtpl"));
        tpl.assign("PTITLE", "MySite");
        tpl.assign("LINK1", "Home");
        tpl.assign("LINK2", "News");
        tpl.assign("LINK3", "About");
        try {
            Class.forName("org.gjt.mm.mysql.Driver").newInstance();
            conn = DriverManager.getConnection("mysql_URL", "USERNAME", "PASSWORD");
            st = conn.createStatement();
            rs = st.executeQuery("select title,link,content from table");
            while (rs.next()) {
                tpl.assign("TITLE", rs.getString("title"));
                tpl.assign("CONTENT", rs.getString("content"));
                tpl.assign("LINK", rs.getString("link"));
                tpl.parse("main1.div");
            }           
            tpl.parse("main1");
        } catch (Exception ex) {
            return ex.toString();
        } finally {
            if (rs != null) {
                rs.close();
            }
            if (st != null) {
                st.close();
            }
            if (conn != null) {
                conn.close();
            }
        }
        return (tpl.out());
    }
}
jtpl is meant for small and simple applications, it does not have many features which other template engines like velocity, stringtemplate etc. have.
jtpl also uses the SingleThreadModel which is not recommended also it gets slower with large data.
Presently I am using StringTemplate which is faster and better than jtpl.