c:if

The JSTL tag c:if helps us to writing smooth HTML where conditional code should be generated.

As an example we could think the case of a web application, where a comment page is available to be read by everyone, but only the registered community members could add content.

The relative code is organized in a couple of servlets and another couple of JSP pages.

The first servlet fakes the information relative at the current user and the comments already entered:
session.setAttribute("isMember", true);

java.util.ArrayList<String> comments = new java.util.ArrayList<String>();
comments.add("cool");
comments.add("boring");
comments.add("funny");
session.setAttribute("commentList", comments);
From the servlet we call a JSP page, showComments.jsp, where we use the c:forEach tag to show the current comments and the c:if tag to choose if we want to give the user a way to enter a new comment:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!-- ... -->

<strong>Member Comments</strong>
<hr>
<c:forEach var="item" items="${commentList}" varStatus="loop">
    ${loop.count}: ${item}<br />
</c:forEach>
<hr>
<c:if test="${isMember eq true }">
    <jsp:include page="inputComment.jsp" />
</c:if>

<!-- ... -->
The forEach stuff should be clear, and the c:if doesn't look too weird. In the test attribute we put the condition we want to evaluate. Since isMember is a Boolean object, we compare it against true. We use the "eq" operator that is equivalent to "==".

If the test in the c:if attribute succeed, we include a JSP page fragment where we put the code for entering the comment:
<form action="commentProcess.do" method="post">
    Add here your comment:
    <br /><textarea name="newComment" cols="40" rows="10"></textarea>
    <br /><input type="submit" value="Add Comment">
</form>
The text entered by the user would be sent to another servlet, commentProcess.do, as newComment parameter in the request, there we add it to the comment list in the session:
String comment = request.getParameter("newComment");
if(comment.length() > 0) {
    Object o = session.getAttribute("commentList");
    if(o != null && o instanceof java.util.ArrayList) {
        @SuppressWarnings("unchecked")
        java.util.ArrayList<String> comments = (java.util.ArrayList<String>)o;
        comments.add(comment);
    }
}
If the user entered something in the text area, and if the commentList is available to this servlet, we add the new comment to the list.

And then we pass back the control to the show comments page.

I originally wrote this post while I was reading Head First Servlet and JSP, chapter nine.

No comments:

Post a Comment