Maya
Maya

Reputation: 41

JSP listbox and Servlet

In my application, am using 2 list boxes where i want to move selected items from one to another. I know to assign values to list box from database. But i don't know how to assign string array value from java file to html field. In my 'record.java' i have following code:

public class Report 
{
    private static String[] types = {
        "Value1",
        "Value2"
    };

    private static String[] fields = {
        "number1",
        "number2"
    };

    public static String[] getList() {
        return types;
    }

    public static String getFieldName(String description) {
        for(int i=0; i< fields.length; i++) {
            if (description.compareToIgnoreCase(types[i]) ==0)
                return fields[i];
        }
        return "";
    }
}

and i have my 'chart.jsp' file as follows:

<form  method="post">
            <fieldset>
                <legend>Chart Data</legend>
                <br/>
                <br/>
                <table >
                    <tbody>
                        <tr>
                            <td>
                              <select name="data" size="5" id="s">
                                 <option value=""></option>
                              </select>
                            </td>
                            <td> 
                                <input type="submit" value="<<"/>
                            </td>
                            <td>
                                <select name="data" size="5" id="d">
                                 <option value=""></option>
                                </select></td>
                         </tr>
                    </tbody>
                </table>
                <br/>
            </fieldset>
            <input class="submit" type="submit" value="Submit" />
        </form>

I am new to JSP. Can any one help me how to do this? Thank You....

Upvotes: 1

Views: 7748

Answers (1)

BalusC
BalusC

Reputation: 1109132

The getter method should not be static:

public String[] getList() {
    return types;
}

An instance of Report should be placed in request scope in doGet() method of the servlet:

Report report = loadItSomehow();
request.setAttribute("report", report);
request.getRequestDispatcher("page.jsp").forward(request, response);

This way it'll be available in JSP EL as ${report} and the list is available as ${report.list}. You can use JSTL c:forEach to iterate over an array or a List.

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
...
<select name="types" size="5">
    <c:forEach items="${report.list}" var="type">
        <option value="${type}">${type}</option>
    </c:forEach>
</select>

Note that you should not give independent input elements the same name.

Upvotes: 4

Related Questions