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
Related
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>
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
Hi I am trying to print the list of strings stored in ArrayList object using JSTL, here is my jsp page:
<%#page import="java.util.ArrayList"%>
<%#page import="java.util.List"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
List<String> al = new ArrayList<String>();
al.add("testing1");
al.add("testing2");
al.add("testing3");
al.add("testing4");
al.add("testing5");
System.out.println("hello"+ al);
%>
<c:forEach var="alla" items="${al}" >
<c:out value="Hello text"></c:out>
<c:out value="${alla}"></c:out>
</c:forEach>
when i see output it is not showing any thing on the browser, I have printed it using foreach it is showing the result where as in JSTL it is not printing ?
jstl is used to print the objects from the session or request scopes. you did not set your List al either of those .
Try adding it to the session and then access it through jstl
HttpSession session = request.getSession();
session.setAttribute("al", al);
and use c:forEach to print it in your page.
See also
Scope of jsp objects
How do i use jstl
Add values to arraylist use JSTL
how do i create an arraylist inside jsp using jstl
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" %>
I have a 2d array stored in a java bean and I'm trying to iterate through its contents to print a corresponding table on a JSP page. The array is a bean data member which I'm accessing through the EL code ${board.cells}. I tried to do this with a c:forEach tag, but it's only printing a single cell. I know the array contents are valid, as I can see them when I index them directly by ${board.cells[0][0]}
Here's my loop code, embedded in the JSP.
<c:forEach items="${board.cells}" var="row">
<tr>
<c:forEach items="${row}" var="cell">
<td><img src=${cell} align="" alt="cell"></td>
</c:forEach>
</tr>
</c:forEach>
Any help is much appreciated!
As per the comments, JSTL core tags are simply not been interpreted/parsed. They are been sent plain to the HTML response. You need to declare the JSTL core taglib in top of your JSP to get them to run.
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
See also:
Our JSTL wiki page