Java populating <option> dropdown list - java

I have the following code:
<div>
<%
TaxonomicTypeFeed ttf = new TaxonomicTypeFeed();
ArrayList<String> tmp = ttf.getTypes();
System.out.println("Going to print");
for (int i=0; i < tmp.size(); i++)
{
System.out.println(tmp.get(i));
}
%>
<form>
<select>
<%
Iterator<String> i = tmp.iterator();
while (i.hasNext())
{
String str = i.next(); %>
<option value="<%str.toString();%>"><%str.toString();%>
</option>
<%}%>
</select>
</form>
</div>
It creates a dropdown list fine, however there is no text.
This is the first time I have ever used any of these options before, so I have no idea if I am even going about it in the right manner.

You need to print the values by <%= %>. The <% %> won't print anything.
<option value="<%=str%>"><%=str%></option>
Unrelated to the problem: this is not the best practice. Consider using taglibs/EL. You end up with better readable/maintainable code.
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<jsp:useBean id="taxonomicTypeFeed" class="com.example.TaxonomicTypeFeed" />
...
<select>
<c:forEach items="${taxonomicTypeFeed.types}" var="type">
<option value="${type}">${type}</option>
</c:forEach>
</select>
Instead of <jsp:useBean> you can also use a preprocessing servlet.

Related

Online polling - database - jsp - servlets [duplicate]

I have a map like this,
Map<Integer,ArrayList<Object>> myMap = new LinkedHashMap<Integer,ArrayList<Object>>();
Now I have to iterate this Map and then the ArrayList inside the map. How can I do this using JSTL?
You can use JSTL <c:forEach> tag to iterate over arrays, collections and maps.
In case of arrays and collections, every iteration the var will give you just the currently iterated item right away.
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:forEach items="${collectionOrArray}" var="item">
Item = ${item}<br>
</c:forEach>
In case of maps, every iteration the var will give you a Map.Entry object which in turn has getKey() and getValue() methods.
<%# 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>
In your particular case, the ${entry.value} is actually a List, thus you need to iterate over it as well:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:forEach items="${map}" var="entry">
Key = ${entry.key}, values =
<c:forEach items="${entry.value}" var="item" varStatus="loop">
${item} ${!loop.last ? ', ' : ''}
</c:forEach><br>
</c:forEach>
The varStatus is there just for convenience ;)
To understand better what's all going on here, here's a plain Java translation:
for (Entry<String, List<Object>> entry : map.entrySet()) {
out.print("Key = " + entry.getKey() + ", values = ");
for (Iterator<Object> iter = entry.getValue().iterator(); iter.hasNext();) {
Object item = iter.next();
out.print(item + (iter.hasNext() ? ", " : ""));
}
out.println();
}
See also:
How to loop through a HashMap in JSP?
Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
How to loop over something a specified number of times in JSTL?
Did you try something like this?
<c:forEach var='item' items='${map}'>
<c:forEach var='arrayItem' items='${item.value}' />
...
</c:forEach>
</c:forEach>
you haven't closed c tag.try out this
<c:forEach items="${logMap}" var="entry">
Key = ${entry.key}, values =
<c:forEach items="${entry.value}" var="item" varStatus="loop">
${item} ${!loop.last ? ', ' : ''}
</c:forEach><br>
</c:forEach>
You can also loop round just the map.value its self if you know the key
<c:forEach var="value" items="${myMap[myObject.someInteger]}">
${value}
</c:forEach>

how to get values from jsp in ${clue.text}

I define a class of Clue :
Class Clue{
...
String text;
..
getter/setter method
}
I want to get ${clue.text} from jsp to use in the scope "<%...%>" to just show subSequence(0, 10),like this:
<c:forEach items="${clues}" var = "clue">
<tr>
<td>${clue.weibo.user.name}</td>
<td>
<%
String str = ${clue.weibo.text};
%>
<%=str.subSequence(0, 10) %>
</td>
</tr>
</c:forEach>
How can I do?
To access A JSTL variable in a scriplet:
<%
String str = (String)pageContext.getAttribute("clue.weibo.text", PageContext.REQUEST_SCOPE);
%>
However, a better way is to use JSTL functions to manipulate the string.
<%# taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<c:forEach items="${clues}" var = "clue">
<tr>
<td>${clue.weibo.user.name}</td>
<td>
${fn:substring(clue.weibo.text, 0, 10)}
</td>
</tr>
</c:forEach>

