Good day.
There is such a task: in JSP, with the help of JSTL ( <%@ taglib prefix="c" uri="" %> ) implement the output of information in JSON format. And nothing else. The task is simple, not requiring much effort. But here I braked on a simple task. It is necessary to implement the output in the map array Map<String, String> . I did it like this:

 [ <c:forEach var="item" items="${payParam.format}"> "<c:out value="${payParam.description}"/>":"<c:out value="${item.value}" />", </c:forEach> ] 

The problem is that at the end of the line, after each cycle, there is always a comma. Tell me, please, how can I check if a comma is needed? Those. If the element in the card is the last, then a comma is not needed.

  • The comma is a consequence of the toString () method, usually removed by the replace () method, it should not be at the end. How do we know if you need a comma?) Check to do - if the element is last, then .. =) - Gorets
  • Check to do - if the element is the last, then .. =) .... then the comma is not needed, as the last sentence says. When using my code, a comma is always put at the end of the line at each iteration. I also need it to be, if the last element. Here the main essence of the question is to check whether the last element is in the map. Also, it is not clear to me, so how can you remove the last comma with the toString () method? It is necessary to admit the possibility that after this array further there could be some JSON elements. Those. commas will continue to occur. - Anton Mukhin
  • Well then, if you have a static string length, i.e. a fixed number of elements in it, then you can simply write a condition, such as after the 5th element - do not put a comma - Gorets
  • Does not fit. Unknown how many items in the map. Maybe it can somehow be calculated? An idea worth living! - Anton Mukhin

1 answer 1

All this is done easily using the isLast property of the LoopTagStatus class. To do this, in the declaration of the iteration, we set another parameter: varStatus="loop" . Next, you can see if this is the last element with the ad:

 <c:if test="${!loop.last}">,</c:if> 

The result is this:

 [ <c:forEach var="item" items="${payParam.format}" varStatus="loop"> "<c:out value="${payParam.description}"/>":"<c:out value="${item.value}" />" <c:if test="${!loop.last}">,</c:if> </c:forEach> ] 
  • he asked a question, he answered - the ideal user - Viacheslav
  • @Viacheslav, there is nothing surprising! I have a project to do. I asked a question in the hope that soon it will be answered. But at that time I did not lose time either, waiting for the manna from heaven, and I was looking for the answer to my question. And, having received no answer, I found it myself. - Anton Mukhin