Folks, I think I am doing something wrong here. My purpose is to get info from DB into a JSON array that will later be used inside a JS calendar to show some events on a daily basis. The problem I am facing is: When I first log in to the app and see the calendar, all is good, I get the initial array of info correctly, I believe I have added 11 elements / events to it. But when I reload the page, at the end of the array, the data is added again, thus bringing me to duplicates (22 records). If I reload again, there will be more, etc. What am I doing wrong? Here's my DAO code:
record = new JSONObject();
record.put("eventName", rs.getInt("id"));
record.put("calendar", rs.getString("tool"));
record.put("color", color);
record.put("eventTime", rs.getString("datestart").replace("T", " "));
//doing the replace because the time comes with a T in between the date and the time
array.add(record);
This is all inside the while (rs.next()) statement after executing the query.
My JSON array looks like this, initially:
[{"calendar":"Mercedes","color":"orange","eventTime":"2022-06-10 00:01","eventName":104},{"calendar":"Mercedes","color":"orange","eventTime":"2022-06-10 00:01","eventName":108},{"calendar":"Mercedes","color":"orange","eventTime":"2022-06-10 00:01","eventName":109},{"calendar":"Mercedes","color":"orange","eventTime":"2022-06-10 00:01","eventName":111},{"calendar":"Mercedes","color":"orange","eventTime":"2022-06-10 00:01","eventName":113}]
Then, it becomes this:
[{"calendar":"Mercedes","color":"orange","eventTime":"2022-06-10 00:01","eventName":104},{"calendar":"Mercedes","color":"orange","eventTime":"2022-06-10 00:01","eventName":108},{"calendar":"Mercedes","color":"orange","eventTime":"2022-06-10 00:01","eventName":109},{"calendar":"Mercedes","color":"orange","eventTime":"2022-06-10 00:01","eventName":111},{"calendar":"Mercedes","color":"orange","eventTime":"2022-06-10 00:01","eventName":113},{"calendar":"Mercedes","color":"orange","eventTime":"2022-06-10 00:01","eventName":104},{"calendar":"Mercedes","color":"orange","eventTime":"2022-06-10 00:01","eventName":108},{"calendar":"Mercedes","color":"orange","eventTime":"2022-06-10 00:01","eventName":109},{"calendar":"Mercedes","color":"orange","eventTime":"2022-06-10 00:01","eventName":111},{"calendar":"Mercedes","color":"orange","eventTime":"2022-06-10 00:01","eventName":113}]
As you can see, the items are repeated starting from the end of the original array. Everytime I do a reload of the page, that's what's happening. Any ideas? Should I make the while loop different? Should I add the elements to the array in another way?
CodePudding user response:
I just had to destroy or reinstantiate the array
<%=UserDAO.array = new JSONArray()%>
That fixed it. I don't need the info anyway after the page loads completely Of course, the array is public static, but that's a risk I am willing to take. Or I might just make another method that invalidates the array and call it from the JSP page.