struts2 jstl iterator tag - java

I have been looking how to implement a thing in struts2 jstl but it is impossible for me to find the way.
When I load the jsp page from the action, I have a list of String lists.
I want to create as divs as elements have the list, but inside every div, I want to create as links as the third element of the sub-list.
So I use the s:iterator tag to parse the list. But I don't know how to iterate "${item[2]}" times inside the first iterator.
The code would be something like this:
<s:iterator value="functions" var="item" status="stat">
<span class="operation">${item[1]}</span>
<div id="${item[0]}">
<s:for var $i=0;$i<${item[2]};$i++>
Link $i
</s:for>
</div>
</s:iterator>
Where I have put the s:for tag is where I would like to iterate "${item[2]}" times...
Anyone can help me?
Thank you very much in advance,
Aleix

Make sure you've got the JSTL core library in scope in your JSP page:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
And simply use <c:forEach>. Something like this:
<c:forEach var="i" begin="0" end="${item[2] - 1}">
Link ${i}
</c:forEach>

You should use List of Map if appropriate, example :
Action class
// List of raw type Map
private List<Map> functions = Lists.newArrayList(); // with getter
#Override
public String execute() {
// loops {
Map map = Maps.newHashMap();
map.put("id", id);
map.put("operation", operation);
map.put("count", count); // count is int/Integer
functions.add(map);
// }
return SUCCESS;
}
.jsp
<s:iterator value="functions">
<span class="operation">${operation}</span>
<div id="${id}">
<s:iterator begin="0" end="count - 1" var="link">
Link ${link}
</s:iterator>
</div>
</s:iterator>
or with <s:a /> (example)
<s:a action="action_name" id="%{link}" anchor="%{link}">Link ${link}</s:a>
output
<a id="[id]" href="/namespace/action#[anchor]">Link [link]</a>
See also
Struts2 Guides -> Tag Reference -> s:iterator

Related

Populate dropdown list with hashmap values in JSP [duplicate]

How can I loop through a HashMap in JSP?
<%
HashMap<String, String> countries = MainUtils.getCountries(l);
%>
<select name="country">
<%
// Here I need to loop through countries.
%>
</select>
Just the same way as you would do in normal Java code.
for (Map.Entry<String, String> entry : countries.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
// ...
}
However, scriptlets (raw Java code in JSP files, those <% %> things) are considered a poor practice. I recommend to install JSTL (just drop the JAR file in /WEB-INF/lib and declare the needed taglibs in top of JSP). It has a <c:forEach> tag which can iterate over among others Maps. Every iteration will give you a Map.Entry back which in turn has getKey() and getValue() methods.
Here's a basic example:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:forEach items="${map}" var="entry">
Key = ${entry.key}, value = ${entry.value}<br>
</c:forEach>
Thus your particular issue can be solved as follows:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<select name="country">
<c:forEach items="${countries}" var="country">
<option value="${country.key}">${country.value}</option>
</c:forEach>
</select>
You need a Servlet or a ServletContextListener to place the ${countries} in the desired scope. If this list is supposed to be request-based, then use the Servlet's doGet():
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
Map<String, String> countries = MainUtils.getCountries();
request.setAttribute("countries", countries);
request.getRequestDispatcher("/WEB-INF/page.jsp").forward(request, response);
}
Or if this list is supposed to be an application-wide constant, then use ServletContextListener's contextInitialized() so that it will be loaded only once and kept in memory:
public void contextInitialized(ServletContextEvent event) {
Map<String, String> countries = MainUtils.getCountries();
event.getServletContext().setAttribute("countries", countries);
}
In both cases the countries will be available in EL by ${countries}.
See also:
Iterate over elements of List and Map using JSTL <c:forEach> tag
How to iterate over a nested map in <c:forEach>
How to iterate an ArrayList inside a HashMap using JSTL?
Using special auto start servlet to initialize on startup and share application data
Depending on what you want to accomplish within the loop, iterate over one of these instead:
countries.keySet()
countries.entrySet()
countries.values()
Below code works for me
first I defined the partnerTypesMap like below in the server side,
Map<String, String> partnerTypes = new HashMap<>();
after adding values to it I added the object to model,
model.addAttribute("partnerTypesMap", partnerTypes);
When rendering the page I use below foreach to print them one by one.
<c:forEach items="${partnerTypesMap}" var="partnerTypesMap">
<form:option value="${partnerTypesMap['value']}">${partnerTypesMap['key']}</form:option>
</c:forEach>

