Search code examples
javascripthtmlservletsfreemarker

Mysql printing table onto html using freemarker


My main servlet containing getting into the mysql database and receiving the data.

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
{

        e.printStackTrace();
    }
    DatabaseAccess.closeConnection(con);
    }

My viewtables.ftl

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>IMDB SEARCHER</title>
<link href="css/style.css" rel="stylesheet" type="text/css">
</head>
<body>
</body>
</html>

I am having trouble how to print the result tables onto the html while using freemarker. I am using the imdb database and trying to print out the movies table onto my html when user searches for it.


Solution

  • You have to put the data of the result set into root, then process the template.

    I would create a Class Row

    public class Row{
        String id, name, year, rank;
        //constructor, getters and setters follow
    }
    

    Fill an array list of rows

    List<Row> rows = new ArrayList<Row>();
    while(rs.next()) {
        Row row = new Row(rs.getString("id"),rs.getString("name"),rs.getString("year"),rs.getString("rank"));
        rows.add(row);
    }
    root.put("rows", rows);
    

    Now that the list of rows is accessible you have to print it out in your template

    <h3>${tableName} search results</h3>
    <table class = 'ResultSet'>
        <#list rows as row >
            <tr>
                <td>${row.id}</td>
                <td>${row.name}</td>
                <td>${row.year}</td>
                <td>${row.rank}</td>
            </tr>
        </#list>
    </div>