7.1 c:if, c:forEach

Everyone liked the code using tags instead of Java code, so they decided to expand the scope. But programming is not limited to creating objects and reading their properties. You need to call methods of objects, work with the database and other services. What to do?

You just need to represent each Java statement as a tag. Was if, will be <if>, was for, will be, <for>and so on. Okay, okay, just kidding, it wasn't like that. Well, it can't be that people actually decide to do that. But no, maybe!

Programmers allowed to add any tags to the code. In principle, there is nothing to worry about - JSP is an extensible standard. But they went further and released the JSP Standard Tag Library - JSTL. The page with it looks like this:

<%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %>
       <title> JSTL Example</title>
        <c:set var = "salary" scope = "session" value = "${2000*5}"/>
        <c:if test = "${ salary > 2000}">
            <p>My salary is: <c:out value = "${salary}"/><p>

It is quite possible that you will come across such code in your future projects, there I will give some explanations.

7.2 JSTL functions

JSTL functions fall into 5 categories:

  • Main tags;
  • Formatting tags;
  • SQL tags;
  • XML tags;
  • Calling functions.

I won't list them all, but I'll list the most popular ones. Let's start with the main tags:

1 <c:out> Outputs the specified expression - equivalent to <%= %>
2 <c:set> Writes the result of an expression to a variable
3 <c:remove> Deletes a variable
4 <c:catch> Catches exceptions
5 <c:if> analogue of if
6 <c:choose> analog switch
7 <c:when> Used together with choose
8 <c:otherwise> Used together with choose
9 <c:import> Allows you to include content in the code (equivalent to the import directive)
10 <c:forEach> for each loop
eleven <c:param> Allows you to set options for import
12 <c:redirect> Redirect
13 <c:url> Creates a URL with parameters

I'll give just one example and finish with that. In principle, it is quite possible to read such code after some skill. But I don't recommend writing.

<%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %>
      <title> Each Tag Example&</title>
       <c:forEach var = "i" begin = "1" end = "5">
            Item <c:out value = "${i}"/><p>

Think about it, we write Java code in the form of tags, so that the JSP parser will then convert these tags into Java code. Something in this world has gone wrong.

By the way, you can write your own tag libraries. I even once worked in a project where they were. Awesome experience. As soon as any changes are made to the library, the whole jsp immediately breaks.

What do you want? The compiler does not track such changes. They can only be found visually when viewing the generated HTML pages. And if these are some rare scenarios that arise in non-trivial situations ... God bless backend development and static typing!