gpt4 book ai didi

javascript - 使用 JSP 在 AlloyUI 数据表中填充数据的优雅方式

转载 作者:行者123 更新时间:2023-11-30 05:40:57 26 4
gpt4 key购买 nike

我正在为 Liferay 门户开发一个 portlet。我正在尝试使用 AlloyUI Data Table 并且我的代码目前正在运行,但我担心我这样做的方式并不优雅且易于使用维护方式。

下面是我的 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>

我在这段代码中看到的问题如下:

  1. 将 scriplet 与 javascript 代码混合。如果代码变大了。
  2. 每个标签声明 3 次(两次同时为表行填充数据,一次为列标签填充数据)。如果一个的标签要改变,程序员可能会忘记改变它在任何这些地方。

您对我如何提高代码质量有什么意见吗?

最佳答案

在我看来,这始终是通过 portlet (java) 创建数据的更好方法,并且只将可视化放到 jsp 中。我知道用 java 创建 JSON 不是那么优雅,但是你可以使用各种框架进行序列化

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

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

或者使用 org.json.* 创建纯 JSON http://json.org/java/

另见How to Create JSON Array in Java

您也可以将列名放在java路径中。

关于javascript - 使用 JSP 在 AlloyUI 数据表中填充数据的优雅方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20882631/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com