Sort select box items in a JSP scriptlet

I'm working on a legacy Tomcat server that is no longer supported by the software developer that provided it. web.xml doesn't tell me what version of JSP I'm working with, but all the .class files are Java 1.5.
I have a customer who is upset, because the system has html boxes that are auto-populated by Java, and it fills it straight the the (unordered) results of an XML database query. I'm trying to sneak a bit of code into the JSP for the Selector to sort the list of fields before they are populated, but it doesn't work and I don't understand why.
The (abridged) relevant code:
<%# page import="src.explorer.ObjectStateFactory"%>
<%# page language="java" %>
<%# taglib uri="/WEB-INF/c.tld" prefix="c" %>
<jsp:useBean id="ExplorerViewContext" scope="session" type="src.explorer.ExplorerViewContext"/>
...
<c:forEach var="nc" items="${ExplorerViewContext.networkControllers}">
<c:choose>
<c:when test="${nc.name == ExplorerViewContext.networkControllerSelection.name}">
<option value="<c:out value="${selectAction}${nc.objectKey}"/>" selected><c:out value="${nc.name}"/></option>
</c:when>
<c:otherwise>
<option value="<c:out value="${selectAction}${nc.objectKey}"/>"><c:out value="${nc.name}"/></option>
</c:otherwise>
</c:choose>
</c:forEach>
</select>
The relevant code with my additions:
<%# page import="src.explorer.ObjectStateFactory"%>
<%# page import="java.util.*"%>
<%# page language="java" %>
<%# taglib uri="/WEB-INF/c.tld" prefix="c" %>
<jsp:useBean id="ExplorerViewContext" scope="session" type="src.explorer.ExplorerViewContext"/>
...
<%
final Comparator<src.explorer.XmldbObjectState> NC_ORDER = new Comparator<src.explorer.XmldbObjectState>(){
public int compare(src.explorer.XmldbObjectState nc1, src.explorer.XmldbObjectState nc2){
return nc1.getName().compareTo(nc2.getName());
}
};
List myList = ExplorerViewContext.getNetworkControllers();
java.util.Collections.sort(myList,NC_ORDER);
%>
<c:forEach var="nc" items="${myList}">
<c:choose>
<c:when test="${nc.name == ExplorerViewContext.networkControllerSelection.name}">
<option value="<c:out value="${selectAction}${nc.objectKey}"/>" selected><c:out value="${nc.name}"/></option>
</c:when>
<c:otherwise>
<option value="<c:out value="${selectAction}${nc.objectKey}"/>"><c:out value="${nc.name}"/></option>
</c:otherwise>
</c:choose>
</c:forEach>
</select>
Basically, I'm trying to grab the list and sort it before it gets sent to the HTML. The problem is, myList always comes up empty, and I don't understand why. I'm guessing that ExplorerViewContext.networkControllers in the original code is calling the getNetwrokControllers() method on an instance of ExplorerViewContext, yes? Why can't I do the same thing in a scriptlet and reformat the output a little before serving it?
You should not add scriptlet code to code that is already using JSTL only. The better thing to do would be to edit the bean class src.explorer.ExplorerViewContext to sort the insides for you automatically.
In any case, the reason ${myList} does nothing in the JSTL is that variables created in scriptlets (i.e. between <% and %>) do not exist for JSTL. To get a variable to exist in JSTL you have to create it in JSTL, or set it in the page context, or it has to be in the session or the request. Generally you put it in the session or request in a servlet.
In this case, your list is in the bean, so it would be better to just edit the bean class to sort the list. But you could set the variable into the page context here so that JSTL can use it:
<%
...
List myList = ExplorerViewContext.getNetworkControllers();
java.util.Collections.sort(myList,NC_ORDER);
pageContext.setAttribute("myList", myList); //set in pageContext so JSTL can see it
%>
<c:forEach var="nc" items="${myList}">
As far as the code being "legacy" adding scriptlets to it would make it even more legacy. The fact is, this code is more modern than the modifications you were trying to add. But only slightly so, since using <jsp:useBean> is an obsolete way of using beans.

JSTL c:set not working as expected

