views:

620

answers:

2

Actually wat I need is: I have submitted some data in database from a html form. Then I have to load one column of that data in select tag of another form. I have done this but problem is that how will I increase the number of options as the number of records are increased.

Code is as follows

<%@ page import="java.util.*"%>  
<%@ page import="java.lang.*"%> 

<%!
    ArrayList al;
    Object o[];
    String s[] = new String[10];
%>

<jsp:useBean id="c" class="com.ebbeans.ViewBean"/>
<jsp:setProperty name="c" property="*"/>

<% 
    al = c.loadExistingEmpCode();
    o = al.toArray();

    for (int i = 0; i < o.length; i++) {
        s[i] = (String) o[i];
    }  
%>

    ..........
    ..........

        <select name="empCode" size="1" id="empCode">
            <option value="<%= s[0] %>" selected><%= s[0] %></option>
            <option value="<%= s[1] %>"><%= s[1] %></option>
            <option value="<%= s[2] %>"><%= s[2] %></option>
            <option value="<%= s[3] %>"><%= s[3] %></option>
            <option value="<%= s[4] %>"><%= s[4] %></option>
        </select>

Here only 5 options will be shown. How would I increase the number of options dynamically when the records are incresed?

A: 

I am a c# coder, but I believe you want something like this:

    <%@ page import="java.util."%>
    <%@ page import="java.lang."%> 
    <%! ArrayList al = c.loadExistingEmpCode(); 

       for(int i=0; i < ai.Count; i++)
       {

    %>

     <option><%= ai[0].toString() %></option>

   <% } %>
Chad Grant
A: 

To start off, do not use scriptlets in JSP. They are replaced by taglibs and EL since a decade. A commonly used taglib is JSTL which provides the <c:forEach> tag for exact this purpose. With EL you can seamlessly access back end data in JSP pages.

Here's an examlpe how your code is best to be replaced with.

Employee:

public class Employee {
    private Long code;
    private String name;
    // +getters +setters
}

EmployeeServlet:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    List<Employee> employees = employeeDAO.list();
    request.setAttribute("employees", employees);
    request.getRequestDispatcher("employees.jsp").forward(request, response);
}

employees.jsp:

<select name="employee">
    <c:forEach items="${employees}" var="employee">
        <option value="${employee.code}">${employee.name}</option>
    </c:forEach>
</select>

Map the EmployeeServlet on url-pattern of /employees/* and invoke it by http://example.com/contextroot/employees. Good luck and keep your JSP scriptletfree :)

BalusC