Thursday, December 18, 2014

Expression language (EL) and jstl tags in JSP

Expression language is very useful and powerful tool available for developers. With JSTL tags and expression language, we can avoid Scriptlets in JSP to make JSP code more clear and maintainable.

Here are few examples to use EL with jstl tags to perform logical operations required in JSP:

1. Condition to check value is not null or blank:
If you want to check value of "abc"  variable is not blank and not null
<c:if test="${not empty abc}">
Your HTML/JSP code
</c:if>
To print value you can also use
${not empty abc ?abc:xyz}

2. Comparision     
<c:if test="${abc eq '1'}">
Your HTML/JSP code
</c:if>
3. Multiple condition

 You can use multiple if-else condition
<c:choose>
                                    <c:when test="${not empty abc}">
                                        Code when abc not empty
                                    </c:when>
                                    <c:when test="${not empty xyz}">
                                        Code when xyz not empty
                                    </c:when>                                   
                                    <c:otherwise>
                                        Code when both abc and xyz empty
            </c:otherwise>
</c:choose>