I'm developing a portlet
for a Liferay
portal. I'm trying to use AlloyUI
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 View.jsp
:
<%@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 =
(List<Unit>)renderRequest.getAttribute("hpUnits");
%>
<script>
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
</script>
<div id="myDataTable"></div>
<script>
YUI().use(
'aui-datatable',
function(Y) {
var columns = ['name', 'city', 'description'];
new Y.DataTable.Base(
{
columnset: columns,
recordset: data
}
).render('#myDataTable');
}
);
</script>
Problems that I see in this code are following:
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.