Working on a program and trying to print a static integer from another class. The weird thing is I can do it with scriptlets, but not with JSTL. Check out the error checking code I just wrote.
Comments: <%=Comments.getCommentCount() %> <br />
Comments: ${Comments.getCommentCount()} <br />
Comments: <c:out value="${Comments.getCommentCount()}" /> <br />
Comments: <c:out value="1" />
This gives me an HTML output of
Comments: 5 <br />
Comments: <br />
Comments: <br />
Comments: 1
So as you can see only the first and last lines of code work. How can I print out this static variable without scriptlets?
And in my header I have
import="org.test.Comments"
Comments.java
package org.test;
import java.util.ArrayList;
import java.util.Collections;
public class Comments
{
private String name = "";
private String comment = "";
private static ArrayList<String> allComments = new ArrayList<String>();
public void setNewComment(String name, String comment)
{
this.name = name;
this.comment = comment;
allComments.add(getComment());
}
public static ArrayList<String> getCommentList()
{
Collections.reverse(allComments);
return allComments;
}
public static int getCommentCount()
{
return allComments.size();
}
public String getComment()
{
return String.format("Name: %s <br />Comment: %s <p><hr /></p>", name, comment);
}
}
You need not call the getter inside jstl. just do this
<c:out value="${Comments.commentCount}" />
assuming your variable name is commentCount
and not CommentCount
.
It would work even without <c:out>
Comments: ${Comments.commentCount} <br />
but using <c:out>
would be better, to avoid cross-site scripting as explained here
UPDATE
In the class you have mentioned, there is no field with the name commentCount. So it wouldn't work. You can use use jsp fn tag to get a the size of a collection directly inside the jsp.
Include this in the header
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
and then do this:
<c:out value="${fn:length(allComments)}" />
or
Comments: ${fn:length(allComments)} <br />
This should work.