First off thank you for reading! So I just learned JSP’s and Servlets this week and this morning I started to tackle a program that accepts comments from a form and then displays them all on the same page! So far it works great but I’m having trouble taking this program to the next stage. Comment Deletion.
So, the way I got the comments to output is by putting each comment object in an array, and then concatenating each comment String together. By putting each comment into a static variable.
AllComments.addComment(comments[count].toString());
And then in my JSP page I have something like this
<%=AllComments.getAllComments() %>
So it works great. A new comment comes in, it’s concatenated, and then all the comments are printed out as one formatted String.
The problem with this is even thought it works, by putting the comments all together I can never do anything to them again. So this makes it impossible to do my next step which would be to have a link next to each comment with the option to delete.
So in order to do that I’m thinking that I need to display the comments as a loop on my JSP page and show each comment as an individual String. And then if anyone clicks delete I can remove that comment from the array!
So far this is what I was doing trying in my JSP page
<%
for (int i = 0; i < UserBean.getCommentCount(); i++)
{
%>
<%=comments[i].toString() %>
<%
}
%>
However this isn’t working b/c the scope of the comments reference variable is only within the protected doPut method and it’s package. So what should i do to get my comments to output within the loop one comment at a time! You can view my entire servlet class below. Thank you for taking the time to read this.
if (!request.getParameter("fullName").equals("") && !request.getParameter("comment").equals(""))
{
UserBean[] comments = new UserBean[10];
int count = UserBean.getCommentCount();
comments[count] = new UserBean();
comments[count].setFullName(request.getParameter("fullName"));
comments[count].setDate(String.valueOf(new Date()));
comments[count].setComment(request.getParameter("comment"));
AllComments.addComment(comments[count].toString());
UserBean.incrementCommentCount();
}
You could set comments to request or sessions attributes, depends on whether you redirects to JSP or not. (If redirect then session, cause request attributes will be empty). And then get comments on JSP page from session or request.
Inside doPut method after filling comments
And on JSP page you will need to add to the top
Hope it helps.