how to add arraylist in Jsp

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%=new Date() %>
<%
ArrayList al = new ArrayList();
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
%>
<select>
<option value="<%=al%>"></option>
</select>
</body>
</html>
This is my code i want to add Arraylist in drop down in Jsp I dont know how to Bind arraylist in html obtion or drop down please help me i have tried Much but unable to do this .
You have to use JSTL <forEach> to iterate through the elements and add it to the select-option . Probably make the List a scoped attribute . Populate the List object in the servlet, set it in request/session scope and forward the request to this JSP. Remember you can populate the List in the JSP itself and use pageScope to refer it , but that will be bad design in my opinion.
<select>
<c:forEach var="element" items="${al}">
<option value="${element}">${element}</option>
</c:forEach>
</select>
Here , al is the name of the attribute which stores the List in probably request or session scope.
Use JSTL in project :
Download the JSTL 1.2 jar .
Declare the taglib in JSP file for the JSTL core taglib.
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
If you want to use just the scriptlets(which is bad off course) :
<%
List<String> al = new ArrayList<String>();
al.add("C");
..........
...........
%>
<select>
<% for(String element: al) { %>
<option value="<%=element%>"><%=element%></option>
<% } %>
</select>
The above code will work if you have defined the List as List<String> , or else you need to cast the element to String.
Read How to avoid Java Code in JSP-Files?.
EDITED
Try this:
<%
ArrayList al = new ArrayList();
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
%>
<select>
<% for(int i = 0; i < al.size(); i++) {
String option = (String)al.get(i);
%>
<option value="<%= option %>"><%= option %></option>
<% } %>
</select>
</body>
</html>
Take a look at the tag in the core JSTL library.
Store the arraylist in pageScope.myList and loop as follows:
<select>
<c:forEach items="${pageScope.myList}" var="item" varStatus="status">
<option value='${item}'></option>
</c:forEach >
</select>
This is preferable than using scriptlets which are not considered good practice
Try this: declare your arraylist in between <%! … %>
<%! ArrayList al = new ArrayList(); %>

Displaying array values in jsp

I have following two array in my code
List<Double> centralityList = (List<Double>) request
.getAttribute("centralityList");
List<String> labelList = (List<String>) request
.getAttribute("labelList");.
Now I have six string values and corresponding 6 double values of the string in these two array. My question is how to display them in tabular format in my JSP?Is this possible
For Example:
label list contains [a,b,c,d,e]
centrality list contains- [4,6,8,9,0]
So now I want to display output like:
label list centrality list
a 4
b 6
c 8.
. .
etc
Yes of course you can. You can use scriplets but they are not recommended. Instead use JSTL.
Try this out:
Have this at top of your JSP:
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
And code for displaying data
<c:forEach begin="0" end="${fn:length(centralityList) - 1}" var="index">
<tr>
<td><c:out value="${centralityList[index]}"/></td>
<td><c:out value="${labelList[index]}"/></td>
</tr>
</c:forEach>
try this code
<%
List<Double> centralityList = (List<Double>) request
.getAttribute("centralityList");
List<String> labelList = (List<String>) request
.getAttribute("labelList");
String myString="";
%>
<table>
<tr><td>
<%
for(int i = 0; i < labelList.size(); i++)
{
out.println((String)labelList.get(i));
}
%>
</td><td>
<%
for(int i = 0; i < centralityList.size(); i++)
{
out.println((double)centralityList.get(i));
}
%>
</td>
</table>
You can achieve this eaisly by using JSTL which is even more easy and far better way but as in your code I didn't find any evidence of using JSTL , so this is the way for now
You can use JSTL tags and iterate through this-
<c:forEach var="Array" items="userNames">
// do something with the element
</c:forEach>
Use this in your jsp page
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

How to set default value for drop-down/select in JSP?

I have an arraylist for Strings eqArray.
I need to show it in a drop-down list for which I'm using the following in my JSP:
<%
for(int count=0;count<eqArray.size();count++){ %>
<option value="<%=eqArray.get(count)%>"><%=eqArray.get(count)%></option>
<%}
%>
I have an eqName String which is part of eqArray and should be the selected value by default.
How do I go about it without having to check and set the first option as eqName always?
<% for(int count=0; count<eqArray.size(); count++){ %>
<option value="<%= eqArray.get(count) %>" <%= (eqArray.get(count).equals("eqName"))?"selected":"" %> ><%= eqArray.get(count) %></option>
<%} %>
Change the index of eqName element to 0 in the array, or use a conditional Statement.
<%
for(int count=0; count < eqArray.size(); count++){ %>
<%if(eqArray.equals("eqName"){ %>
<option selected="selected" value="<%=eqArray.get(count)%>"><%=eqArray.get(count)%></option>
<%} %>
<option value="<%=eqArray.get(count)%>"><%=eqArray.get(count)%></option>
<%} %>
but use JSTL taglibs instead of using scriptlets.
You can do it via JQuery, which IMHO more clean:
<select data-selected="${eqName}">
<%
for(int count=0;count<eqArray.size();count++){ %>
<option value="<%=eqArray.get(count)%>"><%=eqArray.get(count)%></option>
<%}
%>
</select>
At the end of the page:
<script type="text/javascript">
$("select[data-selected]").each(function() {
var selected = $(this).data("selected");
$("select[data-selected='" + selected + "'] option[value='" + selected + "']").attr("selected", "selected");
})
</script>
By this way, you just need include the js at each of your page.
BTW, I recommend you to use JSTL and EL, which is more readable:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<select data-selected="${eqName}">
<c:forEach items="${eqArray}" var="model">
<option value="${model}">${model}</option>
</c:forEach>
</select>
You can implement these in two ways
By using jsp
" selected="selected" >
By Using Javascript at the end of the select box code
document.getElementById('selectBoxID').value=""
instead of selectBoxID id use the select box id

Categories