Friday, 10 November 2017

Dynamically fill the values in Selectbox from database in JSP.

When we work on form and websites, it is obvious to populate the data on page dynamically, means data from database. When data come from database, we don't know the number of data fetched from database.

So, we have to populate these data dynamically on page. Sometimes we have to populate these data on various form elements.

Selectbox/Listbox is one of the important element to show data on webpage. Today we will see, How we can populate data in selectbox in JSP?

I assume that you have done database connectivity in Java/JSP.

To insert value in selectbox from database, initialize the select element before the while loop of data fetching, then insert the valued fetched from database in option tag of select element in while loop.

See the code below -

select.jsp
<select name="select">
        <option>Rooms</option>
 <% 
 while(rs.next())
 {%>
 <option>
 <%out.println(rs.getString("room"));%>
 </option> 
 <%}%>
 </select>

Full example code is given below-

select.jsp
 1 <%@ page contentType="text/html; charset=iso-8859-1" language="java" import="java.sql.*" errorPage="" %>
 2  <%
 3        Connection conn = null;
 4  Statement stmt=null;
 5  try
 6  {
 7  Class.forName("com.mysql.jdbc.Driver");
 8  conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/DB","user","pass");
 9  stmt = conn.createStatement();
10  String sql="SELECT * FROM teacher";
11  ResultSet rs = stmt.executeQuery(sql);
12  %>
13  <select name="select">
14         <option>Rooms</option>
15  <% 
16  while(rs.next())
17  {%>
18  <option>
19  <%out.println(rs.getString("room"));%>
20  </option> 
21  <%}%>
22  </select>
23  <%rs.close();
24  stmt.close();
25  conn.close();
26  }
27  catch(Exception e)
28  {
29  out.println(e);
30  }
31  
32 %>
Output-

No comments:

Post a Comment

Change image source dynamically on hyperlink

 Changing image source dynamically using JQuery. Here in this example I have created there hyperlink and stored all images in the same folde...