jstl
Conditional content with JSTL in JSP page
This is an example of how to create conditional content in a JSP page using JSTL. JavaServer Pages Standard Tag Library (JSTL) encapsulates as simple tags the core functionality common to many Web applications. JSTL has support for common, structural tasks such as iteration and conditionals, tags for manipulating XML documents, internationalization tags, and SQL tags. Creating conditional content in a JSP page using JSTL implies that you should:
- Create a jsp page that contains the
<%code fragment%>
scriptlet. It can contain any number of JAVA language statements, variable or method declarations, or expressions that are valid in the page scripting language. - Include JSTL Core library in your JSP page, using the
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
syntax. - Use the
<c:if>
tag to evaluate an expression. It displays its body content only if the expression evaluates to true. Thetest
attribute holds the condition to evaluate. - Use the
<c:choose>
tag, that works like a Java switch statement in that it lets you choose between a number of alternatives. It uses<c:when>
tag, with an attribute namedtest
that evaluates a condition. It also uses<c:otherwise>
to perform the default clause.
Let’s take a look at the code snippet that follows:
ConditionalContentJSTL.jsp
<%@ page language="java" contentType="text/html;charset=UTF-8" %> <%@ taglib uri="/WEB-INF/tld/c-rt.tld" prefix="c-rt" %> <html> <head> <title>Java Code Geeks Snippets - Conditional Content with JSTL in JSP Page</title> </head> <body> <%-- if condition --%> <c-rt:if test='${param.myparam1 == "myvalue1"}'> This is printed if parameter "myparam1" equals "myvalue1" </br> </c-rt:if> <%-- if/else condition --%> <c-rt:choose> <c-rt:when test='${param.myparam2 == "myvalue2"}'> This is printed if parameter "myparam2" equals "myvalue2" </br> </c-rt:when> <c-rt:otherwise> This is printed if parameter "myparam2" DOES NOT equal "myvalue2" </br> </c-rt:otherwise> </c-rt:choose> <%-- multiple conditions --%> <c-rt:choose> <c-rt:when test='${param.myparam3 == "0"}'> This is printed if parameter "myparam1" equals 0 </br> </c-rt:when> <c-rt:when test='${param.myparam3 == "1"}'> This is printed if parameter "myparam1" equals 1 </br> </c-rt:when> <c-rt:otherwise> This is printed for any other value of the parameter </br> </c-rt:otherwise> </c-rt:choose> </body>
URL:
http://localhost:8080/jcgsnippets/ConditionalContentJSTL.jsp?myparam1=myvalue1&myparam2=other&myparam3=1
Output:
This is printed if parameter "myparam1" equals "myvalue1"
This is printed if parameter "myparam2" DOES NOT equal "myvalue2"
This is printed if parameter "myparam1" equals 1
This was an example of how to create conditional content in a JSP page using JSTL.