I have a JSTL loop where I'm trying to check to see if a given variable is empty or not with a dynamic variable name. When I use c:set with page scope, the variable is not accessible to the if statement. However, when I set it using <% pageCotnext.setAttribute(...); %>, the variable is available.
<%
pageContext.setAttribute("alphaParA", "test");
pageContext.setAttribute("alphaParF", "test");
int i = 0;
%>
<ul class="alphadex_links">
<c:forEach var="i" begin="0" end="25" step="1" varStatus="status">
<c:set var="currentLetter" scope="page">&#${i+65}</c:set>
<c:set var="currentPar" scope="page">alphaPar${currentLetter}</c:set>
<% pageContext.setAttribute("currentPar", "alphaPar" + (char)('A' + i++)); %>
<li>
<c:choose>
<c:when test="${not empty pageScope[currentPar]}">
The test is always fails when I remove the pageContext.setAttribute block, however it succeeds for A and F as it should when the block is in. I'm very confused and can't find help anywhere.
It fails because HTML doesn't run at the moment JSTL runs. You're effectively passing a Java String &#65 to it instead of the desired character A which would be represented as such based on the HTML entity A when the HTML is retrieved and parsed by the webbrowser after Java/JSP/JSTL has done its job. Please note that your HTML entity is missing the closing semicolon, but this isn't the cause of your concrete problem.
As to the concrete functional requirement, sorry, you're out of luck with EL. It doesn't support char. Your best bet is to deal with strings like this:
<c:forEach items="${fn:split('A,B,C,D,E,F,G,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z', ',')}" var="currentLetter">
<c:set var="currentPar" value="alphaPar${currentLetter}" />
${pageScope[currentPar]}
</c:forEach>
If necessary, just autogenerate the letters as String[] in Java end and set it as application attribute.

Import and print arraylist to JSP

I have simple jsp page (page.jsp), and a simple java class (classWithArray) with an arraylist (list) in it.
How can I get access to the arraylist from jsp, for example to show it in a table?
Use JSTL's forEach tag to iterate over a collection (an ArrayList in this case in particular) inside a JSP, take a look at this post for more details.
you can iterate over an ArrayList using c:forEach tag from JSTL
Below is the sample code which iterates over an peopleList List.
<c:forEach var="person" items="${people.peopleList}">
<tr>
<td>${person.name}</td>
</tr>
</c:forEach>
use page tag to import a java.util.List in your JSP page use
<%# page import="java.util.List" %>

Add values to arraylist use JSTL

is it possible to add values to an ArrayList instead of using a HashMap
something like:
<jsp:useBean id="animalList" class="java.util.ArrayList" />
<c:set target="${animalList}" value="Sylvester"/>
<c:set target="${animalList}" value="Goofy"/>
<c:set target="${animalList}" value="Mickey"/>
<c:forEach items="${animalList}" var="animal">
${animal}<br>
</c:forEach>
now getting the error:
javax.servlet.jsp.JspTagException: Invalid property in <set>: "null"
thx
JSTL is not designed to do this kind of stuff. This really belongs in the business logic which is (in)directly to be controlled by a servlet class.
Create a servlet which does like:
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
List<String> animals = new ArrayList<String>();
animals.add("Sylvester");
animals.add("Goofy");
animals.add("Mickey");
request.setAttribute("animals", animals);
request.getRequestDispatcher("/WEB-INF/animals.jsp").forward(request, response);
}
Map this on an url-pattern of /animals.
Now create a JSP file in /WEB-INF/animals.jsp (place it in WEB-INF to prevent direct access):
<c:forEach items="${animals}" var="animal">
${animal}<br>
</c:forEach>
No need for jsp:useBean as servlet has already set it.
Now call the servlet+JSP by http://example.com/context/animals.
To do add() to a List or others methods from Map, Set, etc... You have to use a unusable variable.
<jsp:useBean id="list" class="java.util.ArrayList"/>
<c:set var="noUse" value="${list.add('YourThing')}"/>
<c:out value="${list}"/>
The above code is not working.
Following are the lines of code that has to be placed in file animals.jsp
<%# taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<c:forEach var="animal" items="${animals}">
<c:set var="animalName" value="${animal}"/>
<c:out value="${animalName}"/>
</c:forEach>

Categories