I have a arraylist with some data. I need to bind that data to a dropdown list in JSP and get the selected index. Can any one help me for this?
You can use JSTL c:forEach
to iterate over a list (if not done yet, just drop jstl-1.2.jar in /WEB-INF/lib
to install it).
<select name="item">
<c:forEach items="${list}" var="item">
<option value="${item.value}">${item.label}</option>
</c:forEach>
</select>
This assumes that you've a List<Item>
where Item
look like this:
public class Item {
private String value;
private String label;
// Add/generate c'tors, getters and setters.
}
In the server side you can obtain the selected item as follows:
String selectedItem = request.getParameter("item");
You can alternatively also use a Map<String, String>
instead of a List<Item>
where Item
is actually a key-value pair. You can then iterate over it the following way:
<select name="item">
<c:forEach items="${map}" var="entry">
<option value="${entry.key}">${entry.value}</option>
</c:forEach>
</select>
Related answers:
Update: As per the comments, you should never copy server-specific libraries like Tomcat/lib/*.*
into the webapp's /WEB-INF/lib
or anywhere else in (default) runtime classpath (e.g. JRE/lib/ext
). This would only lead to collisions in the classpath which leads to this kind of errors and it will make your webapp unrunnable and unportable. You should keep the server-specific libraries at their default location. Cleanup the /WEB-INF/lib
from any server-specific libraries.
You probably copied server-specific libraries there because you wasn't able to compile your servlets. Copying the libraries in /WEB-INF/lib
is the wrong solution. You should basically just specify those libraries in the compiletime classpath. It's unclear which IDE you're using, but if it's Eclipse, this can be done easily: first add the server in Servers view, then associate your dynamic webapp project with the added server. On a brand new web project you can choose the server during project creation wizard. On existing web projects, you can modify it in Targeted Runtimes section in project's properties. This way Eclipse will automatically add the server-specific libraries to the project's buildpath.