Populate dropdown list with hashmap values in JSP [duplicate] - java

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>

Related

Print contents of a Map<String,List<Bean>> in Java

I've a map in which I'm storing an Id as a Key and under that Id I've a List of bean class where in all the bean properties are set and stored. How do I display the contents of the map in my java class? I tried something like this but not getting the list values.
for (Entry<String, List<MyBean>> me : MyForm.getClientId().entrySet())
{
String key = me.getKey();
List<MyBean> valueList = me.getValue();
System.out.println(" Key: " + key);
System.out.print("Values: ");
for (MyBean s : valueList) {
System.out.println(" " + s.getFundId());//This comes as null even though there are values in the list
}
}
Similarly I want to print the contents on the jsp page. How do I do that?
Try this code :
Set your result map in as request attribute in Servlet as show below
request.setAttribute("myMap", map);
RequestDispatcher des = request.getRequestDispatcher("test.jsp");
des.forward(request, response);
You may used different method to pass value to JSP page.
Than after you can use JSTL Tag Library to read that value in JSP page.
You need to include jstl jar file into your class path and add below line to jsp to add tag library in page
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
Used this code in JSP when you required to read value
<c:forEach var="beanList" items="${myMap}">
<c:forEach var="bean" items="${beanList['value']}">
<c:out value="${bean.fundId}"></c:out>
</c:forEach>
</c:forEach>
Where fundId is your bean property name.
May this will help you.
Just try this :-
Put this in your servlet/Controller class:-
javax.servlet.http.HttpServletRequest.setAttribute("myFormEntrySet",
And these lines in your jsp page:-
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
MyForm.getClientId().entrySet());
<c:forEach var="myFormEntrySetVar" items="${myFormEntrySet}">
<c:set var="myBeanList" value="${myFormEntrySetVar.value}" />
<c:forEach var="myBeanListVar" items="${myBeanList}" >
${myBeanListVar}
</c:forEach>
</c:forEach>
To use JSTL please download the jar of JSTL

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" %>

struts2 jstl iterator tag

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

Problem with arrayList e session jsp

I have a problem with my program.
I have a servlet; in this servlet save the session attribute
ArrayList<Integer> list = new ArrayList<Integer>;
list.add(1);
request.getsession().setAttribute("list",list);
Now the attribute is a String and not an ArrayList.
In fact when i try to do:
request.getsession().getAttribute(list)
is a string and not an Array.
I want an Array.
Thanks
You have to cast when you get the attribute from the session like this:
ArrayList<Integer> list = (ArrayList<Integer>)request.getsession().getAttribute("list");
And the attributes in the session are stored in a map, that is why the key you used is a String and you have to use a string to retrieve the value.
session.getAttribute(..) returns Object
You will have to cast it like
List<Integer> list = (List<Integer>)request.getsession().getAttribute("list");
As answered in your previous questions, just access it by EL in JSP.
${list}
If you want to iterate over it, use JSTL c:forEach:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
...
<c:forEach items="${list}" var="item">
${item}<br />
</c:forEach>
See also:
How to avoid Java code in JSP files

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