Disper Disper - 1 month ago 11x
Javascript Question

Elegant way for populating data in AlloyUI Data Table using JSP

I'm developing a

for a
portal. I'm trying to use
Data Table
and my code is currently working, but they way in which I fear that I'm doing it in not an elegant and easy to maitain way.

Below is code from my

<%@page import="java.util.ArrayList"%>
<%@page import="com.mypackage.model.hpuc.Unit"%>
<%@page import="java.util.List"%>
<%@page import="javax.portlet.PortletPreferences"%>
<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet"%>

<portlet:defineObjects />

This is the <b>Units Folder</b> portlet in View mode.

List<Unit> hpUnits =

var data = [

<%//loop through all but last because of the
//coma that shouldn't be added for the last element
for (int i = 0; i < hpUnits.size() - 1; i++){
Unit unit = hpUnits.get(i);%>
description: '<%=unit.getDescription()%>',
city: '<%=unit.getContactData().getAddress().getCity()%>',
name: '<%=unit.getRegistrationInfo().getName()%>'

<%} //close for loop

//add last element
Unit lastUnit = hpUnits.get(hpUnits.size() -1);%>

description: '<%= lastUnit.getDescription()%>',
city: '<%= lastUnit.getContactData().getAddress().getCity()%>',
name: '<%= lastUnit.getRegistrationInfo().getName() %>'
]; //close data2 array

<div id="myDataTable"></div>

function(Y) {
var columns = ['name', 'city', 'description'];

new Y.DataTable.Base(
columnset: columns,
recordset: data

Problems that I see in this code are following:

  1. Mixing scriplets with javascript code. It might be very confusing if
    code grows bigger.

  2. Each label is declared 3 times (two times while
    populating data for table rows, and once for column labels). If one
    of the labels were to be changed, programmer might forgot to change
    it in any of those places.

Do you have any remarks about the way on how I could improve the quality of my code?


In my opinion, that is always better way to create data by portlet (java) and only the visualization put to the jsp. I know that is not so elegant to create JSON with java, but you can use various frameworks for serialization

Jackson: https://github.com/FasterXML/jackson-databind/

XStream: http://x-stream.github.io/json-tutorial.html

or create plain JSON with org.json.* http://json.org/java/

see too How to Create JSON Array in Java

you can also put the column names to java path.